org.eclipse.text.edits.MalformedTreeException Java Examples

The following examples show how to use org.eclipse.text.edits.MalformedTreeException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
	IDocument doc= new Document(buffer.getString());
	int nLines= doc.getNumberOfLines();
	MultiTextEdit edit= new MultiTextEdit();
	HashSet<Integer> removedLines= new HashSet<Integer>();
	for (int i= 0; i < variables.length; i++) {
		TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added
		if (position == null || position.getLength() > 0) {
			continue;
		}
		int[] offsets= position.getOffsets();
		for (int k= 0; k < offsets.length; k++) {
			int line= doc.getLineOfOffset(offsets[k]);
			IRegion lineInfo= doc.getLineInformation(line);
			int offset= lineInfo.getOffset();
			String str= doc.get(offset, lineInfo.getLength());
			if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
				int nextStart= doc.getLineOffset(line + 1);
				edit.addChild(new DeleteEdit(offset, nextStart - offset));
			}
		}
	}
	edit.apply(doc, 0);
	return doc.get();
}
 
Example #2
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Formats the template buffer.
 * @param buffer
 * @param context
 * @throws BadLocationException
 */
public void format(TemplateBuffer buffer, TemplateContext context) throws BadLocationException {
	try {
		VariableTracker tracker= new VariableTracker(buffer);
		IDocument document= tracker.getDocument();

		internalFormat(document, context);
		convertLineDelimiters(document);
		if (!(context instanceof JavaDocContext) && !isReplacedAreaEmpty(context))
			trimStart(document);

		tracker.updateBuffer();
	} catch (MalformedTreeException e) {
		throw new BadLocationException();
	}
}
 
Example #3
Source File: TextEditConverter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(CopySourceEdit edit) {
	try {
		if (edit.getTargetEdit() != null) {
			org.eclipse.lsp4j.TextEdit te = new org.eclipse.lsp4j.TextEdit();
			te.setRange(JDTUtils.toRange(compilationUnit, edit.getOffset(), edit.getLength()));
			Document doc = new Document(compilationUnit.getSource());
			edit.apply(doc, TextEdit.UPDATE_REGIONS);
			String content = doc.get(edit.getOffset(), edit.getLength());
			if (edit.getSourceModifier() != null) {
				content = applySourceModifier(content, edit.getSourceModifier());
			}
			te.setNewText(content);
			converted.add(te);
		}
		return false;
	} catch (JavaModelException | MalformedTreeException | BadLocationException e) {
		JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
	}
	return super.visit(edit);
}
 
Example #4
Source File: TextEditConverter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(MultiTextEdit edit) {
	try {
		org.eclipse.lsp4j.TextEdit te = new org.eclipse.lsp4j.TextEdit();
		te.setRange(JDTUtils.toRange(compilationUnit, edit.getOffset(), edit.getLength()));
		Document doc = new Document(compilationUnit.getSource());
		edit.apply(doc, TextEdit.UPDATE_REGIONS);
		String content = doc.get(edit.getOffset(), edit.getLength());
		te.setNewText(content);
		converted.add(te);
		return false;
	} catch (JavaModelException | MalformedTreeException | BadLocationException e) {
		JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
	}
	return false;
}
 
Example #5
Source File: TextEditConverter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(CopyTargetEdit edit) {
	try {
		if (edit.getSourceEdit() != null) {
			org.eclipse.lsp4j.TextEdit te = new org.eclipse.lsp4j.TextEdit();
			te.setRange(JDTUtils.toRange(compilationUnit, edit.getOffset(), edit.getLength()));

			Document doc = new Document(compilationUnit.getSource());
			edit.apply(doc, TextEdit.UPDATE_REGIONS);
			String content = doc.get(edit.getSourceEdit().getOffset(), edit.getSourceEdit().getLength());

			if (edit.getSourceEdit().getSourceModifier() != null) {
				content = applySourceModifier(content, edit.getSourceEdit().getSourceModifier());
			}

			te.setNewText(content);
			converted.add(te);
		}
		return false; // do not visit children
	} catch (MalformedTreeException | BadLocationException | CoreException e) {
		JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
	}
	return super.visit(edit);
}
 
