/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
for (Map.Entry<HighlightSeverity, HighlightDisplayLevel> entry : ourMap.entrySet()) {
HighlightSeverity severity = entry.getKey();
HighlightDisplayLevel displayLevel = entry.getValue();
- if (Comparing.strEqual(severity.toString(), name)) {
+ if (Comparing.strEqual(severity.getName(), name)) {
return displayLevel;
}
}
return mySeverity.toString();
}
+ @NotNull
+ public String getName() {
+ return mySeverity.getName();
+ }
+
public Icon getIcon() {
return myIcon;
}
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* if two annotations with different severity levels cover the same text range, only
* the annotation with a higher severity level is displayed.
*/
- public HighlightSeverity(@NonNls String name, int val) {
+ public HighlightSeverity(@NonNls @NotNull String name, int val) {
myName = name;
myVal = val;
}
//read external only
public HighlightSeverity(@NotNull Element element) {
- myName = JDOMExternalizerUtil.readField(element, "myName");
- myVal = Integer.valueOf(JDOMExternalizerUtil.readField(element, "myVal"));
+ this(JDOMExternalizerUtil.readField(element, "myName"), Integer.valueOf(JDOMExternalizerUtil.readField(element, "myVal")));
}
public String toString() {
public int hashCode() {
return myName.hashCode();
}
+
+ @NotNull
+ public String getName() {
+ return myName;
+ }
}
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
+import com.intellij.util.concurrency.AtomicFieldUpdater;
+import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.util.containers.ContainerUtil;
-import gnu.trove.THashMap;
import gnu.trove.TObjectIntHashMap;
import gnu.trove.TObjectIntProcedure;
import org.jdom.Element;
public class SeverityRegistrar implements JDOMExternalizable, Comparator<HighlightSeverity> {
@NonNls private static final String INFO_TAG = "info";
@NonNls private static final String COLOR_ATTRIBUTE = "color";
- private final Map<String, SeverityBasedTextAttributes> myMap = new THashMap<String, SeverityBasedTextAttributes>();
- private final Map<String, Color> myRendererColors = new THashMap<String, Color>();
+ private final Map<String, SeverityBasedTextAttributes> myMap = new ConcurrentHashMap<String, SeverityBasedTextAttributes>();
+ private final Map<String, Color> myRendererColors = new ConcurrentHashMap<String, Color>();
- private final OrderMap myOrder = new OrderMap();
+ private volatile OrderMap myOrderMap;
private JDOMExternalizableStringList myReadOrder;
- private static final Map<String, HighlightInfoType> STANDARD_SEVERITIES = new THashMap<String, HighlightInfoType>();
+ private static final Map<String, HighlightInfoType> STANDARD_SEVERITIES = new ConcurrentHashMap<String, HighlightInfoType>();
public SeverityRegistrar() {
}
}
public static void registerStandard(@NotNull HighlightInfoType highlightInfoType, @NotNull HighlightSeverity highlightSeverity) {
- STANDARD_SEVERITIES.put(highlightSeverity.toString(), highlightInfoType);
+ STANDARD_SEVERITIES.put(highlightSeverity.getName(), highlightInfoType);
}
@NotNull
: InspectionProjectProfileManager.getInstance(project).getSeverityRegistrar();
}
- public void registerSeverity(@NotNull SeverityBasedTextAttributes info, Color renderColor){
+ public void registerSeverity(@NotNull SeverityBasedTextAttributes info, Color renderColor) {
final HighlightSeverity severity = info.getType().getSeverity(null);
- myMap.put(severity.toString(), info);
- myRendererColors.put(severity.toString(), renderColor);
- myOrder.clear();
+ myMap.put(severity.getName(), info);
+ myRendererColors.put(severity.getName(), renderColor);
+ myOrderMap = null;
HighlightDisplayLevel.registerSeverity(severity, renderColor);
}
-
public SeverityBasedTextAttributes unregisterSeverity(@NotNull HighlightSeverity severity){
- return myMap.remove(severity.toString());
+ return myMap.remove(severity.getName());
}
@NotNull
public HighlightInfoType.HighlightInfoTypeImpl getHighlightInfoTypeBySeverity(@NotNull HighlightSeverity severity) {
- HighlightInfoType infoType = STANDARD_SEVERITIES.get(severity.toString());
+ HighlightInfoType infoType = STANDARD_SEVERITIES.get(severity.getName());
if (infoType != null) {
return (HighlightInfoType.HighlightInfoTypeImpl)infoType;
}
return (HighlightInfoType.HighlightInfoTypeImpl)HighlightInfoType.INFORMATION;
}
- final SeverityBasedTextAttributes type = myMap.get(severity.toString());
- return (HighlightInfoType.HighlightInfoTypeImpl)(type != null ? type.getType() : HighlightInfoType.WARNING);
+ final SeverityBasedTextAttributes type = getAttributesBySeverity(severity);
+ return (HighlightInfoType.HighlightInfoTypeImpl)(type == null ? HighlightInfoType.WARNING : type.getType());
+ }
+
+ private SeverityBasedTextAttributes getAttributesBySeverity(@NotNull HighlightSeverity severity) {
+ return myMap.get(severity.getName());
}
@Nullable
public TextAttributes getTextAttributesBySeverity(@NotNull HighlightSeverity severity) {
- final SeverityBasedTextAttributes infoType = myMap.get(severity.toString());
+ final SeverityBasedTextAttributes infoType = getAttributesBySeverity(severity);
if (infoType != null) {
return infoType.getAttributes();
}
}
registerSeverity(highlightInfo, color);
}
- myOrder.clear();
-
myReadOrder = new JDOMExternalizableStringList();
myReadOrder.readExternal(element);
+
+ OrderMap orderMap = new OrderMap(myReadOrder.size());
for (int i = 0; i < myReadOrder.size(); i++) {
String name = myReadOrder.get(i);
HighlightSeverity severity = getSeverity(name);
if (severity == null) continue;
- myOrder.put(severity, i);
+ orderMap.put(severity, i);
}
final List<HighlightSeverity> knownSeverities = getDefaultOrder();
- myOrder.retainEntries(new TObjectIntProcedure<HighlightSeverity>() {
+ orderMap.retainEntries(new TObjectIntProcedure<HighlightSeverity>() {
@Override
public boolean execute(HighlightSeverity severity, int order) {
return knownSeverities.contains(severity);
}
});
- if (myOrder.isEmpty()) {
- setFromList(knownSeverities);
+ if (orderMap.isEmpty()) {
+ orderMap = fromList(knownSeverities);
}
- //enforce include all known
- List<HighlightSeverity> list = getOrderAsList();
- for (int i = 0; i < knownSeverities.size(); i++) {
- HighlightSeverity stdSeverity = knownSeverities.get(i);
- if (!list.contains(stdSeverity)) {
- for (int oIdx = 0; oIdx < list.size(); oIdx++) {
- HighlightSeverity orderSeverity = list.get(oIdx);
- HighlightInfoType type = STANDARD_SEVERITIES.get(orderSeverity.toString());
- if (type != null && knownSeverities.indexOf(type.getSeverity(null)) > i) {
- list.add(oIdx, stdSeverity);
- myReadOrder = null;
- break;
+ else {
+ //enforce include all known
+ List<HighlightSeverity> list = getOrderAsList(orderMap);
+ for (int i = 0; i < knownSeverities.size(); i++) {
+ HighlightSeverity stdSeverity = knownSeverities.get(i);
+ if (!list.contains(stdSeverity)) {
+ for (int oIdx = 0; oIdx < list.size(); oIdx++) {
+ HighlightSeverity orderSeverity = list.get(oIdx);
+ HighlightInfoType type = STANDARD_SEVERITIES.get(orderSeverity.getName());
+ if (type != null && knownSeverities.indexOf(type.getSeverity(null)) > i) {
+ list.add(oIdx, stdSeverity);
+ myReadOrder = null;
+ break;
+ }
}
}
}
+ orderMap = fromList(list);
}
- setFromList(list);
+ myOrderMap = orderMap;
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
- List<HighlightSeverity> list = getOrderAsList();
- for (HighlightSeverity s : list) {
+ List<HighlightSeverity> list = getOrderAsList(getOrderMap());
+ for (HighlightSeverity severity : list) {
Element info = new Element(INFO_TAG);
- String severity = s.toString();
- final SeverityBasedTextAttributes infoType = myMap.get(severity);
+ String severityName = severity.getName();
+ final SeverityBasedTextAttributes infoType = getAttributesBySeverity(severity);
if (infoType != null) {
infoType.writeExternal(info);
- final Color color = myRendererColors.get(severity);
+ final Color color = myRendererColors.get(severityName);
if (color != null) {
info.setAttribute(COLOR_ATTRIBUTE, Integer.toString(color.getRGB() & 0xFFFFFF, 16));
}
myReadOrder.writeExternal(element);
}
else if (!getDefaultOrder().equals(list)) {
- final JDOMExternalizableStringList ext = new JDOMExternalizableStringList(Collections.nCopies(myOrder.size(), ""));
- myOrder.forEachEntry(new TObjectIntProcedure<HighlightSeverity>() {
+ final JDOMExternalizableStringList ext = new JDOMExternalizableStringList(Collections.nCopies(getOrderMap().size(), ""));
+ getOrderMap().forEachEntry(new TObjectIntProcedure<HighlightSeverity>() {
@Override
public boolean execute(HighlightSeverity orderSeverity, int oIdx) {
- ext.set(oIdx, orderSeverity.toString());
+ ext.set(oIdx, orderSeverity.getName());
return true;
}
});
}
@NotNull
- private List<HighlightSeverity> getOrderAsList() {
+ private List<HighlightSeverity> getOrderAsList(@NotNull OrderMap orderMap) {
List<HighlightSeverity> list = new ArrayList<HighlightSeverity>();
- for (Object o : getOrder().keys()) {
+ for (Object o : orderMap.keys()) {
list.add((HighlightSeverity)o);
}
Collections.sort(list, this);
}
public int getSeveritiesCount() {
- return createCurrentSeverities().size();
+ return createCurrentSeverityNames().size();
}
public HighlightSeverity getSeverityByIndex(final int i) {
final HighlightSeverity[] found = new HighlightSeverity[1];
- getOrder().forEachEntry(new TObjectIntProcedure<HighlightSeverity>() {
+ getOrderMap().forEachEntry(new TObjectIntProcedure<HighlightSeverity>() {
@Override
public boolean execute(HighlightSeverity severity, int order) {
if (order == i) {
}
public int getSeverityMaxIndex() {
- int[] values = getOrder().getValues();
+ int[] values = getOrderMap().getValues();
int max = values[0];
for(int i = 1; i < values.length; ++i) if (values[i] > max) max = values[i];
}
@NotNull
- private List<String> createCurrentSeverities() {
+ private List<String> createCurrentSeverityNames() {
List<String> list = new ArrayList<String>();
list.addAll(STANDARD_SEVERITIES.keySet());
list.addAll(myMap.keySet());
return level.getIcon();
}
- return HighlightDisplayLevel.createIconByMask(myRendererColors.get(severity.toString()));
+ return HighlightDisplayLevel.createIconByMask(myRendererColors.get(severity.getName()));
}
- public boolean isSeverityValid(@NotNull String severity) {
- return createCurrentSeverities().contains(severity);
+ public boolean isSeverityValid(@NotNull String severityName) {
+ return createCurrentSeverityNames().contains(severityName);
}
@Override
public int compare(final HighlightSeverity s1, final HighlightSeverity s2) {
- OrderMap order = getOrder();
- int o1 = order.getOrder(s1, -1);
- int o2 = order.getOrder(s2, -1);
+ OrderMap orderMap = getOrderMap();
+ int o1 = orderMap.getOrder(s1, -1);
+ int o2 = orderMap.getOrder(s2, -1);
return o1 - o2;
}
@NotNull
- private OrderMap getOrder() {
- if (myOrder.isEmpty()) {
- List<HighlightSeverity> order = getDefaultOrder();
- setFromList(order);
+ private OrderMap getOrderMap() {
+ OrderMap orderMap;
+ OrderMap defaultOrder = null;
+ while ((orderMap = myOrderMap) == null) {
+ if (defaultOrder == null) {
+ defaultOrder = fromList(getDefaultOrder());
+ }
+ boolean replaced = ORDER_MAP_UPDATER.compareAndSet(this, null, defaultOrder);
+ if (replaced) {
+ orderMap = defaultOrder;
+ break;
+ }
}
- return myOrder;
+ return orderMap;
}
- private void setFromList(@NotNull List<HighlightSeverity> order) {
- myOrder.clear();
- for (int i = 0; i < order.size(); i++) {
- HighlightSeverity severity = order.get(i);
- myOrder.put(severity, i);
+ private static final AtomicFieldUpdater<SeverityRegistrar, OrderMap> ORDER_MAP_UPDATER = AtomicFieldUpdater.forFieldOfType(SeverityRegistrar.class, OrderMap.class);
+
+ @NotNull
+ private static OrderMap fromList(@NotNull List<HighlightSeverity> orderList) {
+ OrderMap orderMap = new OrderMap(orderList.size());
+ for (int i = 0; i < orderList.size(); i++) {
+ HighlightSeverity severity = orderList.get(i);
+ orderMap.put(severity, i);
}
+ orderMap.trimToSize();
+ return orderMap;
}
@NotNull
return order;
}
- public void setOrder(@NotNull List<HighlightSeverity> order) {
- setFromList(order);
+ public void setOrder(@NotNull List<HighlightSeverity> orderList) {
+ myOrderMap = fromList(orderList);
myReadOrder = null;
}
public int getSeverityIdx(@NotNull HighlightSeverity severity) {
- return getOrder().getOrder(severity, -1);
+ return getOrderMap().getOrder(severity, -1);
}
public boolean isDefaultSeverity(@NotNull HighlightSeverity severity) {
}
private static class OrderMap extends TObjectIntHashMap<HighlightSeverity> {
+ private OrderMap(int initialCapacity) {
+ super(initialCapacity);
+ }
+
private int getOrder(@NotNull HighlightSeverity severity, int defaultOrder) {
int index = index(severity);
return index < 0 ? defaultOrder : _values[index];
//read external
public SeverityBasedTextAttributes(@NotNull Element element) throws InvalidDataException {
- myAttributes = new TextAttributes(element);
- myType = new HighlightInfoType.HighlightInfoTypeImpl(element);
+ this(new TextAttributes(element), new HighlightInfoType.HighlightInfoTypeImpl(element));
}
- public SeverityBasedTextAttributes(final TextAttributes attributes, final HighlightInfoType.HighlightInfoTypeImpl type) {
+ public SeverityBasedTextAttributes(@NotNull TextAttributes attributes, @NotNull HighlightInfoType.HighlightInfoTypeImpl type) {
myAttributes = attributes;
myType = type;
}
+ @NotNull
public TextAttributes getAttributes() {
return myAttributes;
}
+ @NotNull
public HighlightInfoType.HighlightInfoTypeImpl getType() {
return myType;
}
- private void writeExternal(Element element) throws WriteExternalException {
+ private void writeExternal(@NotNull Element element) throws WriteExternalException {
myAttributes.writeExternal(element);
myType.writeExternal(element);
}
final SeverityBasedTextAttributes that = (SeverityBasedTextAttributes)o;
- if (myAttributes != null ? !myAttributes.equals(that.myAttributes) : that.myAttributes != null) return false;
- if (myType != null ? !myType.equals(that.myType) : that.myType != null) return false;
+ if (!myAttributes.equals(that.myAttributes)) return false;
+ if (!myType.equals(that.myType)) return false;
return true;
}
public int hashCode() {
- int result = myAttributes != null ? myAttributes.hashCode() : 0;
- result = 31 * result + (myType != null ? myType.hashCode() : 0);
+ int result = myAttributes.hashCode();
+ result = 31 * result + myType.hashCode();
return result;
}
}
Collection<HighlightInfoType> standardSeverities() {
return STANDARD_SEVERITIES.values();
}
-
}
Project project = element == null ? null : element.getProject();
final ToolsImpl tools = getTools(inspectionToolKey.toString(), project);
HighlightDisplayLevel level = tools != null ? tools.getLevel(element) : HighlightDisplayLevel.WARNING;
- if (!((SeverityProvider)getProfileManager()).getOwnSeverityRegistrar().isSeverityValid(level.getSeverity().toString())) {
+ if (!((SeverityProvider)getProfileManager()).getOwnSeverityRegistrar().isSeverityValid(level.getSeverity().getName())) {
level = HighlightDisplayLevel.WARNING;
setErrorLevel(inspectionToolKey, level, project);
}
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
for (ScopeToolState state : myTools) {
final Element scopeElement = new Element("scope");
scopeElement.setAttribute("name", state.getScopeName());
- scopeElement.setAttribute(LEVEL_ATTRIBUTE, state.getLevel().toString());
+ scopeElement.setAttribute(LEVEL_ATTRIBUTE, state.getLevel().getName());
scopeElement.setAttribute(ENABLED_ATTRIBUTE, Boolean.toString(state.isEnabled()));
InspectionToolWrapper toolWrapper = state.getTool();
if (toolWrapper.isInitialized()) {
}
}
inspectionElement.setAttribute(ENABLED_ATTRIBUTE, Boolean.toString(isEnabled()));
- inspectionElement.setAttribute(LEVEL_ATTRIBUTE, getLevel().toString());
+ inspectionElement.setAttribute(LEVEL_ATTRIBUTE, getLevel().getName());
inspectionElement.setAttribute(ENABLED_BY_DEFAULT_ATTRIBUTE, Boolean.toString(myDefaultState.isEnabled()));
InspectionToolWrapper toolWrapper = myDefaultState.getTool();
if (toolWrapper.isInitialized()) {
private volatile SoftReference<String> myTextString;
private boolean myIsReadOnly = false;
- private boolean isStripTrailingSpacesEnabled = true;
+ private volatile boolean isStripTrailingSpacesEnabled = true;
private volatile long myModificationStamp;
private final PropertyChangeSupport myPropertyChangeSupport = new PropertyChangeSupport(this);
*/
public class CharTableImpl implements CharTable {
private static final int INTERN_THRESHOLD = 40; // 40 or more characters long tokens won't be interned.
- private static final CharSequenceHashingStrategy HASHER = new CharSequenceHashingStrategy();
+ private static final CharSequenceHashingStrategy HASHER = CharSequenceHashingStrategy.CASE_SENSITIVE;
private static final OpenTHashSet<CharSequence> STATIC_ENTRIES = newStaticSet();
private final OpenTHashSet<CharSequence> entries = new OpenTHashSet<CharSequence>(10, 0.9f, HASHER);
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
};
boolean success = processFilesWithText(scope, searchContext, caseSensitively, text, processor);
- LOG.assertTrue(success);
+ // success == false means exception in index
}
finally {
myManager.finishBatchFilesProcessingMode();
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
@Nullable
- public static Language reallyEvaluateLanguageInRange(final int start, final int end, final PsiFile file) {
+ public static Language reallyEvaluateLanguageInRange(final int start, final int end, @NotNull PsiFile file) {
+ if (file instanceof PsiBinaryFile) {
+ return file.getLanguage();
+ }
Language lang = null;
int curOffset = start;
do {
}
@Nullable
- public static Language evaluateLanguageInRange(final int start, final int end, final PsiFile file) {
+ public static Language evaluateLanguageInRange(final int start, final int end, @NotNull PsiFile file) {
PsiElement elt = getElementAtOffset(file, start);
TextRange selectionRange = new TextRange(start, end);
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
if (textAttributes != null) {
return new SeverityRegistrar.SeverityBasedTextAttributes(textAttributes, (HighlightInfoType.HighlightInfoTypeImpl)type);
}
- return new SeverityRegistrar.SeverityBasedTextAttributes(registrar.getTextAttributesBySeverity(type.getSeverity(null)), (HighlightInfoType.HighlightInfoTypeImpl)type);
+ TextAttributes severity = registrar.getTextAttributesBySeverity(type.getSeverity(null));
+ return new SeverityRegistrar.SeverityBasedTextAttributes(severity, (HighlightInfoType.HighlightInfoTypeImpl)type);
}
}
if (status.errorCount[i] > 0) {
final HighlightSeverity severity = SeverityRegistrar.getSeverityRegistrar(myTrafficLightRenderer.getProject()).getSeverityByIndex(i);
String name =
- status.errorCount[i] > 1 ? StringUtil.pluralize(severity.toString().toLowerCase()) : severity.toString().toLowerCase();
+ status.errorCount[i] > 1 ? StringUtil.pluralize(severity.getName().toLowerCase()) : severity.getName().toLowerCase();
text += status.errorAnalyzingFinished
? DaemonBundle.message("errors.found", status.errorCount[i], name)
: DaemonBundle.message("errors.found.so.far", status.errorCount[i], name);
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public void run() {
final PsiFile injected;
try {
- injected = psiFile == null || psiFile instanceof PsiCompiledElement || isReallyDisposed(editor, project)
+ injected = psiFile == null || psiFile instanceof PsiCompiledElement || psiFile instanceof PsiBinaryFile || isReallyDisposed(editor, project)
? null : getInjectedFileIfAny(editor, project, offset, psiFile, alarm);
}
catch (RuntimeException e) {
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Editor editor = event.getEditor();
if (editor.getProject() != null && editor.getProject() != myProject) return;
if (myProject.isDisposed() || !myProject.isOpen()) return;
- TemplateState tState = getTemplateState(editor);
- if (tState != null) {
- tState.gotoEnd();
+ TemplateState state = getTemplateState(editor);
+ if (state != null) {
+ state.gotoEnd();
}
- editor.putUserData(TEMPLATE_STATE_KEY, null);
+ clearTemplateState(editor);
}
};
EditorFactory.getInstance().addEditorFactoryListener(myEditorFactoryListener, myProject);
});
}
- private static void disposeState(final TemplateState tState) {
- Disposer.dispose(tState);
+ private static void disposeState(@NotNull TemplateState state) {
+ Disposer.dispose(state);
}
@Override
}
@Nullable
- public static TemplateState getTemplateState(Editor editor) {
+ public static TemplateState getTemplateState(@NotNull Editor editor) {
return editor.getUserData(TEMPLATE_STATE_KEY);
}
- void clearTemplateState(final Editor editor) {
+ static void clearTemplateState(@NotNull Editor editor) {
TemplateState prevState = getTemplateState(editor);
if (prevState != null) {
disposeState(prevState);
editor.putUserData(TEMPLATE_STATE_KEY, null);
}
- private TemplateState initTemplateState(final Editor editor) {
+ private TemplateState initTemplateState(@NotNull Editor editor) {
clearTemplateState(editor);
TemplateState state = new TemplateState(myProject, editor);
Disposer.register(this, state);
final Document document = editor.getDocument();
final CharSequence text = document.getCharsSequence();
- if (template2argument == null || template2argument.size() == 0) {
+ if (template2argument == null || template2argument.isEmpty()) {
return null;
}
if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), myProject)) {
@Nullable Character shortcutChar,
TemplateSettings settings,
boolean hasArgument) {
- String key;
List<TemplateImpl> candidates = Collections.emptyList();
for (int i = settings.getMaxKeyLength(); i >= 1; i--) {
int wordStart = caretOffset - i;
if (wordStart < 0) {
continue;
}
- key = text.subSequence(wordStart, caretOffset).toString();
+ String key = text.subSequence(wordStart, caretOffset).toString();
if (Character.isJavaIdentifierStart(key.charAt(0))) {
if (wordStart > 0 && Character.isJavaIdentifierPart(text.charAt(wordStart - 1))) {
continue;
final TemplateContextType[] typeCollection = getAllContextTypes();
LinkedList<TemplateContextType> userDefinedExtensionsFirst = new LinkedList<TemplateContextType>();
for (TemplateContextType contextType : typeCollection) {
- if (contextType.getClass().getName().startsWith("com.intellij.codeInsight.template")) {
+ if (contextType.getClass().getName().startsWith(Template.class.getPackage().getName())) {
userDefinedExtensionsFirst.addLast(contextType);
}
else {
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
private boolean myFinished;
@Nullable private PairProcessor<String, String> myProcessor;
private boolean mySelectionCalculated = false;
+ private boolean myStarted;
public TemplateState(@NotNull Project project, final Editor editor) {
myProject = project;
final LookupImpl lookup = myEditor != null ? (LookupImpl)LookupManager.getActiveLookup(myEditor) : null;
if (lookup != null) {
lookup.performGuardedChange(runnable);
- } else {
+ }
+ else {
runnable.run();
}
}
}
};
- myDocument.addDocumentListener(myEditorDocumentListener);
- CommandProcessor.getInstance().addCommandListener(myCommandListener);
+ myDocument.addDocumentListener(myEditorDocumentListener, this);
+ CommandProcessor.getInstance().addCommandListener(myCommandListener, this);
}
@Override
public synchronized void dispose() {
- if (myEditorDocumentListener != null) {
- myDocument.removeDocumentListener(myEditorDocumentListener);
- myEditorDocumentListener = null;
- }
- if (myCommandListener != null) {
- CommandProcessor.getInstance().removeCommandListener(myCommandListener);
- myCommandListener = null;
- }
+ myEditorDocumentListener = null;
+ myCommandListener = null;
myProcessor = null;
//Avoid the leak of the editor
- releaseEditor();
+ releaseAll();
myDocument = null;
}
private void setCurrentVariableNumber(int variableNumber) {
myCurrentVariableNumber = variableNumber;
- final boolean isFinished = variableNumber < 0;
+ final boolean isFinished = isFinished();
((DocumentEx)myDocument).setStripTrailingSpacesEnabled(isFinished);
myCurrentSegmentNumber = isFinished ? -1 : getCurrentSegmentNumber();
}
}
}
- public void start(TemplateImpl template,
+ public void start(@NotNull TemplateImpl template,
@Nullable final PairProcessor<String, String> processor,
@Nullable Map<String, String> predefinedVarValues) {
+ LOG.assertTrue(!myStarted, "Already started");
+ myStarted = true;
myTemplate = template;
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
}
}
- private void processAllExpressions(final TemplateImpl template) {
+ private void processAllExpressions(@NotNull final TemplateImpl template) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
});
}
- public void doReformat(final TextRange range) {
+ private void doReformat(final TextRange range) {
RangeMarker rangeMarker = null;
if (range != null) {
rangeMarker = myDocument.createRangeMarker(range);
}
}
+ boolean isDisposed() {
+ return myDocument == null;
+ }
+
private void cleanupTemplateState(boolean brokenOff) {
final Editor editor = myEditor;
fireBeforeTemplateFinished();
int oldVar = myCurrentVariableNumber;
- setCurrentVariableNumber(-1);
currentVariableChanged(oldVar);
- ((TemplateManagerImpl)TemplateManager.getInstance(myProject)).clearTemplateState(editor);
- fireTemplateFinished(brokenOff);
+ if (!isDisposed()) {
+ setCurrentVariableNumber(-1);
+ TemplateManagerImpl.clearTemplateState(editor);
+ fireTemplateFinished(brokenOff);
+ }
myListeners.clear();
myProject = null;
}
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
-import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
final Component rendererComponent = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof SeverityBasedTextAttributes) {
- setText(((SeverityBasedTextAttributes)value).getSeverity().toString());
+ setText(((SeverityBasedTextAttributes)value).getSeverity().getName());
}
return rendererComponent;
}
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public int compare(HighlightDisplayLevel o1, HighlightDisplayLevel o2) {
final int severityDiff = o1.getSeverity().compareTo(o2.getSeverity());
if (severityDiff == 0) {
- return o1.toString().compareTo(o2.toString());
+ return o1.getName().compareTo(o2.getName());
}
return severityDiff;
}
}
static String renderSeverity(HighlightSeverity severity) {
- return StringUtil.capitalizeWords(severity.toString().toLowerCase(), true);
+ return StringUtil.capitalizeWords(severity.getName().toLowerCase(), true);
}
private void toggleToolNode(final InspectionConfigTreeNode toolNode) {
final Set<HighlightSeverity> severities = ((InspectionProfileImpl)selectedProfile).getUsedSeverities();
for (Iterator<HighlightSeverity> iterator = severities.iterator(); iterator.hasNext();) {
HighlightSeverity severity = iterator.next();
- if (registrar.isSeverityValid(severity.toString())) {
+ if (registrar.isSeverityValid(severity.getName())) {
iterator.remove();
}
}
if (!severities.isEmpty()) {
final SeverityRegistrar oppositeRegister = ((SeverityProvider)selectedProfile.getProfileManager()).getSeverityRegistrar();
for (HighlightSeverity severity : severities) {
- final TextAttributesKey attributesKey = TextAttributesKey.find(severity.toString());
+ final TextAttributesKey attributesKey = TextAttributesKey.find(severity.getName());
final TextAttributes textAttributes = oppositeRegister.getTextAttributesBySeverity(severity);
- LOG.assertTrue(textAttributes != null, severity.toString());
+ LOG.assertTrue(textAttributes != null, severity);
HighlightInfoType.HighlightInfoTypeImpl info = new HighlightInfoType.HighlightInfoTypeImpl(severity, attributesKey);
registrar.registerSeverity(new SeverityRegistrar.SeverityBasedTextAttributes(textAttributes.clone(), info),
textAttributes.getErrorStripeColor());
factory.init((KeyStore)null);
// assume that only X509 TrustManagers exist
X509TrustManager systemManager = findX509TrustManager(factory.getTrustManagers());
+ assert systemManager != null;
+
+ // can also check, that default trust store exists, on this step
+ //assert systemManager.getAcceptedIssuers().length != 0
MutableX509TrustManager customManager = new MutableX509TrustManager(myCacertsPath, myPassword);
MyX509TrustManager trustManager = new MyX509TrustManager(systemManager, customManager);
try {
mySystemManager.checkServerTrusted(certificates, s);
}
- catch (CertificateException e1) {
+ catch (RuntimeException e) {
+ Throwable cause = e.getCause();
+ // this can happen on some version of Apple's JRE, e.g. see IDEA-115565
+ if (cause != null && cause.getMessage().equals("the trustAnchors parameter must be non-empty")) {
+ LOG.error("It seems, that your JRE installation doesn't have system trust store.\n" +
+ "If you're using Mac JRE, try upgrading to the latest version.", e);
+ }
+ }
+ catch (CertificateException e) {
X509Certificate certificate = certificates[0];
// looks like self-signed certificate
if (certificates.length == 1) {
}
catch (CertificateException e2) {
if (myCustomManager.isBroken() || !updateTrustStore(certificate)) {
- throw e1;
+ throw e;
}
}
}
? new MyDialogWrapper(myParentWindow, myShouldShowCancel)
: new MyDialogWrapper(myProject, myShouldShowCancel);
myPopup.setUndecorated(true);
+ if (SystemInfo.isAppleJvm) {
+ // With Apple JDK we look for MacMessage parent by the window title.
+ // As far as progress windows are undecorated we set the window
+ // component name as a title to keep it unique.
+ myPopup.setTitle(myPopup.getWindow().getName());
+ }
if (myPopup.getPeer() instanceof DialogWrapperPeerImpl) {
((DialogWrapperPeerImpl)myPopup.getPeer()).setAutoRequestFocus(false);
}
}
}
- protected void beforeFileRename(VirtualFile file, Object requestor, String oldName, String newName) {
+ protected void beforeFileRename(@NotNull VirtualFile file, Object requestor, @NotNull String oldName, @NotNull String newName) {
fireBeforePropertyChange(requestor, file, VirtualFile.PROP_NAME, oldName, newName);
myCachedFiles.remove(file.getPath());
}
/*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
- final VirtualFileDirectoryImpl dir = ((VirtualFileDirectoryImpl)vDir);
+ final VirtualFileDirectoryImpl dir = (VirtualFileDirectoryImpl)vDir;
VirtualFileImpl child = new VirtualFileDataImpl(this, dir, fileName);
dir.addChild(child);
fireFileCreated(requestor, child);
@Override
@NotNull
public VirtualFile createChildDirectory(Object requestor, @NotNull VirtualFile vDir, @NotNull String dirName) throws IOException {
- final VirtualFileDirectoryImpl dir = ((VirtualFileDirectoryImpl)vDir);
+ final VirtualFileDirectoryImpl dir = (VirtualFileDirectoryImpl)vDir;
VirtualFileImpl child = new VirtualFileDirectoryImpl(this, dir, dirName);
dir.addChild(child);
fireFileCreated(requestor, child);
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
class VirtualFileImpl extends HttpVirtualFile {
private final HttpFileSystemBase myFileSystem;
- private final @Nullable RemoteFileInfoImpl myFileInfo;
+ @Nullable private final RemoteFileInfoImpl myFileInfo;
private FileType myInitialFileType;
private final String myPath;
private final String myParentPath;
private final String myName;
- VirtualFileImpl(HttpFileSystemBase fileSystem, String path, final @Nullable RemoteFileInfoImpl fileInfo) {
+ VirtualFileImpl(HttpFileSystemBase fileSystem, String path, @Nullable final RemoteFileInfoImpl fileInfo) {
myFileSystem = fileSystem;
myPath = path;
myFileInfo = fileInfo;
}
@Override
- public void renameFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final String newName) throws IOException {
+ public void renameFile(final Object requestor, @NotNull VirtualFile file, @NotNull String newName) throws IOException {
getDelegate(file).renameFile(requestor, file, newName);
processEvent(new VFilePropertyChangeEvent(requestor, file, VirtualFile.PROP_NAME, file.getName(), newName, false));
}
if (myText != null) {
printer.print(myText, ConsoleViewContentType.SYSTEM_OUTPUT);
}
- if (StringUtil.isEmptyOrSpaces(myStacktrace)) {
- printer.print(CompositePrintable.NEW_LINE, ConsoleViewContentType.SYSTEM_OUTPUT);
- }
- else {
+ if (!StringUtil.isEmptyOrSpaces(myStacktrace)) {
printer.print(CompositePrintable.NEW_LINE, ConsoleViewContentType.ERROR_OUTPUT);
printer.mark();
printer.print(myStacktrace, ConsoleViewContentType.ERROR_OUTPUT);
myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true));
myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false));
- assertAllOutputs(myMockResettablePrinter, "stdout1 ", "stderr1 ", "\nignored msg\n");
+ assertAllOutputs(myMockResettablePrinter, "stdout1 ", "stderr1 ", "\nignored msg");
final MockPrinter mockPrinter1 = new MockPrinter(true);
mockPrinter1.onNewAvailable(myTest1);
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
for (SeveritiesProvider provider : Extensions.getExtensions(SeveritiesProvider.EP_NAME)) {
for (HighlightInfoType type : provider.getSeveritiesHighlightInfoTypes()) {
final HighlightSeverity severity = type.getSeverity(null);
- highlightingTypes.put(severity.toString(), new ExpectedHighlightingSet(severity, false, true));
+ highlightingTypes.put(severity.getName(), new ExpectedHighlightingSet(severity, false, true));
}
}
highlightingTypes.put(END_LINE_HIGHLIGHT_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, true, true));
/*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.ExceptionUtil;
+import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Format string syntax as in {@linkplain String#format(String, Object...)}.
*/
- public static void debug(@NotNull Logger logger, @NotNull String format, @Nullable Object... args) {
+ public static void debug(@NotNull Logger logger, @NonNls @NotNull String format, @Nullable Object... args) {
if (logger.isDebugEnabled()) {
logger.debug(String.format(format, args));
}
*/
package com.intellij.util.text;
+import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import gnu.trove.TObjectHashingStrategy;
* @author max
*/
public final class CharSequenceHashingStrategy implements TObjectHashingStrategy<CharSequence> {
- private static final int COMPARISON_THRESHOLD = 5;
+ public static final CharSequenceHashingStrategy CASE_SENSITIVE = new CharSequenceHashingStrategy(true);
+ public static final CharSequenceHashingStrategy CASE_INSENSITIVE = new CharSequenceHashingStrategy(false);
+ private final boolean myCaseSensitive;
+
+ @Deprecated
+ public CharSequenceHashingStrategy() {
+ this(true);
+ }
+
+ private CharSequenceHashingStrategy(boolean caseSensitive) {
+ myCaseSensitive = caseSensitive;
+ }
@Override
public int computeHashCode(final CharSequence chars) {
- return StringUtil.stringHashCode(chars);
+ return myCaseSensitive ? StringUtil.stringHashCode(chars) : StringUtil.stringHashCodeInsensitive(chars);
}
@Override
public boolean equals(final CharSequence s1, final CharSequence s2) {
- if(s1 == null || s2 == null) return false;
- if(s1 == s2) return true;
- int len = s1.length();
- if (len != s2.length()) return false;
-
- if (len > COMPARISON_THRESHOLD && s1 instanceof String && s2 instanceof String) {
- return s1.equals(s2);
- }
-
- for (int i = 0; i < len; i++) {
- if (s1.charAt(i) != s2.charAt(i)) return false;
- }
- return true;
+ return Comparing.equal(s1, s2, myCaseSensitive);
}
}
protected String getLastCommitMessage(@NotNull VirtualFile root) throws VcsException {
GitSimpleHandler h = new GitSimpleHandler(myProject, root, GitCommand.LOG);
h.addParameters("--max-count=1");
+ String formatPattern;
if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(myVcs.getVersion())) {
- h.addParameters("--pretty=%B");
+ formatPattern = "%B";
}
else {
// only message: subject + body; "%-b" means that preceding line-feeds will be deleted if the body is empty
// %s strips newlines from subject; there is no way to work around it before 1.7.2 with %B (unless parsing some fixed format)
- h.addParameters("--pretty=%s%n%n%-b");
+ formatPattern = "%s%n%n%-b";
}
+ h.addParameters("--pretty=format:" + formatPattern);
return h.run();
}
public Set<String> filteringExclusions = new THashSet<String>(FileUtil.PATH_HASHING_STRATEGY);
@OptionTag
- public String escapeString = MavenProjectConfiguration.DEFAULT_ESCAPE_STRING;
+ public String escapeString = null;
@OptionTag
public boolean escapeWindowsPaths = true;
Set<String> nonFilteredExtensions = collectNonFilteredExtensions(mavenProject);
String escapeString = MavenJDOMUtil.findChildValueByPath(mavenProject.getPluginConfiguration("org.apache.maven.plugins",
"maven-resources-plugin"),
- "escapeString", "\\");
+ "escapeString", null);
List<MyProcessingItem> moduleItemsToProcess = new ArrayList<MyProcessingItem>();
collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode,
Properties properties,
long propertiesHashCode,
Set<String> nonFilteredExtensions,
- String escapeString,
+ @Nullable String escapeString,
boolean tests,
List<MyProcessingItem> result) {
String outputDir = CompilerPaths.getModuleOutputPath(module, tests);
final Properties properties,
final long propertiesHashCode,
final Set<String> nonFilteredExtensions,
- final String escapeString,
+ @Nullable final String escapeString,
final List<MyProcessingItem> result,
final ProgressIndicator indicator) {
VfsUtilCore.visitChildrenRecursively(currentDir, new VirtualFileVisitor() {
boolean isFiltered,
Properties properties,
long propertiesHashCode,
- String escapeString) {
+ @Nullable String escapeString) {
myModule = module;
mySourceFile = sourceFile;
myOutputPath = outputPath;
return myProperties;
}
+ @Nullable
public String getEscapeString() {
return myEscapeString;
}
public static void doFilterText(Module module,
String text,
Properties additionalProperties,
- String propertyEscapeString,
+ @Nullable String propertyEscapeString,
Appendable out) throws IOException {
MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject());
MavenProject mavenProject = manager.findProject(module);
}
Element pluginConfiguration = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin");
- resourceConfig.escapeString = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeString", "\\");
+ resourceConfig.escapeString = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeString", null);
String escapeWindowsPaths = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeWindowsPaths");
if (escapeWindowsPaths != null) {
resourceConfig.escapeWindowsPaths = Boolean.parseBoolean(escapeWindowsPaths);
" <filtering>true</filtering>" +
" </resource>" +
" </resources>" +
+ " <plugins>" +
+ " <plugin>" +
+ " <groupId>org.apache.maven.plugins</groupId>" +
+ " <artifactId>maven-resources-plugin</artifactId>" +
+ " <configuration>" +
+ " <escapeString>\\</escapeString>" +
+ " </configuration>" +
+ " </plugin>" +
+ " </plugins>" +
"</build>");
compileModules("project");
return "{id} (e.g. FOO-001), {summary}, {number} (e.g. 001), {project} (e.g. FOO)";
}
- public void updateTimeSpent(final LocalTask task, final String timeSpent, final String comment) throws Exception {
+ public void updateTimeSpent(@NotNull LocalTask task, @NotNull String timeSpent, @NotNull String comment) throws Exception {
throw new UnsupportedOperationException();
}
@NotNull
List<GitlabProject> fetchProjects() throws Exception {
- HttpGet request = new HttpGet(getRestApiBaseUrl() + "projects");
+ HttpGet request = new HttpGet(getRestApiUrl("projects"));
ResponseHandler<List<GitlabProject>> handler = new GsonMultipleObjectsDeserializer<GitlabProject>(GSON, LIST_OF_PROJECTS_TYPE);
return getHttpClient().execute(request, handler);
}
@SuppressWarnings("UnusedDeclaration")
@NotNull
GitlabProject fetchProject(int id) throws Exception {
- HttpGet request = new HttpGet(getRestApiBaseUrl() + "project/" + id);
+ HttpGet request = new HttpGet(getRestApiUrl("project", id));
return getHttpClient().execute(request, new GsonSingleObjectDeserializer<GitlabProject>(GSON, GitlabProject.class));
}
private String getIssuesUrl() {
if (myCurrentProject != null && myCurrentProject != UNSPECIFIED_PROJECT) {
- return getRestApiBaseUrl() + "projects/" + myCurrentProject.getId() + "/issues";
+ return getRestApiUrl("projects", myCurrentProject.getId(), "issues");
}
- return getRestApiBaseUrl() + "issues";
+ return getRestApiUrl("issues");
}
@NotNull
GitlabIssue fetchIssue(int id) throws Exception {
- HttpGet request = new HttpGet(getRestApiBaseUrl() + "issues/" + id);
+ HttpGet request = new HttpGet(getRestApiUrl("issues", id));
ResponseHandler<GitlabIssue> handler = new GsonSingleObjectDeserializer<GitlabIssue>(GSON, GitlabIssue.class);
return getHttpClient().execute(request, handler);
}
return super.isConfigured() && !myPassword.isEmpty();
}
- private String getRestApiBaseUrl() {
- return getUrl() + REST_API_PATH_PREFIX;
+ @NotNull
+ @Override
+ public String getRestApiPathPrefix() {
+ return REST_API_PATH_PREFIX;
}
@Nullable
import com.intellij.tasks.TaskRepositoryType;
import com.intellij.tasks.config.TaskSettings;
import com.intellij.tasks.impl.BaseRepository;
+import com.intellij.tasks.impl.TaskUtil;
import com.intellij.util.net.CertificatesManager;
import com.intellij.util.net.HttpConfigurable;
import org.apache.http.HttpHost;
HttpClientBuilder builder = HttpClients.custom()
.setDefaultRequestConfig(createRequestConfig())
.setSslcontext(CertificatesManager.getInstance().getSslContext())
- // TODO: use custom one for additional certificate check
+ // TODO: use custom one for additional certificate check
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setDefaultCredentialsProvider(createCredentialsProvider());
HttpRequestInterceptor interceptor = createRequestInterceptor();
}
return builder.build();
}
+
+ /**
+ * Return server's REST API path prefix, e.g. {@code /rest/api/latest} for JIRA or {@code /api/v3/} for Gitlab.
+ * This value will be used in {@link #getRestApiUrl(Object...)}
+ *
+ * @return server's REST API path prefix
+ */
+ @NotNull
+ public String getRestApiPathPrefix() {
+ return "";
+ }
+
+ /**
+ * Build URL using {@link #getUrl()}, {@link #getRestApiPathPrefix()}} and specified path components.
+ * <p/>
+ * Individual path components will should not contain leading or trailing slashes. Empty or null components
+ * will be omitted. Each components is converted to string using its {@link Object#toString()} method and url encoded, so
+ * numeric IDs can be used as well. Returned URL doesn't contain trailing '/', because it's not compatible with some services.
+ *
+ * @return described URL
+ */
+ @NotNull
+ public String getRestApiUrl(@NotNull Object... parts) {
+ StringBuilder builder = new StringBuilder(getUrl());
+ builder.append(getRestApiPathPrefix());
+ if (builder.charAt(builder.length() - 1) == '/') {
+ builder.deleteCharAt(builder.length() - 1);
+ }
+ for (Object part : parts) {
+ if (part == null || part.equals("")) {
+ continue;
+ }
+ builder.append('/').append(TaskUtil.encodeUrl(String.valueOf(part)));
+ }
+ return builder.toString();
+ }
}
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskRepository;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
+import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
public static GsonBuilder installDateDeserializer(GsonBuilder builder) {
return builder.registerTypeAdapter(Date.class, DATE_DESERIALIZER);
}
+
+ /**
+ * Perform standard {@code application/x-www-urlencoded} translation for string {@code s}.
+ *
+ * @return urlencoded string
+ */
+ @NotNull
+ public static String encodeUrl(@NotNull String s) {
+ try {
+ return URLEncoder.encode(s, CharsetToolkit.UTF8);
+ }
+ catch (UnsupportedEncodingException e) {
+ throw new AssertionError("UTF-8 is not supported");
+ }
+ }
}
import com.google.gson.JsonObject;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.CharsetToolkit;
+import com.intellij.tasks.LocalTask;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskState;
import com.intellij.tasks.impl.BaseRepositoryImpl;
public static final Gson GSON = TaskUtil.installDateDeserializer(new GsonBuilder()).create();
private final static Logger LOG = Logger.getInstance("#com.intellij.tasks.jira.JiraRepository");
public static final String LOGIN_FAILED_CHECK_YOUR_PERMISSIONS = "Login failed. Check your permissions.";
- public static final String REST_API_PATH_SUFFIX = "/rest/api/latest";
+ public static final String REST_API_PATH = "/rest/api/latest";
/**
* Default JQL query
@Nullable
@Override
public CancellableConnection createCancellableConnection() {
- String uri = getUrl() + REST_API_PATH_SUFFIX + "/search?maxResults=1&jql=" + encodeUrl(mySearchQuery);
+ String uri = getUrl() + REST_API_PATH + "/search?maxResults=1&jql=" + encodeUrl(mySearchQuery);
return new HttpTestConnection<GetMethod>(new GetMethod(uri)) {
@Override
public void doTest(GetMethod method) throws Exception {
public JiraRestApi discoverRestApiVersion() throws Exception {
String responseBody;
try {
- responseBody = executeMethod(new GetMethod(getUrl() + REST_API_PATH_SUFFIX + "/serverInfo"));
+ responseBody = executeMethod(new GetMethod(getRestUrl("serverInfo")));
}
catch (Exception e) {
LOG.warn("Can't find out JIRA REST API version");
JsonObject object = GSON.fromJson(responseBody, JsonObject.class);
// when JIRA 4.x support will be dropped 'versionNumber' array in response
// may be used instead version string parsing
- return JiraRestApi.fromJiraVersion(object.get("version").getAsString(), this);
+ JiraRestApi version = JiraRestApi.fromJiraVersion(object.get("version").getAsString(), this);
+ if (version == null) {
+ throw new Exception("JIRA below 4.0.0 doesn't have REST API and is no longer supported.");
+ }
+ return version;
}
@Override
myRestApiVersion.setTaskState(task, state);
}
+ @Override
+ public void updateTimeSpent(@NotNull LocalTask task, @NotNull String timeSpent, @NotNull String comment) throws Exception {
+ myRestApiVersion.updateTimeSpend(task, timeSpent, comment);
+ }
+
@NotNull
- public String executeMethod(HttpMethod method) throws Exception {
- LOG.debug("URI is " + method.getURI());
+ public String executeMethod(@NotNull HttpMethod method) throws Exception {
+ LOG.debug("URI: " + method.getURI());
int statusCode;
String entityContent;
try {
statusCode = getHttpClient().executeMethod(method);
- LOG.debug("Status code is " + statusCode);
+ LOG.debug("Status code: " + statusCode);
// may be null if 204 No Content received
final InputStream stream = method.getResponseBodyAsStream();
- entityContent = stream == null ? "" : StreamUtil.readText(stream, "utf-8");
+ entityContent = stream == null ? "" : StreamUtil.readText(stream, CharsetToolkit.UTF8);
LOG.debug(entityContent);
}
finally {
}
// besides SC_OK, can also be SC_NO_CONTENT in issue transition requests
// see: JiraRestApi#setTaskStatus
- if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) {
- //if (statusCode >= 200 && statusCode < 300) {
+ //if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT) {
+ if (statusCode >= 200 && statusCode < 300) {
return entityContent;
}
else if (method.getResponseHeader("Content-Type") != null) {
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
throw new Exception(LOGIN_FAILED_CHECK_YOUR_PERMISSIONS);
}
- throw new Exception("Request failed with HTTP error: " + HttpStatus.getStatusText(method.getStatusCode()));
+ String statusText = HttpStatus.getStatusText(method.getStatusCode());
+ throw new Exception(String.format("Request failed with HTTP error: %d %s", statusCode, statusText));
}
@Override
myRestApiVersion = null;
super.setUrl(url);
}
+
+ public String getRestUrl(String... parts) {
+ return getUrl() + REST_API_PATH + "/" + FileUtil.join(parts);
+ }
}
package com.intellij.tasks.jira;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.vfs.CharsetToolkit;
+import com.intellij.tasks.LocalTask;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskState;
import com.intellij.tasks.jira.model.JiraIssue;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import java.io.UnsupportedEncodingException;
import java.util.List;
-import static com.intellij.tasks.jira.JiraRepository.REST_API_PATH_SUFFIX;
-
/**
* @author Mikhail Golubev
*/
@NotNull
protected GetMethod getSingleIssueSearchMethod(String key) {
- return new GetMethod(myRepository.getUrl() + REST_API_PATH_SUFFIX + "/issue/" + key);
+ return new GetMethod(myRepository.getRestUrl("issue", key));
}
@NotNull
protected GetMethod getMultipleIssuesSearchMethod(String jql, int max) {
- GetMethod method = new GetMethod(myRepository.getUrl() + REST_API_PATH_SUFFIX + "/search");
+ GetMethod method = new GetMethod(myRepository.getRestUrl("search"));
method.setQueryString(new NameValuePair[]{
new NameValuePair("jql", jql),
new NameValuePair("maxResults", String.valueOf(max))
public void setTaskState(Task task, TaskState state) throws Exception {
String requestBody = getRequestForStateTransition(state);
+ LOG.debug(String.format("Transition: %s -> %s, request: %s", task.getState(), state, requestBody));
if (requestBody == null) {
return;
}
- final String transitionsUrl = myRepository.getUrl() + REST_API_PATH_SUFFIX + "/issue/" + task.getId() + "/transitions";
- LOG.debug(String.format("Transition: %s -> %s, request: %s", task.getState(), state, requestBody));
- final PostMethod method = new PostMethod(transitionsUrl);
- method.setRequestEntity(new StringRequestEntity(requestBody, "application/json", "utf-8"));
+ PostMethod method = new PostMethod(myRepository.getRestUrl("issue", task.getId(), "transitions"));
+ method.setRequestEntity(createJsonEntity(requestBody));
myRepository.executeMethod(method);
}
@Nullable
protected abstract String getRequestForStateTransition(@NotNull TaskState state);
+
+ public abstract void updateTimeSpend(LocalTask task, String timeSpent, String comment) throws Exception;
+
+ protected static RequestEntity createJsonEntity(String requestBody) {
+ try {
+ return new StringRequestEntity(requestBody, "application/json", CharsetToolkit.UTF8);
+ }
+ catch (UnsupportedEncodingException e) {
+ throw new AssertionError("UTF-8 encoding is not supported");
+ }
+ }
}
import com.google.gson.reflect.TypeToken;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.tasks.LocalTask;
import com.intellij.tasks.TaskState;
import com.intellij.tasks.jira.JiraRepository;
import com.intellij.tasks.jira.JiraRestApi;
import com.intellij.tasks.jira.model.JiraIssue;
import com.intellij.tasks.jira.model.JiraResponseWrapper;
import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
}
}
+ @Override
+ public void updateTimeSpend(LocalTask task, String timeSpent, String comment) throws Exception {
+ LOG.debug(String.format("Time spend: %s, comment: %s", timeSpent, comment));
+ PostMethod method = new PostMethod(myRepository.getRestUrl("issue", task.getId(), "worklog"));
+ String request;
+ if (StringUtil.isEmpty(comment)) {
+ request = String.format("{\"timeSpent\" : \"" + timeSpent + "\"}", timeSpent);
+ } else {
+ request = String.format("{\"timeSpent\": \"%s\", \"comment\": \"%s\"}", timeSpent, StringUtil.escapeQuotes(comment));
+ }
+ method.setRequestEntity(createJsonEntity(request));
+ myRepository.executeMethod(method);
+ }
+
@NotNull
@Override
public String getVersionName() {
import com.google.gson.reflect.TypeToken;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.tasks.LocalTask;
import com.intellij.tasks.TaskState;
import com.intellij.tasks.jira.JiraRepository;
import com.intellij.tasks.jira.JiraRestApi;
}
}
+ @Override
+ public void updateTimeSpend(LocalTask task, String timeSpent, String comment) throws Exception {
+ throw new Exception(String.format("This version of JIRA REST API (%s) doesn't support updating worklog items.", getVersionName()));
+ }
+
@NotNull
@Override
public String getVersionName() {
private static final Logger LOG = Logger.getInstance("#com.intellij.tasks.youtrack.YouTrackRepository");
@Override
- public void updateTimeSpent(final LocalTask task, final String timeSpent, final String comment) throws Exception {
+ public void updateTimeSpent(@NotNull LocalTask task, @NotNull String timeSpent, @NotNull String comment) throws Exception {
checkVersion();
final HttpMethod method = doREST("/rest/issue/execute/" + task.getId() + "?command=work+Today+" + timeSpent.replaceAll(" ", "+") + "+" + comment, true);
if (method.getStatusCode() != 200) {
--- /dev/null
+<html>
+<body>
+<span style="font-family: verdana,serif;">
+ This inspection checks for cases when loop variable is redeclared inside of loop.
+</span>
+<pre style="font-family: monospace">
+ for i in xrange(5):
+ for i in xrange(20, 25):
+ print("Inner", i)
+ print("Outer", i)
+ </pre>
+</body>
+</html>
<localInspection language="Python" shortName="PyShadowingNamesInspection" displayName="Shadowing names from outer scopes" groupKey="INSP.GROUP.python" enabledByDefault="true" level="WEAK WARNING" implementationClass="com.jetbrains.python.inspections.PyShadowingNamesInspection"/>
<localInspection language="Python" shortName="PyAbstractClassInspection" displayName="Class must implement all abstract methods" groupKey="INSP.GROUP.python" enabledByDefault="true" level="WARNING" implementationClass="com.jetbrains.python.inspections.PyAbstractClassInspection"/>
<localInspection language="Python" shortName="PyPep8NamingInspection" displayName="PEP 8 naming convention violation" groupKey="INSP.GROUP.python" enabledByDefault="true" level="WEAK WARNING" implementationClass="com.jetbrains.python.inspections.PyPep8NamingInspection"/>
+ <localInspection language="Python" shortName="PyAssignmentToForLoopParameterInspection" displayName="Assignment to 'for' loop parameter" groupKey="INSP.GROUP.python" enabledByDefault="true" level="WARNING" implementationClass="com.jetbrains.python.inspections.PyAssignmentToForLoopParameterInspection"/>
<liveTemplateContext implementation="com.jetbrains.python.codeInsight.liveTemplates.PythonTemplateContextType"/>
<liveTemplateMacro implementation="com.jetbrains.python.codeInsight.liveTemplates.CollectionElementNameMacro"/>
INSP.NAME.global.undefined=Global variable is undefined at the module level
INSP.NAME.global.$0.undefined=Global variable ''{0}'' is undefined at the module level
+#PyAssignmentToForLoopParameterInspection
+INSP.NAME.assignment.to.for.loop.parameter.display.name=Assignment to 'for' loop parameter
+
# Refactoring
# introduce
refactoring.introduce.name.error=Incorrect name
--- /dev/null
+/*
+ * Copyright 2000-2014 JetBrains s.r.o.
+ *
+ * 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 com.jetbrains.python.inspections;
+
+import com.intellij.codeInspection.LocalInspectionToolSession;
+import com.intellij.codeInspection.ProblemsHolder;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiElementVisitor;
+import com.intellij.psi.PsiFile;
+import com.jetbrains.python.PyBundle;
+import com.jetbrains.python.psi.PyForPart;
+import com.jetbrains.python.psi.PyTargetExpression;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+//TODO: Try to share logic with AssignmentToForLoopParameterInspection
+
+/**
+ * Checks for cases like
+ * <pre>
+ * for i in range(1, 10):
+ * i = "new value"
+ * </pre>
+ *
+ * @author link
+ */
+public class PyAssignmentToForLoopParameterInspection extends PyInspection {
+
+ private static final String MESSAGE = PyBundle.message("INSP.NAME.assignment.to.for.loop.parameter.display.name");
+
+ @NotNull
+ @Override
+ public String getDisplayName() {
+ return MESSAGE;
+ }
+
+
+ @NotNull
+ @Override
+ public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder,
+ boolean isOnTheFly,
+ @NotNull final LocalInspectionToolSession session) {
+ return new Visitor(holder, session);
+ }
+
+ private static class Visitor extends PyInspectionVisitor {
+ private Visitor(@Nullable ProblemsHolder holder, @NotNull LocalInspectionToolSession session) {
+ super(holder, session);
+ }
+
+ @Override
+ public void visitPyTargetExpression(PyTargetExpression node) {
+ PsiElement variableDeclaration = node.getReference().resolve();
+ if (variableDeclaration == null) {
+ return;
+ }
+ PsiElement variableFirstTimeDeclaration = variableDeclaration.getParent();
+
+ if (variableFirstTimeDeclaration.equals(node.getParent())) {
+ return; //We are checking first time declaration
+ }
+
+ //Find "for" between predecessors until we tree root
+ PsiElement element = variableFirstTimeDeclaration;
+ while (!(element instanceof PsiFile) && element != null) {
+ if (element instanceof PyForPart) {
+ registerProblem(node, MESSAGE);
+ return;
+ }
+ element = element.getParent();
+ }
+ }
+ }
+}
--- /dev/null
+for a in (1, 12):
+ for b in (2, 24):
+ for (c, d) in {"C": "D"}.items():
+ (e, f) = (a, d)
+
+i = 12
+print(i)
+(z, x) = (i, 12)
+print(z)
\ No newline at end of file
--- /dev/null
+for i in range(1, 2):
+ print(i)
+ <warning descr="Assignment to 'for' loop parameter">i</warning> = 12
\ No newline at end of file
--- /dev/null
+for i in [1, 2, 3]:
+ print(i)
+ (<warning descr="Assignment to 'for' loop parameter">i</warning>, f) = (1, 2)
\ No newline at end of file
--- /dev/null
+for (k, v) in {"K": "V"}.items():
+ print(k)
+ <warning descr="Assignment to 'for' loop parameter">k</warning> = "12"
\ No newline at end of file
--- /dev/null
+for i in range(5):
+ for <warning descr="Assignment to 'for' loop parameter">i</warning> in range(20, 25):
+ print("Inner", i)
+ print("Outer", i)
\ No newline at end of file
--- /dev/null
+package com.jetbrains.python.fixtures;
+
+import com.jetbrains.python.inspections.PyInspection;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Helps you to create inspection tests.
+ * <br/>
+ * For each case
+ * <ol>
+ * <li>Create file <code>testData/inspections/_YOUR_INSPECTION_CLASS_SIMPLE_NAME_/CASE_NAME_CAMEL_CASE.py</code></li>
+ * <li>Create method <code>test_YOUR_CASE_NAME_PASCAL_CASE</code> that runs {@link #doTest()}</li>
+ * <li>Overwrite {@link #isInfo()}, {@link #isWarning()} or {@link #isWeakWarning()} to configure what to check</li>
+ * </ol>
+ *
+ * @author link
+ */
+public abstract class PyInspectionTestCase extends PyTestCase {
+
+ @NotNull
+ protected abstract Class<? extends PyInspection> getInspectionClass();
+
+ /**
+ * Launches test. To be called by test author
+ */
+ protected void doTest() {
+ myFixture.configureByFile("inspections/" + getInspectionClass().getSimpleName() + "/" + getTestName(true) + ".py");
+ myFixture.enableInspections(getInspectionClass());
+ myFixture.checkHighlighting(isWarning(), isInfo(), isWeakWarning());
+ }
+
+
+ protected boolean isWeakWarning() {
+ return true;
+ }
+
+ protected boolean isInfo() {
+ return false;
+ }
+
+ protected boolean isWarning() {
+ return true;
+ }
+}
--- /dev/null
+/*
+ * Copyright 2000-2014 JetBrains s.r.o.
+ *
+ * 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 com.jetbrains.python.inspections;
+
+import com.jetbrains.python.fixtures.PyInspectionTestCase;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * @author link
+ */
+public class PyAssignmentToForLoopParameterInspectionTest extends PyInspectionTestCase {
+
+ public void testGood() {
+ doTest();
+ }
+
+ public void testSimpleReassignment() {
+ doTest();
+ }
+
+ public void testTupleAssignment() {
+ doTest();
+ }
+
+ public void testTupleDeclaration() {
+ doTest();
+ }
+
+ public void testTwoLoops() {
+ doTest();
+ }
+
+
+ @NotNull
+ @Override
+ protected Class<? extends PyInspection> getInspectionClass() {
+ return PyAssignmentToForLoopParameterInspection.class;
+ }
+
+ @Override
+ protected boolean isWeakWarning() {
+ return false;
+ }
+}
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.jetbrains.annotations.NotNull;
import java.awt.*;
-import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
public class SpellCheckerSeveritiesProvider extends SeveritiesProvider {
@Override
@NotNull
public List<HighlightInfoType> getSeveritiesHighlightInfoTypes() {
- final List<HighlightInfoType> result = new ArrayList<HighlightInfoType>();
-
final TextAttributes attributes = new TextAttributes();
attributes.setEffectType(EffectType.WAVE_UNDERSCORE);
attributes.setEffectColor(new Color(0, 128, 0));
- result.add(new HighlightInfoType.HighlightInfoTypeImpl(TYPO,
- TextAttributesKey.createTextAttributesKey("TYPO", attributes)));
- return result;
+ HighlightInfoType typo = new HighlightInfoType.HighlightInfoTypeImpl(TYPO, TextAttributesKey.createTextAttributesKey("TYPO", attributes));
+ return Collections.singletonList(typo);
}
@Override
try {
writeDiff(olderFileIn, newerFileIn, patchOutput);
}
- catch (Exception ex) {
- Runner.printStackTrace(ex);
- }
finally {
olderFileIn.close();
newerFileIn.close();
Utils.copyStreamToFile(in, toFile);
Utils.setExecutable(toFile, executable);
}
- catch (Exception ex) {
- Runner.printStackTrace(ex);
- }
finally {
in.close();
}
try {
return doDigestZipFile(zipFile);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
zipFile.close();
}
try {
doDigestStream(in, crc);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
in.close();
}
if (lock == null) return false;
lock.release();
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
ch.close();
s.close();
each.buildPatchFile(olderDir, newerDir, out);
}
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
out.close();
}
try {
preparationResult.patch.revert(actionsToRevert, backupDir, preparationResult.toDir, ui);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
zipFile.close();
}
out.zipEntry(e, in);
}
}
- catch (Exception ex) {
- printStackTrace(ex);
- }
finally {
in.close();
}
props.setProperty(NEW_BUILD_DESCRIPTION, newBuildDesc);
props.store(byteOut, "");
}
- catch (Exception ex) {
- printStackTrace(ex);
- }
finally {
byteOut.close();
}
out.zipFile(PATCH_FILE_NAME, tempPatchFile);
out.finish();
}
- catch (Exception ex) {
- printStackTrace(ex);
- }
finally {
fileOut.close();
}
}
- catch (Exception ex) {
- printStackTrace(ex);
- }
finally {
cleanup(ui);
}
try {
props.load(in);
}
- catch (Exception ex) {
- printStackTrace(ex);
- }
finally {
in.close();
}
try {
Utils.copyStream(in, out);
}
- catch (Exception ex) {
- printStackTrace(ex);
- }
finally {
in.close();
out.close();
}
}
- catch (Exception ex) {
- printStackTrace(ex);
- }
finally {
jarFile.close();
}
printStackTrace(e);
}
}
- catch (Exception ex) {
- printStackTrace(ex);
- }
finally {
try {
cleanup(ui);
try {
applyDiff(in, oldFileIn, out);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
oldFileIn.close();
}
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
out.close();
}
}
});
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
olderZip.close();
}
try {
applyDiff(Utils.findEntryInputStream(patchFile, myPath + "/" + path), in, entryOut);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
entryOut.close();
}
try {
out.zipEntry(each, in);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
in.close();
}
out.finish();
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
fileOut.close();
}
processed.add(inEntry.getName());
}
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
in.close();
}
try {
copyStreamToFile(in, to);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
in.close();
}
try {
copyStream(in, out);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
in.close();
}
try {
copyStream(from, out);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
out.close();
}
try {
from.writeTo(out);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
out.flush();
}
try {
copyStream(in, byteOut);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
byteOut.close();
}
try {
Utils.copyStream(from, tempOut);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
tempOut.close();
}
try {
zipEntry(new ZipEntry(entryPath), from);
}
- catch (Exception e) {
- Runner.printStackTrace(e);
- }
finally {
from.close();
}
package com.intellij.html.impl;
import com.intellij.html.index.Html5CustomAttributesIndex;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.Processor;
currentAttrs.add(attribute.getName());
}
final List<XmlAttributeDescriptor> result = new ArrayList<XmlAttributeDescriptor>();
+ final GlobalSearchScope scope = GlobalSearchScope.allScope(tag.getProject());
FileBasedIndex.getInstance().processAllKeys(Html5CustomAttributesIndex.INDEX_ID, new Processor<String>() {
@Override
public boolean process(String s) {
+ final boolean canProcessKey = !FileBasedIndex.getInstance().processValues(Html5CustomAttributesIndex.INDEX_ID, s,
+ null, new FileBasedIndex.ValueProcessor<Void>() {
+ @Override
+ public boolean process(VirtualFile file, Void value) {
+ return false;
+ }
+ }, scope);
+ if (!canProcessKey) return true;
+
boolean add = true;
for (String attr : currentAttrs) {
if (attr.startsWith(s)) {
}
return true;
}
- }, tag.getProject());
+ }, scope, null);
return result.toArray(new XmlAttributeDescriptor[result.size()]);
}