/** * Returns the defined encoding for the given module. * * <pre> * The search for the encoding is done in this order: * 1. Check the encoding that is set specifically to a LocalModule. * 2. Check the workspace default charset. * 3. If all the above fails, get ResourcesPlugin.getEncoding(), which actually gets the encoding from the system. * </pre> * * @param module an {@link IModule}. * @return The module's encoding. */ public static String getModuleEncoding(IModule module) { String charset = null; try { if (module instanceof LocalModule) { IFile file = ((LocalModule) module).getFile(); if (file != null) { String fileCharset = file.getCharset(true); if (fileCharset != null) { charset = fileCharset; } } } } catch (Throwable e) { // If there is any error, return the default IdeLog.logInfo( PHPEditorPlugin.getDefault(), "PHP encoding utils - Returning the default encoding due to an error (getModuleEncoding)", //$NON-NLS-1$ e, PHPEditorPlugin.DEBUG_SCOPE); } if (charset == null) { try { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); charset = workspaceRoot.getDefaultCharset(true); } catch (CoreException ce) { charset = WorkbenchEncoding.getWorkbenchDefaultEncoding(); } } if (charset == null) { // Use the system's encoding charset = ResourcesPlugin.getEncoding(); } return charset; }
public void setFile(IFile file) { try { this.charset = file.getCharset(); } catch (CoreException e) { HTMLPlugin.logException(e); } }
public IAccumulatingLexer createLexer(IFile file, ISourceForm sourceForm) throws CoreException, IOException { return createLexer( new BufferedReader(new InputStreamReader(file.getContents(true), file.getCharset())), file, SourceForm.determineFilename(file), sourceForm); }
public void annotate(final IFile file, final Iterable<RuleViolation> violations) throws CoreException, IOException { MarkerUtil.removeAllMarkers(file); if (!Iterables.isEmpty(violations)) { final String content = Files.toString(file.getRawLocation().toFile(), Charset.forName(file.getCharset())); for (final RuleViolation violation : violations) { MarkerUtil.addMarker(file, content, violation); } } }
private void getChangedLines(Subscriber s, PatchFile p, IProgressMonitor monitor) { try { // For an outgoing changed resource, find out which lines // differ from the local file and its previous local version // (i.e. we don't want to force a diff with the repository). IDiff d = s.getDiff(p.getResource()); if (d instanceof IThreeWayDiff && ((IThreeWayDiff) d).getDirection() == IThreeWayDiff.OUTGOING) { IThreeWayDiff diff = (IThreeWayDiff) d; monitor.beginTask(null, 100); IResourceDiff localDiff = (IResourceDiff) diff.getLocalChange(); IResource resource = localDiff.getResource(); if (resource instanceof IFile) { IFile file = (IFile) resource; monitor.subTask(Messages.getString("ChangeLog.MergingDiffs")); // $NON-NLS-1$ String osEncoding = file.getCharset(); IFileRevision ancestorState = localDiff.getBeforeState(); IStorage ancestorStorage; if (ancestorState != null) { ancestorStorage = ancestorState.getStorage(monitor); p.setStorage(ancestorStorage); } else ancestorStorage = null; try { // We compare using a standard differencer to get ranges // of changes. We modify them to be document-based (i.e. // first line is line 1) and store them for later parsing. LineComparator left = new LineComparator(ancestorStorage.getContents(), osEncoding); LineComparator right = new LineComparator(file.getContents(), osEncoding); for (RangeDifference tmp : RangeDifferencer.findDifferences(left, right)) { if (tmp.kind() == RangeDifference.CHANGE) { // Right side of diff are all changes found in local file. int rightLength = tmp.rightLength() > 0 ? tmp.rightLength() : tmp.rightLength() + 1; // We also want to store left side of the diff which are changes to the ancestor as // it may contain // functions/methods that have been removed. int leftLength = tmp.leftLength() > 0 ? tmp.leftLength() : tmp.leftLength() + 1; // Only store left side changes if the storage exists and we add one to the start // line number if (p.getStorage() != null) p.addLineRange(tmp.leftStart(), tmp.leftStart() + leftLength, false); p.addLineRange(tmp.rightStart(), tmp.rightStart() + rightLength, true); } } } catch (UnsupportedEncodingException e) { // do nothing for now } } monitor.done(); } } catch (CoreException e) { // Do nothing if error occurs } }
/* * This method is called only when encoding is not detected in the file. * * Here is encoding lookup order we will try: - try resource content * description (Eclipse Text file encoding) - try resource content * properties (for JSP only) - try content type encoding preferences (for * HTML only) - try resource content description (Eclipse Text file * encoding, implicit check) * * Note: This method appears in both CodedReaderCreator and * CodedStreamCreator (with just a minor difference). They should be kept * the same. */ private EncodingMemento getEncodingMementoFromResourceAndPreference() throws IOException, CoreException { EncodingMemento encodingMemento = fEncodingMemento; // Follow Eclipse Platform's direction. Get the charset from IFile. if (fIFile != null) { String charset = fIFile.getCharset(); encodingMemento = CodedIO.createEncodingMemento(charset); } return encodingMemento; }
private static void formatFile(IFile file, IProgressMonitor monitor) throws UnsupportedEncodingException, CoreException, IOException { Reader reader = new InputStreamReader(file.getContents(), file.getCharset()); String contents = FileUtilities.getContents(reader); if (contents != null) { FormattedSource result = format(contents, null, monitor); if (!contents.equals(result.source)) { InputStream stream = new ByteArrayInputStream(result.source.getBytes("UTF-8")); file.setContents(stream, IResource.KEEP_HISTORY, monitor); } } }
@Override public void execute() throws BuildException { try { ArrayList<Manifest> manifests = new ArrayList<Manifest>(); ArrayList<IProject> projects = getProjects(); ArrayList<String> bundleIdList = new ArrayList<String>(); for (IProject eachProject : projects) { if (eachProject.getName().contains("kr.or.eclipse")) { continue; } IFile manifestFile = eachProject.getFile(new Path("META-INF/MANIFEST.MF")); Manifest m = new Manifest(manifestFile); manifests.add(m); bundleIdList.add(m.getBundleId()); } for (Manifest m : manifests) { System.out.println(m.getBundleId() + " Update version > " + this.version + ".qualifier"); m.setBundleVersion(this.version + ".qualifier"); m.updateDependencies(bundleIdList, this.version); m.save(); } System.out.println("Update versions on feature"); IFile featureFile = getFeatureProject().getFile("feature.xml"); String featureContent = read(featureFile.getContents(), featureFile.getCharset()); String newcontent = featureContent.replaceAll( "version=\"[0-9]+\\.[0-9]+\\.[0-9]+\\.qualifier\"", "version=\"" + this.version + ".qualifier\""); write(featureFile, newcontent, featureFile.getCharset()); } catch (Exception e) { e.printStackTrace(); throw new BuildException(e); } }
private void hack(IFile pFile) { String lFileContents; try { lFileContents = inputStreamToString(pFile.getContents(true), pFile.getCharset()); if (lFileContents.contains("http://www.og.dti.gov/fox2\"") || lFileContents.contains("http://www.og.dti.gov/fox_global2\"")) { lFileContents = mergeNamespaces(lFileContents); } else { lFileContents = hackNamespaces(lFileContents); } pFile.setContents(stringToInputStream(lFileContents), IFile.KEEP_HISTORY, null); } catch (CoreException e) { e.printStackTrace(); } }
@Override public void generateFile(String fileName, String slot, CharSequence contents) { IFile file = getFile(fileName, slot); try { createFolder(file.getParent()); final String defaultCharset = file.getCharset(); final String newContentAsString = postProcess(fileName, slot, contents).toString(); if (file.exists()) { StringInputStream newContent = null; try { newContent = new StringInputStream(newContentAsString, defaultCharset); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } final boolean contentChanged = hasChanged(file, newContent); if (contentChanged) { if (isJava(file)) { InputStream mergedContent = null; try { mergedContent = getMergedContent(file, newContentAsString, defaultCharset); file.setContents(mergedContent, true, true, null); } finally { if (mergedContent != null) { try { mergedContent.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } else { file.create(new StringInputStream(newContentAsString, defaultCharset), true, null); } file.setDerived(true, new NullProgressMonitor()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (CoreException e) { throw new RuntimeException(e); } }
public static IFile createFile( final String name, final IContainer container, final String content) { final IFile file = container.getFile(new Path(name)); try { final InputStream stream = new ByteArrayInputStream(content.getBytes(file.getCharset())); if (file.exists()) { file.setContents(stream, true, true, null); } else { file.create(stream, true, null); } stream.close(); } catch (final Exception e) { throw new RuntimeException(e); } return file; }
private String parseFileContent(String fileName) throws CoreException { // TODO we should use the project path instead of its name, but // don't know how to do that IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject bizProj = workspace.getRoot().getProject(pi.getBusinessProjectId()); IFile bizFile = bizProj.getFile(fileName); if (!bizFile.exists()) { throw new RuntimeException("Missing " + fileName + " in business tier project: " + bizFile); } BufferedReader bizReader; try { bizReader = new BufferedReader(new InputStreamReader(bizFile.getContents(), bizFile.getCharset())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } return ResourceHelper.content(bizReader); }
@Override protected IBaseModel createModel(IEditorInput input) throws CoreException { PluginPackageModel model = null; if (input instanceof IFileEditorInput) { IDocument document = getDocumentProvider().getDocument(input); IFile file = ((IFileEditorInput) input).getFile(); model = new PluginPackageModel(file, document, true); model.setUnderlyingResource(file); model.setCharset(file.getCharset()); return model; } return null; }
@Override protected IBaseModel createModel(IEditorInput input) throws CoreException { BundleModel model = null; boolean isReconciling = input instanceof IFileEditorInput; IDocument document = getDocumentProvider().getDocument(input); model = new BundleModel(document, isReconciling); if (input instanceof IFileEditorInput) { IFile file = ((IFileEditorInput) input).getFile(); model.setUnderlyingResource(file); model.setCharset(file.getCharset()); } else if (input instanceof IURIEditorInput) { IFileStore store = EFS.getStore(((IURIEditorInput) input).getURI()); model.setInstallLocation(store.getParent().getParent().toString()); model.setCharset(getDefaultCharset()); } else if (input instanceof JarEntryEditorInput) { File file = (File) ((JarEntryEditorInput) input).getAdapter(File.class); model.setInstallLocation(file.toString()); model.setCharset(getDefaultCharset()); } else { model.setCharset(getDefaultCharset()); } model.load(); return model; }
/** @exception JavaModelException if setting the source of the original compilation unit fails */ protected void executeOperation() throws JavaModelException { try { beginTask(Messages.workingCopy_commit, 2); CompilationUnit workingCopy = getCompilationUnit(); if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals( workingCopy.getJavaProject().getElementName())) { // case of a working copy without a resource workingCopy.getBuffer().save(this.progressMonitor, this.force); return; } ICompilationUnit primary = workingCopy.getPrimary(); boolean isPrimary = workingCopy.isPrimary(); JavaElementDeltaBuilder deltaBuilder = null; PackageFragmentRoot root = (PackageFragmentRoot) workingCopy.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); boolean isIncluded = !Util.isExcluded(workingCopy); IFile resource = (IFile) workingCopy.getResource(); IJavaProject project = root.getJavaProject(); if (isPrimary || (root.validateOnClasspath().isOK() && isIncluded && resource.isAccessible() && Util.isValidCompilationUnitName( workingCopy.getElementName(), project.getOption(JavaCore.COMPILER_SOURCE, true), project.getOption(JavaCore.COMPILER_COMPLIANCE, true)))) { // force opening so that the delta builder can get the old info if (!isPrimary && !primary.isOpen()) { primary.open(null); } // creates the delta builder (this remembers the content of the cu) if: // - it is not excluded // - and it is not a primary or it is a non-consistent primary if (isIncluded && (!isPrimary || !workingCopy.isConsistent())) { deltaBuilder = new JavaElementDeltaBuilder(primary); } // save the cu IBuffer primaryBuffer = primary.getBuffer(); if (!isPrimary) { if (primaryBuffer == null) return; char[] primaryContents = primaryBuffer.getCharacters(); boolean hasSaved = false; try { IBuffer workingCopyBuffer = workingCopy.getBuffer(); if (workingCopyBuffer == null) return; primaryBuffer.setContents(workingCopyBuffer.getCharacters()); primaryBuffer.save(this.progressMonitor, this.force); primary.makeConsistent(this); hasSaved = true; } finally { if (!hasSaved) { // restore original buffer contents since something went wrong primaryBuffer.setContents(primaryContents); } } } else { // for a primary working copy no need to set the content of the buffer again primaryBuffer.save(this.progressMonitor, this.force); primary.makeConsistent(this); } } else { // working copy on cu outside classpath OR resource doesn't exist yet String encoding = null; try { encoding = resource.getCharset(); } catch (CoreException ce) { // use no encoding } String contents = workingCopy.getSource(); if (contents == null) return; try { byte[] bytes = encoding == null ? contents.getBytes() : contents.getBytes(encoding); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); if (resource.exists()) { resource.setContents( stream, this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, null); } else { resource.create(stream, this.force, this.progressMonitor); } } catch (CoreException e) { throw new JavaModelException(e); } catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } } setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); // make sure working copy is in sync workingCopy.updateTimeStamp((CompilationUnit) primary); workingCopy.makeConsistent(this); worked(1); // build the deltas if (deltaBuilder != null) { deltaBuilder.buildDeltas(); // add the deltas to the list of deltas created during this operation if (deltaBuilder.delta != null) { addDelta(deltaBuilder.delta); } } worked(1); } finally { done(); } }
/** * Finds the start position in the property file. We assume that the key is the first match on a * line. * * @param propertyName the property name * @return the start position of the property name in the file, -1 if not found */ private int findPropertyNameStartPosition(String propertyName) { // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19319 InputStream stream = null; LineReader lineReader = null; String encoding; try { encoding = fPropertiesFile.getCharset(); } catch (CoreException e1) { encoding = "ISO-8859-1"; // $NON-NLS-1$ } try { stream = createInputStream(fPropertiesFile); lineReader = new LineReader(stream, encoding); } catch (CoreException cex) { // failed to get input stream JavaPlugin.log(cex); return -1; } catch (IOException e) { if (stream != null) { try { stream.close(); } catch (IOException ce) { JavaPlugin.log(ce); } } return -1; } int start = 0; try { StringBuffer buf = new StringBuffer(80); int eols = lineReader.readLine(buf); int keyLength = propertyName.length(); while (eols > 0) { String line = buf.toString(); int i = line.indexOf(propertyName); int charPos = i + keyLength; char terminatorChar = 0; boolean hasNoValue = (charPos >= line.length()); if (i > -1 && !hasNoValue) terminatorChar = line.charAt(charPos); if (line.trim().startsWith(propertyName) && (hasNoValue || Character.isWhitespace(terminatorChar) || terminatorChar == '=')) { start += line.indexOf(propertyName); eols = -17; // found key } else { start += line.length() + eols; buf.setLength(0); eols = lineReader.readLine(buf); } } if (eols != -17) start = -1; // key not found in file. See bug 63794. This can happen if the key contains escaped // characters. } catch (IOException ex) { JavaPlugin.log(ex); return -1; } finally { try { lineReader.close(); } catch (IOException ex) { JavaPlugin.log(ex); } } return start; }
/** * Run PMD against a resource * * @param resource the resource to process */ protected final void reviewResource(IResource resource) { IFile file = (IFile) resource.getAdapter(IFile.class); if (file == null || file.getFileExtension() == null) return; Reader input = null; try { boolean included = isIncluded(file); log.debug("Derived files included: " + projectProperties.isIncludeDerivedFiles()); log.debug("file " + file.getName() + " is derived: " + file.isDerived()); log.debug("file checked: " + included); prepareMarkerAccumulator(file); LanguageVersionDiscoverer languageDiscoverer = new LanguageVersionDiscoverer(); LanguageVersion languageVersion = languageDiscoverer.getDefaultLanguageVersionForFile(file.getName()); // in case it is java, select the correct java version if (languageVersion != null && languageVersion.getLanguage() == Language.JAVA) { languageVersion = PMDPlugin.javaVersionFor(file.getProject()); } if (languageVersion != null) { configuration().setDefaultLanguageVersion(languageVersion); } log.debug("discovered language: " + languageVersion); final File sourceCodeFile = file.getRawLocation().toFile(); if (included && getRuleSet().applies(sourceCodeFile) && isFileInWorkingSet(file) && languageVersion != null) { subTask("PMD checking: " + file.getName()); Timer timer = new Timer(); RuleContext context = PMD.newRuleContext(file.getName(), sourceCodeFile); context.setLanguageVersion(languageVersion); input = new InputStreamReader(file.getContents(), file.getCharset()); // getPmdEngine().processFile(input, getRuleSet(), context); // getPmdEngine().processFile(sourceCodeFile, getRuleSet(), context); RuleSets rSets = new RuleSets(getRuleSet()); new SourceCodeProcessor(configuration()).processSourceCode(input, rSets, context); timer.stop(); pmdDuration += timer.getDuration(); updateMarkers(file, context, isUseTaskMarker()); worked(1); fileCount++; } else { log.debug("The file " + file.getName() + " is not in the working set"); } } catch (CoreException e) { log.error("Core exception visiting " + file.getName(), e); // TODO: // complete message } catch (PMDException e) { log.error("PMD exception visiting " + file.getName(), e); // TODO: // complete message } catch (IOException e) { log.error("IO exception visiting " + file.getName(), e); // TODO: // complete message } catch (PropertiesException e) { log.error("Properties exception visiting " + file.getName(), e); // TODO: // complete message } finally { IOUtil.closeQuietly(input); } }
/** * Copies/moves a compilation unit with the name <code>newCUName</code> to the destination * package.<br> * The package statement in the compilation unit is updated if necessary. The main type of the * compilation unit is renamed if necessary. * * @exception JavaModelException if the operation is unable to complete */ private void processCompilationUnitResource(ICompilationUnit source, PackageFragment dest) throws JavaModelException { String newCUName = getNewNameFor(source); String destName = (newCUName != null) ? newCUName : source.getElementName(); TextEdit edit = updateContent(source, dest, newCUName); // null if unchanged // TODO (frederic) remove when bug 67606 will be fixed (bug 67823) // store encoding (fix bug 66898) IFile sourceResource = (IFile) source.getResource(); String sourceEncoding = null; try { sourceEncoding = sourceResource.getCharset(false); } catch (CoreException ce) { // no problem, use default encoding } // end todo // copy resource IContainer destFolder = (IContainer) dest.getResource(); // can be an IFolder or an IProject IFile destFile = destFolder.getFile(new Path(destName)); org.eclipse.jdt.internal.core.CompilationUnit destCU = new org.eclipse.jdt.internal.core.CompilationUnit( dest, destName, DefaultWorkingCopyOwner.PRIMARY); if (!destFile.equals(sourceResource)) { try { if (!destCU.isWorkingCopy()) { if (destFile.exists()) { if (this.force) { // we can remove it deleteResource(destFile, IResource.KEEP_HISTORY); destCU.close(); // ensure the in-memory buffer for the dest CU is closed } else { // abort throw new JavaModelException( new JavaModelStatus( IJavaModelStatusConstants.NAME_COLLISION, Messages.bind( Messages.status_nameCollision, destFile.getFullPath().toString()))); } } int flags = this.force ? IResource.FORCE : IResource.NONE; if (isMove()) { flags |= IResource.KEEP_HISTORY; sourceResource.move(destFile.getFullPath(), flags, getSubProgressMonitor(1)); } else { if (edit != null) flags |= IResource.KEEP_HISTORY; sourceResource.copy(destFile.getFullPath(), flags, getSubProgressMonitor(1)); } setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); } else { destCU.getBuffer().setContents(source.getBuffer().getContents()); } } catch (JavaModelException e) { throw e; } catch (CoreException e) { throw new JavaModelException(e); } // update new resource content if (edit != null) { boolean wasReadOnly = destFile.isReadOnly(); try { saveContent(dest, destName, edit, sourceEncoding, destFile); } catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); } finally { Util.setReadOnly(destFile, wasReadOnly); } } // register the correct change deltas prepareDeltas(source, destCU, isMove()); if (newCUName != null) { // the main type has been renamed String oldName = Util.getNameWithoutJavaLikeExtension(source.getElementName()); String newName = Util.getNameWithoutJavaLikeExtension(newCUName); prepareDeltas(source.getType(oldName), destCU.getType(newName), isMove()); } } else { if (!this.force) { throw new JavaModelException( new JavaModelStatus( IJavaModelStatusConstants.NAME_COLLISION, Messages.bind(Messages.status_nameCollision, destFile.getFullPath().toString()))); } // update new resource content // in case we do a saveas on the same resource we have to simply update the contents // see http://dev.eclipse.org/bugs/show_bug.cgi?id=9351 if (edit != null) { saveContent(dest, destName, edit, sourceEncoding, destFile); } } }