Example #6
Source File: TextEditConverter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(MoveTargetEdit edit) {
	try {
		if (edit.getSourceEdit() != null) {
			org.eclipse.lsp4j.TextEdit te = new org.eclipse.lsp4j.TextEdit();
			te.setRange(JDTUtils.toRange(compilationUnit, edit.getOffset(), edit.getLength()));

			Document doc = new Document(compilationUnit.getSource());
			edit.apply(doc, TextEdit.UPDATE_REGIONS);
			String content = doc.get(edit.getSourceEdit().getOffset(), edit.getSourceEdit().getLength());
			if (edit.getSourceEdit().getSourceModifier() != null) {
				content = applySourceModifier(content, edit.getSourceEdit().getSourceModifier());
			}
			te.setNewText(content);
			converted.add(te);
			return false; // do not visit children
		}
	} catch (MalformedTreeException | BadLocationException | CoreException e) {
		JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
	}
	return super.visit(edit);
}
 
Example #7
Source File: CleanUpPostSaveListener.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void performEdit(IDocument document, long oldFileValue, LinkedList<UndoEdit> editCollector, long[] oldDocValue, boolean[] setContentStampSuccess) throws MalformedTreeException, BadLocationException, CoreException {
	if (document instanceof IDocumentExtension4) {
		oldDocValue[0]= ((IDocumentExtension4)document).getModificationStamp();
	} else {
		oldDocValue[0]= oldFileValue;
	}

	// perform the changes
	for (int index= 0; index < fUndos.length; index++) {
		UndoEdit edit= fUndos[index];
		UndoEdit redo= edit.apply(document, TextEdit.CREATE_UNDO);
		editCollector.addFirst(redo);
	}

	if (document instanceof IDocumentExtension4 && fDocumentStamp != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP) {
		try {
			((IDocumentExtension4)document).replace(0, 0, "", fDocumentStamp); //$NON-NLS-1$
			setContentStampSuccess[0]= true;
		} catch (BadLocationException e) {
			throw wrapBadLocationException(e);
		}
	}
}
 
Example #8
Source File: ProcessVariableRenamer.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    final Variable accessedVar = expression.getAccessedVariable();
    // look for dynamic variables since the parameters already have the
    // new names, the actual references to the parameters are using the
    // old names
    if (accessedVar instanceof DynamicVariable) {
        final String newName = findReplacement(accessedVar.getName());
        if (newName != null) {
            ReplaceEdit replaceEdit = new ReplaceEdit(expression.getStart(), expression.getLength(), newName);
            try {
                edits.addChild(replaceEdit);
            }catch (MalformedTreeException e) {
                BonitaStudioLog.error(e);
            }
        }
    }
}
 
Example #9
Source File: EnsuresPredicateFix.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
private boolean conductVisit(ASTNode node) {
	if (this.sourceFound) {
		return false;
	}

	if (this.lineNumber == this.unit.getLineNumber(node.getStartPosition())) {
		try {
			this.sourceFound = true;
			addEnsuresConstructor(node, this.marker, this.unit, this.sourceUnit, this.varName, this.errorVarIndex, this.predicate);
			return false;
		}
		catch (JavaModelException | IllegalArgumentException | MalformedTreeException | BadLocationException e) {
			Activator.getDefault().logError(e);
		}
	}
	return true;
}
 
Example #10
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Formats the template buffer.
 * @param buffer
 * @param context
 * @throws BadLocationException
 */
public void format(TemplateBuffer buffer, CompilationUnitContext context) throws BadLocationException {
	try {
		VariableTracker tracker= new VariableTracker(buffer);
		IDocument document= tracker.getDocument();

		internalFormat(document, context);
		convertLineDelimiters(document);
		if (!(context instanceof JavaDocContext) && !isReplacedAreaEmpty(context))
			trimStart(document);

		tracker.updateBuffer();
	} catch (MalformedTreeException e) {
		throw new BadLocationException();
	}
}
 
Example #11
Source File: DocumentUtils.java    From typescript.java with MIT License 6 votes vote down vote up
/**
 * Method will apply all edits to document as single modification. Needs to
 * be executed in UI thread.
 * 
 * @param document
 *            document to modify
 * @param edits
 *            list of TypeScript {@link CodeEdit}.
 * @throws TypeScriptException
 * @throws BadLocationException
 * @throws MalformedTreeException
 */
public static void applyEdits(IDocument document, List<CodeEdit> codeEdits)
		throws TypeScriptException, MalformedTreeException, BadLocationException {
	if (document == null || codeEdits.isEmpty()) {
		return;
	}

	IDocumentUndoManager manager = DocumentUndoManagerRegistry.getDocumentUndoManager(document);
	if (manager != null) {
		manager.beginCompoundChange();
	}

	try {
		TextEdit edit = toTextEdit(codeEdits, document);
		// RewriteSessionEditProcessor editProcessor = new
		// RewriteSessionEditProcessor(document, edit,
		// org.eclipse.text.edits.TextEdit.NONE);
		// editProcessor.performEdits();
		edit.apply(document);
	} finally {
		if (manager != null) {
			manager.endCompoundChange();
		}
	}
}
 
