Skip to content

Commit

Permalink
Surround with try/catch reformats document
Browse files Browse the repository at this point in the history
Signed-off-by: Snjezana Peco <[email protected]>
  • Loading branch information
snjeza committed Sep 27, 2020
1 parent 8b7e12d commit 6ea9056
Show file tree
Hide file tree
Showing 9 changed files with 162 additions and 102 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ public void didChangeConfiguration(DidChangeConfigurationParams params) {
} catch (CoreException e) {
JavaLanguageServerPlugin.logException(e.getMessage(), e);
}
FormatterManager.configureFormatter(preferenceManager, pm);
FormatterManager.configureFormatter(preferenceManager.getPreferences());
logInfo(">> New configuration: " + settings);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URI;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
Expand All @@ -33,6 +33,7 @@
import org.eclipse.jdt.ls.core.internal.IConstants;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager;
import org.eclipse.jdt.ls.core.internal.preferences.Preferences;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
Expand Down Expand Up @@ -163,43 +164,40 @@ public static Map<String, String> readSettingsFromStream(InputSource inputSource
return handler.getSettings();
}

public static void configureFormatter(PreferenceManager preferenceManager, ProjectsManager projectsManager) {
String formatterUrl = preferenceManager.getPreferences().getFormatterUrl();
public static void configureFormatter(Preferences preferences) {
URI formatterUri = preferences.getFormatterAsURI();
Map<String, String> options = null;
if (formatterUrl != null) {
URL url = projectsManager.getUrl(formatterUrl);
if (url != null) {
try (InputStream inputStream = url.openStream()) {
InputSource inputSource = new InputSource(inputStream);
String profileName = preferenceManager.getPreferences().getFormatterProfileName();
options = FormatterManager.readSettingsFromStream(inputSource, profileName);
} catch (Exception e) {
JavaLanguageServerPlugin.logException(e.getMessage(), e);
}
} else {
JavaLanguageServerPlugin.logInfo("Invalid formatter:" + formatterUrl);
if (formatterUri != null) {
try (InputStream inputStream = formatterUri.toURL().openStream()) {
InputSource inputSource = new InputSource(inputStream);
String profileName = preferences.getFormatterProfileName();
options = FormatterManager.readSettingsFromStream(inputSource, profileName);
} catch (Exception e) {
JavaLanguageServerPlugin.logException(e.getMessage(), e);
}
}
if (options != null && !options.isEmpty()) {
setFormattingOptions(options);
setFormattingOptions(preferences, options);
} else {
Map<String, String> defaultOptions = DefaultCodeFormatterOptions.getEclipseDefaultSettings().getMap();
PreferenceManager.initializeJavaCoreOptions();
Hashtable<String, String> javaOptions = JavaCore.getOptions();
defaultOptions.forEach((k, v) -> {
javaOptions.put(k, v);
});
preferences.updateTabSizeInsertSpaces(javaOptions);
JavaCore.setOptions(javaOptions);
JavaLanguageServerPlugin.getPreferencesManager().initializeJavaCoreOptions();
}
}

private static void setFormattingOptions(Map<String, String> options) {
private static void setFormattingOptions(Preferences preferences, Map<String, String> options) {
Map<String, String> defaultOptions = DefaultCodeFormatterOptions.getEclipseDefaultSettings().getMap();
defaultOptions.putAll(options);
Hashtable<String, String> javaOptions = JavaCore.getOptions();
defaultOptions.entrySet().stream().filter(p -> p.getKey().startsWith(FORMATTER_OPTION_PREFIX)).forEach(p -> {
javaOptions.put(p.getKey(), p.getValue());
});
preferences.updateTabSizeInsertSpaces(javaOptions);
JavaCore.setOptions(javaOptions);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@
import static org.eclipse.jdt.ls.core.internal.JVMConfigurator.configureJVMSettings;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand Down Expand Up @@ -244,23 +242,6 @@ private static IWorkspaceRoot getWorkspaceRoot() {
return ResourcesPlugin.getWorkspace().getRoot();
}

public URL getUrl(String formatterUrl) {
URL url = null;
try {
url = new URL(ResourceUtils.toClientUri(formatterUrl));
} catch (MalformedURLException e1) {
File file = findFile(formatterUrl);
if (file != null && file.isFile()) {
try {
url = file.toURI().toURL();
} catch (MalformedURLException e) {
JavaLanguageServerPlugin.logInfo("Invalid formatter:" + formatterUrl);
}
}
}
return url;
}

@Override
public boolean isBuildFile(IResource resource) {
return buildSupports().filter(bs -> bs.isBuildFile(resource)).findAny().isPresent();
Expand Down Expand Up @@ -491,23 +472,6 @@ public static boolean setAutoBuilding(boolean enable) throws CoreException {
return changed;
}

public File findFile(String formatterUrl) {
File file = new File(formatterUrl);
if (file.exists()) {
return file;
}
Collection<IPath> rootPaths = preferenceManager.getPreferences().getRootPaths();
if (rootPaths != null) {
for (IPath rootPath : rootPaths) {
File f = new File(rootPath.toOSString(), formatterUrl);
if (f.isFile()) {
return f;
}
}
}
return null;
}

public void configureFilters(IProgressMonitor monitor) throws CoreException {
List<String> resourceFilters = preferenceManager.getPreferences().getResourceFilters();
if (resourceFilters != null && !resourceFilters.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand Down Expand Up @@ -217,22 +215,14 @@ public void fileChanged(String uriString, CHANGE_TYPE changeType) {
if (resource == null) {
return;
}
String formatterUrl = preferenceManager.getPreferences().getFormatterUrl();
if (formatterUrl != null) {
try {
URL url = getUrl(formatterUrl);
if (url != null) {
URI formatterUri = url.toURI();
URI uri = JDTUtils.toURI(uriString);
if (uri != null && uri.equals(formatterUri) && JavaLanguageServerPlugin.getInstance().getProtocol() != null) {
if (changeType == CHANGE_TYPE.DELETED || changeType == CHANGE_TYPE.CREATED) {
registerWatchers();
}
FormatterManager.configureFormatter(preferenceManager, this);
}
URI formatterUri = preferenceManager.getPreferences().getFormatterAsURI();
if (formatterUri != null) {
URI uri = JDTUtils.toURI(uriString);
if (uri != null && uri.equals(formatterUri) && JavaLanguageServerPlugin.getInstance().getProtocol() != null) {
if (changeType == CHANGE_TYPE.DELETED || changeType == CHANGE_TYPE.CREATED) {
registerWatchers();
}
} catch (URISyntaxException e) {
// ignore
FormatterManager.configureFormatter(preferenceManager.getPreferences());
}
}

Expand Down Expand Up @@ -367,12 +357,9 @@ public List<FileSystemWatcher> registerWatchers() {
JavaLanguageServerPlugin.logException(e.getMessage(), e);
}
List<FileSystemWatcher> fileWatchers = new ArrayList<>();
String formatterUrl = preferenceManager.getPreferences().getFormatterUrl();
if (formatterUrl != null) {
File file = new File(formatterUrl);
if (!file.isFile()) {
file = findFile(formatterUrl);
}
URI formatter = preferenceManager.getPreferences().getFormatterAsURI();
if (formatter != null && "file".equals(formatter.getScheme())) {
File file = new File(formatter);
if (file != null && file.isFile()) {
IPath formatterPath = new Path(file.getAbsolutePath());
if (!isContainedIn(formatterPath, sources)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.google.common.base.Objects;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
Expand Down Expand Up @@ -158,7 +157,7 @@ private static void reloadTemplateStore() {
private static boolean updateTemplate(String templateId, String content) {
Template template = templates.get(templateId);
if ((StringUtils.isEmpty(content) && template == null)
|| (template != null && Objects.equal(content, template.getPattern()))) {
|| (template != null && Objects.equals(content, template.getPattern()))) {
return false;
}

Expand All @@ -178,7 +177,6 @@ public void update(Preferences preferences) {
Preferences oldPreferences = this.preferences;
this.preferences = preferences;
preferencesChanged(oldPreferences, preferences); // listener will get latest preference from getPreferences()

// Update the templates according to the new preferences.
boolean templateChanged = false;
List<String> fileHeader = preferences.getFileHeaderTemplate();
Expand All @@ -191,7 +189,9 @@ public void update(Preferences preferences) {
if (templateChanged) {
reloadTemplateStore();
}

Hashtable<String, String> options = JavaCore.getOptions();
preferences.updateTabSizeInsertSpaces(options);
JavaCore.setOptions(options);
// TODO serialize preferences
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,16 @@
import static org.eclipse.jdt.ls.core.internal.handlers.MapFlattener.getString;
import static org.eclipse.jdt.ls.core.internal.handlers.MapFlattener.getValue;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
Expand All @@ -36,6 +40,8 @@
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.core.manipulation.CodeStyleConfiguration;
import org.eclipse.jdt.internal.core.manipulation.MembersOrderPreferenceCacheCommon;
import org.eclipse.jdt.ls.core.internal.IConstants;
Expand All @@ -57,6 +63,14 @@ public class Preferences {
* Specifies the folder path to the JDK .
*/
public static final String JAVA_HOME = "java.home";
/**
* Insert spaces when pressing Tab
*/
public static final String JAVA_CONFIGURATION_INSERTSPACES = "java.format.insertSpaces";
/**
* Tab Size
*/
public static final String JAVA_CONFIGURATION_TABSIZE = "java.format.tabSize";
/**
* Specifies Java Execution Environments.
*/
Expand Down Expand Up @@ -393,6 +407,7 @@ public class Preferences {
public static final String IMPLEMENTATION_ID = UUID.randomUUID().toString();
public static final String SELECTION_RANGE_ID = UUID.randomUUID().toString();
private static final String GRADLE_OFFLINE_MODE = "gradle.offline.mode";
private static final int DEFAULT_TAB_SIZE = 4;

private Map<String, Object> configuration;
private Severity incompleteClasspathSeverity;
Expand Down Expand Up @@ -458,6 +473,8 @@ public class Preferences {

private List<String> fileHeaderTemplate = new LinkedList<>();
private List<String> typeCommentTemplate = new LinkedList<>();
private boolean insertSpaces;
private int tabSize;

static {
JAVA_IMPORT_EXCLUSIONS_DEFAULT = new LinkedList<>();
Expand Down Expand Up @@ -630,6 +647,8 @@ public Preferences() {
staticImportOnDemandThreshold = IMPORTS_STATIC_ONDEMANDTHRESHOLD_DEFAULT;
referencedLibraries = JAVA_PROJECT_REFERENCED_LIBRARIES_DEFAULT;
resourceFilters = JAVA_RESOURCE_FILTERS_DEFAULT;
insertSpaces = true;
tabSize = DEFAULT_TAB_SIZE;
}

/**
Expand All @@ -652,6 +671,10 @@ public static Preferences createFrom(Map<String, Object> configuration) {

boolean importGradleEnabled = getBoolean(configuration, IMPORT_GRADLE_ENABLED, true);
prefs.setImportGradleEnabled(importGradleEnabled);
boolean insertSpaces = getBoolean(configuration, JAVA_CONFIGURATION_INSERTSPACES, true);
prefs.setInsertSpaces(insertSpaces);
int tabSize = getInt(configuration, JAVA_CONFIGURATION_TABSIZE, DEFAULT_TAB_SIZE);
prefs.setTabSize(tabSize);
boolean importGradleOfflineEnabled = getBoolean(configuration, IMPORT_GRADLE_OFFLINE_ENABLED, false);
prefs.setImportGradleOfflineEnabled(importGradleOfflineEnabled);
boolean gradleWrapperEnabled = getBoolean(configuration, GRADLE_WRAPPER_ENABLED, true);
Expand Down Expand Up @@ -1183,6 +1206,43 @@ public String getFormatterUrl() {
return formatterUrl;
}

public URI getFormatterAsURI() {
return asURI(formatterUrl);
}

private URI asURI(String formatterUrl) {
if (formatterUrl == null || formatterUrl.isBlank()) {
return null;
}
URI uri = null;
try {
uri = new URI(ResourceUtils.toClientUri(formatterUrl));
} catch (URISyntaxException e1) {
File file = findFile(formatterUrl);
if (file != null && file.isFile()) {
uri = file.toURI();
}
}
return uri;
}

private File findFile(String path) {
File file = new File(path);
if (file.exists()) {
return file;
}
Collection<IPath> rootPaths = getRootPaths();
if (rootPaths != null) {
for (IPath rootPath : rootPaths) {
File f = new File(rootPath.toOSString(), path);
if (f.isFile()) {
return f;
}
}
}
return null;
}

public List<String> getResourceFilters() {
return resourceFilters;
}
Expand Down Expand Up @@ -1461,4 +1521,33 @@ public Preferences setTypeCommentTemplate(List<String> typeCommentTemplate) {
this.typeCommentTemplate = typeCommentTemplate;
return this;
}

public Preferences setInsertSpaces(boolean insertSpaces) {
this.insertSpaces = insertSpaces;
return this;
}

public Preferences setTabSize(int tabSize) {
this.tabSize = tabSize;
return this;
}

public boolean isInsertSpaces() {
return insertSpaces;
}

public int getTabSize() {
return tabSize;
}

public void updateTabSizeInsertSpaces(Hashtable<String, String> options) {
if (options == null) {
return;
}
if (tabSize > 0) {
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, String.valueOf(tabSize));
}
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, insertSpaces ? JavaCore.SPACE : JavaCore.TAB);
}

}
Loading

0 comments on commit 6ea9056

Please sign in to comment.