Example #12
Source File: GeneratePropertiesTestCase.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
private IDocument applyGenerateProperties(MockupGeneratePropertiesRequestProcessor requestProcessor)
        throws BadLocationException, MalformedTreeException, MisconfigurationException {
    IDocument refactoringDoc = new Document(data.source);
    MultiTextEdit multi = new MultiTextEdit();
    for (GeneratePropertiesRequest req : requestProcessor.getRefactoringRequests()) {
        SelectionState state = req.getSelectionState();

        if (state.isGetter()) {
            multi.addChild(new GetterMethodEdit(req).getEdit());
        }
        if (state.isSetter()) {
            multi.addChild(new SetterMethodEdit(req).getEdit());
        }
        if (state.isDelete()) {
            multi.addChild(new DeleteMethodEdit(req).getEdit());
        }
        multi.addChild(new PropertyEdit(req).getEdit());
    }
    multi.apply(refactoringDoc);
    return refactoringDoc;
}
 
Example #13
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Restores any decorated regions and updates the buffer's variable offsets.
 *
 * @return the buffer.
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
public TemplateBuffer updateBuffer() throws MalformedTreeException, BadLocationException {
	checkState();
	TemplateVariable[] variables= fBuffer.getVariables();
	try {
		removeRangeMarkers(fPositions, fDocument, variables);
	} catch (BadPositionCategoryException x) {
		Assert.isTrue(false);
	}
	fBuffer.setContent(fDocument.get(), variables);
	fDocument= null;

	return fBuffer;
}
 
Example #14
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Applies a {@link TextEdit} to the {@link IDocument} of this context and updates
 * the completion offset variable.
 * 
 * @param te {@link TextEdit} to apply
 * @return <code>true</code> if the method was successful, <code>false</code> otherwise
 */
public boolean applyTextEdit(TextEdit te) {
	try {
		te.apply(getDocument());
		setCompletionOffset(getCompletionOffset() + ((te.getOffset() < getCompletionOffset()) ? te.getLength() : 0));
		return true;
	} catch (MalformedTreeException | BadLocationException e) {
	
	}
	return false;
}
 
Example #15
Source File: ExtractMethodTestCase.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private IDocument applyExtractMethod(RefactoringInfo info, MockupExtractMethodRequestProcessor requestProcessor)
        throws BadLocationException, MalformedTreeException, MisconfigurationException {
    ExtractMethodRequest req = requestProcessor.getRefactoringRequests().get(0);

    ExtractMethodEdit extractedMethodEdit = new ExtractMethodEdit(req);
    ExtractCallEdit callExtractedMethodEdit = new ExtractCallEdit(req);

    MultiTextEdit edit = new MultiTextEdit();
    edit.addChild(extractedMethodEdit.getEdit());
    edit.addChild(callExtractedMethodEdit.getEdit());

    IDocument refactoringDoc = new Document(data.source);
    edit.apply(refactoringDoc);
    return refactoringDoc;
}
 
Example #16
Source File: OverrideMethodsTestCase.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private IDocument applyOverrideMethod(MockupOverrideMethodsRequestProcessor requestProcessor)
        throws BadLocationException, MalformedTreeException, MisconfigurationException {
    MethodEdit methodEdit = new MethodEdit(requestProcessor.getRefactoringRequests().get(0));

    IDocument refactoringDoc = new Document(data.source);
    methodEdit.getEdit().apply(refactoringDoc);
    return refactoringDoc;
}
 
Example #17
Source File: ConstructorFieldTestCase.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private IDocument applyConstructorUsingFields(MockupConstructorFieldRequestProcessor requestProcessor)
        throws BadLocationException, MalformedTreeException, MisconfigurationException {
    ConstructorMethodEdit constructorEdit = new ConstructorMethodEdit(requestProcessor.getRefactoringRequests()
            .get(0));

    IDocument refactoringDoc = new Document(data.source);
    constructorEdit.getEdit().apply(refactoringDoc);
    return refactoringDoc;
}
 
Example #18
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new tracker.
 * 
 * @param buffer the buffer to track
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
public VariableTracker(TemplateBuffer buffer) throws MalformedTreeException, BadLocationException {
	Assert.isLegal(buffer != null);
	fBuffer= buffer;
	fDocument= new Document(fBuffer.getString());
	installJavaStuff(fDocument);
	fDocument.addPositionCategory(CATEGORY);
	fDocument.addPositionUpdater(new ExclusivePositionUpdater(CATEGORY));
	fPositions= createRangeMarkers(fBuffer.getVariables(), fDocument);
}
 
Example #19
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Restores any decorated regions and updates the buffer's variable offsets.
 *
 * @return the buffer.
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
public TemplateBuffer updateBuffer() throws MalformedTreeException, BadLocationException {
	checkState();
	TemplateVariable[] variables= fBuffer.getVariables();
	try {
		removeRangeMarkers(fPositions, fDocument, variables);
	} catch (BadPositionCategoryException x) {
		Assert.isTrue(false);
	}
	fBuffer.setContent(fDocument.get(), variables);
	fDocument= null;

	return fBuffer;
}
 
Example #20
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unused")
	protected void indent(IDocument document) throws BadLocationException, MalformedTreeException {
//		// first line
//		int offset= document.getLineOffset(0);
//		document.replace(offset, 0, CodeFormatterUtil.createIndentString(fInitialIndentLevel, fProject));
//		
//		// following lines
//		int lineCount= document.getNumberOfLines();
//		IndentUtil.indentLines(document, new LineRange(1, lineCount - 1), fProject, null);
	}
 
Example #21
Source File: LangContext.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
public TemplateBuffer evaluate(Template template, boolean fixIndentation) 
			throws BadLocationException, TemplateException {
		if (!canEvaluate(template))
			return null;
		
		TemplateTranslator translator= new TemplateTranslator();
		
		String pattern = template.getPattern();
//		if(fixIndentation) {
//			pattern = fixIndentation(pattern);
//		}
		TemplateBuffer buffer = translator.translate(pattern);
		
		getContextType().resolve(buffer, this);
		
		if(fixIndentation) {
			String delimiter = TextUtilities.getDefaultLineDelimiter(getDocument());
			JavaFormatter formatter = new JavaFormatter(delimiter) {
				@Override
				protected void indent(IDocument document) throws BadLocationException, MalformedTreeException {
					simpleIndent(document);
				}
			};
			formatter.format(buffer, this);
		}
		
		return buffer;
	}
 
Example #22
Source File: MappingOperationScriptBuilder.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private String format(final String initialValue) {
    final Document document = new Document(initialValue);
    try {
        new DefaultGroovyFormatter(document, DEFAULT_FORMATTER_PREFS, FORMAT_LEVEL).format().apply(document);
    } catch (MalformedTreeException | BadLocationException e) {
        BonitaStudioLog.error("Failed to format generated script", e);
    }
    return document.get();
}
 
Example #23
Source File: DocumentUpdateOperationBuilder.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private String format(String initialValue) {
    final org.eclipse.jface.text.Document document = new org.eclipse.jface.text.Document(initialValue);
    try {
        new DefaultGroovyFormatter(document, new DefaultFormatterPreferences(), 0).format().apply(document);
    } catch (MalformedTreeException | BadLocationException e) {
        BonitaStudioLog.error("Failed to format generated script", e);
    }
    return document.get();
}
 
Example #24
Source File: FieldToContractInputMappingExpressionBuilderTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private String format(String initialValue) {
    final Document document = new Document(initialValue);
    try {
        new DefaultGroovyFormatter(document, new DefaultFormatterPreferences(), 0).format().apply(document);
    } catch (MalformedTreeException | BadLocationException e) {
        BonitaStudioLog.error("Failed to format generated script", e);
    }
    return document.get();
}
 
Example #25
Source File: EditorDocumentUndoChange.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected UndoEdit performEdits(IDocument document) throws BadLocationException, MalformedTreeException {
	DocumentRewriteSession session = null;
	try {
		if (document instanceof IDocumentExtension4) {
			session = ((IDocumentExtension4) document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
		}
		return undoEdit.apply(document);
	} finally {
		if (session != null) {
			((IDocumentExtension4) document).stopRewriteSession(session);
		}
	}
}
 
Example #26
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new tracker.
 * 
 * @param buffer the buffer to track
 * @throws MalformedTreeException
 * @throws BadLocationException
 */
public VariableTracker(TemplateBuffer buffer) throws MalformedTreeException, BadLocationException {
	Assert.isLegal(buffer != null);
	fBuffer= buffer;
	fDocument= new Document(fBuffer.getString());
	installJavaStuff(fDocument);
	fDocument.addPositionCategory(CATEGORY);
	fDocument.addPositionUpdater(new ExclusivePositionUpdater(CATEGORY));
	fPositions= createRangeMarkers(fBuffer.getVariables(), fDocument);
}
 
Example #27
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void rewriteImports(TextChangeManager changeManager, IProgressMonitor pm) throws CoreException {
	for (Iterator<Entry<ICompilationUnit, ImportChange>> iter= fImportChanges.entrySet().iterator(); iter.hasNext();) {
		Entry<ICompilationUnit, ImportChange> entry= iter.next();
		ICompilationUnit cu= entry.getKey();
		ImportChange importChange= entry.getValue();

		ImportRewrite importRewrite= StubUtility.createImportRewrite(cu, true);
		importRewrite.setFilterImplicitImports(false);
		for (Iterator<String> iterator= importChange.fStaticToRemove.iterator(); iterator.hasNext();) {
			importRewrite.removeStaticImport(iterator.next());
		}
		for (Iterator<String> iterator= importChange.fToRemove.iterator(); iterator.hasNext();) {
			importRewrite.removeImport(iterator.next());
		}
		for (Iterator<String[]> iterator= importChange.fStaticToAdd.iterator(); iterator.hasNext();) {
			String[] toAdd= iterator.next();
			importRewrite.addStaticImport(toAdd[0], toAdd[1], true);
		}
		for (Iterator<String> iterator= importChange.fToAdd.iterator(); iterator.hasNext();) {
			importRewrite.addImport(iterator.next());
		}

		if (importRewrite.hasRecordedChanges()) {
			TextEdit importEdit= importRewrite.rewriteImports(pm);
			String name= RefactoringCoreMessages.RenamePackageRefactoring_update_imports;
			try {
				TextChangeCompatibility.addTextEdit(changeManager.get(cu), name, importEdit);
			} catch (MalformedTreeException e) {
				JavaPlugin.logErrorMessage("MalformedTreeException while processing cu " + cu); //$NON-NLS-1$
				throw e;
			}
		}
	}
}
 
Example #28
Source File: TextMatchUpdater.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addTextUpdates(ICompilationUnit cu, Set<TextMatch> matches) {
	for (Iterator<TextMatch> resultIter= matches.iterator(); resultIter.hasNext();){
		TextMatch match= resultIter.next();
		if (!match.isQualified() && fOnlyQualified)
			continue;
		int matchStart= match.getStartPosition();
		ReplaceEdit edit= new ReplaceEdit(matchStart, fCurrentNameLength, fNewName);
		try {
			TextChangeCompatibility.addTextEdit(fManager.get(cu), TEXT_EDIT_LABEL, edit, TEXTUAL_MATCHES);
		} catch (MalformedTreeException e) {
			// conflicting update -> omit text match
		}
	}
}
 
Example #29
Source File: CopyrightManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Rewrites compilation unit with new source
 *
 * @param unit
 *            compilation unit to be rewritten
 * @param source
 *            new source of compilation unit
 */
private void rewriteCompilationUnit(final ICompilationUnit unit, final String source) {
	try {
		final TextEdit edits = rewriter.rewriteAST();
		final Document document = new Document(source);
		edits.apply(document);
		unit.getBuffer().setContents(document.get());
		change.setEdit(edits);
	} catch (final JavaModelException | MalformedTreeException | BadLocationException e) {
		ConsoleUtils.printError(e.getMessage());
	}
}
 
Example #30
Source File: AbstractCacheableFormatter.java    From formatter-maven-plugin with Apache License 2.0 5 votes vote down vote up
public String formatFile(File file, String originalCode, LineEnding ending) {
    try {
        this.log.debug("Processing file: " + file + " with line ending: " + ending);
        LineEnding formatterLineEnding = ending;
        // if the line ending is set as KEEP we have to determine the current line ending of the file
        // and let the formatter use this one. Otherwise it would likely fall back to current system line separator
        if (formatterLineEnding == LineEnding.KEEP) {
            formatterLineEnding = LineEnding.determineLineEnding(originalCode);
            this.log.debug("Determined line ending: " + formatterLineEnding + " to keep for file: " + file);
        }
        String formattedCode = doFormat(originalCode, formatterLineEnding);

        if (formattedCode == null) {
            this.log.debug("Nothing formatted. Try to fix line endings.");
            formattedCode = fixLineEnding(originalCode, ending);
        }

        if (formattedCode == null) {
            this.log.debug("Equal code. Not writing result to file.");
            return originalCode;
        }

        this.log.debug("Line endings fixed");

        return formattedCode;
    } catch (IOException | MalformedTreeException | BadLocationException e) {
        this.log.warn(e);
        return null;
    }
}