📄 ref.java
字号:
public static String getFileAbsolutePath(File f) {
try {
return f.getCanonicalPath();
} catch (IOException e) {
return f.getAbsolutePath();
}
}
/**
* Calls a method for an object
*
* @param obj the object with the method we want to call
* @param name the method name
* @param args the arguments received for the call
* @return the return of the method
*/
public static Object invoke(Object obj, String name, Object... args) {
//the args are not checked for the class because if a subclass is passed, the method is not correctly gotten
//another method might do it...
Method m = findMethod(obj, name, args);
return invoke(obj, m, args);
}
public static Object invoke(Object obj, Method m, Object... args) {
try {
return m.invoke(obj, args);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Method findMethod(Object obj, String name, Object... args) {
return findMethod(obj.getClass(), name, args);
}
public static Method findMethod(Class class_, String name, Object... args) {
try {
Method[] methods = class_.getMethods();
for (Method method : methods) {
Class[] parameterTypes = method.getParameterTypes();
if(method.getName().equals(name) && parameterTypes.length == args.length){
//check the parameters
int i = 0;
for (Class param : parameterTypes) {
if(!param.isInstance(args[i])){
continue;
}
i++;
}
//invoke it
return method;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
throw new RuntimeException("The method with name: "+name+" was not found (or maybe it was found but the parameters didn't match).");
}
public static char [] INVALID_FILESYSTEM_CHARS = {
'!', '@', '#', '$', '%', '^', '&', '*',
'(', ')', '[', ']', '{', '}', '=', '+',
'.', ' ', '`', '~', '\'', '"', ',', ';'};
public static boolean IN_TESTS = false;
public static String getValidProjectName(IProject project) {
String name = project.getName();
for (char c : INVALID_FILESYSTEM_CHARS) {
name = name.replace(c, '_');
}
return name;
}
/**
* Makes an equal comparisson taking into account that one of the parameters may be null.
*/
public static boolean nullEq(Object o1, Object o2){
if (o1 == null && o2 == null){
return true;
}
if(o1 == null || o2 == null){
return false;
}
return o1.equals(o2);
}
public static IDocument getDocFromFile(java.io.File f) throws IOException {
return getDocFromFile(f, true);
}
/**
* @return the document given its 'filesystem' file
* @throws IOException
*/
public static IDocument getDocFromFile(java.io.File f, boolean loadIfNotInWorkspace) throws IOException {
IPath path = Path.fromOSString(getFileAbsolutePath(f));
IDocument doc = getDocFromPath(path);
if (doc == null && loadIfNotInWorkspace) {
return getPythonDocFromFile(f);
}
return doc;
}
/**
* @return the document given its 'filesystem' file (checks for the declared python encoding in the file)
* @throws IOException
*/
private static IDocument getPythonDocFromFile(java.io.File f) throws IOException {
IDocument docFromPath = getDocFromPath(Path.fromOSString(getFileAbsolutePath(f)));
if(docFromPath != null){
return docFromPath;
}
FileInputStream stream = new FileInputStream(f);
String fileContents = "";
try {
String encoding = getPythonFileEncoding(f);
fileContents = getFileContents(stream, encoding, null);
} finally {
try { if(stream != null) stream.close(); } catch (Exception e) {Log.log(e);}
}
return new Document(fileContents);
}
/**
* @return null if it was unable to get the document from the path (this may happen if it was not refreshed).
* Or the document that represents the file
*/
public static IDocument getDocFromPath(IPath path) {
//TODO: make this better for 3.3/ 3.2 (and check if behaviour is correct now)
try{
try{
//eclipse 3.3 has a different interface
ITextFileBufferManager textFileBufferManager = ITextFileBufferManager.DEFAULT;
if(textFileBufferManager != null){//we don't have it in tests
ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(path, LocationKind.LOCATION);
if(textFileBuffer != null){ //we don't have it when it is not properly refreshed
return textFileBuffer.getDocument();
}
}
}catch(Throwable e){//NoSuchMethod/NoClassDef exception
if(e instanceof ClassNotFoundException || e instanceof LinkageError){
ITextFileBufferManager textFileBufferManager = FileBuffers.getTextFileBufferManager();
if(textFileBufferManager != null){//we don't have it in tests
ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(path);
if(textFileBuffer != null){ //we don't have it when it is not properly refreshed
return textFileBuffer.getDocument();
}
}
}else{
throw e;
}
}
return null;
}catch(Throwable e){
//private static final IWorkspaceRoot WORKSPACE_ROOT= ResourcesPlugin.getWorkspace().getRoot();
//throws an error and we don't even have access to the FileBuffers class in tests
if(!IN_TESTS ){
Log.log("Unable to get doc from text file buffer");
}
return null;
}
}
/**
* Returns a document, created with the contents of a resource (first tries to get from the 'FileBuffers',
* and if that fails, it creates one reading the file.
*/
public static IDocument getDocFromResource(IResource resource) {
IProject project = resource.getProject();
if (project != null && resource instanceof IFile && resource.exists()) {
IFile file = (IFile) resource;
try {
if(file.exists() && !file.isSynchronized(IResource.DEPTH_ZERO)){
file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
}
IPath path = file.getFullPath();
IDocument doc = getDocFromPath(path);
if(doc == null){
//can this actually happen?... yeap, it can
InputStream contents = file.getContents();
try {
int i = contents.available();
byte b[] = new byte[i];
contents.read(b);
doc = new Document(new String(b));
} finally{
contents.close();
}
}
return doc;
}catch(ResourceException e){
//it may stop existing from the initial exists check to the getContents call
return null;
} catch (Exception e) {
Log.log(e);
}
}
return null;
}
/**
* The encoding declared in the document is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/)
*/
public static String getPythonFileEncoding(IDocument doc, String fileLocation) throws IllegalCharsetNameException{
Reader inputStreamReader = new StringReader(doc.get());
return getPythonFileEncoding(inputStreamReader, fileLocation);
}
/**
* The encoding declared in the file is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/)
*/
public static String getPythonFileEncoding(File f) throws IllegalCharsetNameException{
try {
final FileInputStream fileInputStream = new FileInputStream(f);
try {
Reader inputStreamReader = new InputStreamReader(new BufferedInputStream(fileInputStream));
String pythonFileEncoding = getPythonFileEncoding(inputStreamReader, f.getAbsolutePath());
return pythonFileEncoding;
} finally {
//NOTE: the reader will be closed at 'getPythonFileEncoding'.
try { fileInputStream.close(); } catch (Exception e) {Log.log(e); }
}
} catch (FileNotFoundException e) {
return null;
}
}
/**
* The encoding declared in the reader is returned (according to the PEP: http://www.python.org/doc/peps/pep-0263/)
* -- may return null
*
* Will close the reader.
* @param fileLocation the file we want to get the encoding from (just passed for giving a better message if it fails -- may be null).
*/
public static String getPythonFileEncoding(Reader inputStreamReader, String fileLocation) throws IllegalCharsetNameException{
String ret = null;
BufferedReader reader = new BufferedReader(inputStreamReader);
try{
//pep defines that coding must be at 1st or second line: http://www.python.org/doc/peps/pep-0263/
String l1 = reader.readLine();
String l2 = reader.readLine();
String lEnc = null;
//encoding must be specified in first or second line...
if (l1 != null && l1.indexOf("coding") != -1){
lEnc = l1;
}
else if (l2 != null && l2.indexOf("coding") != -1){
lEnc = l2;
}
else{
ret = null;
}
if(lEnc != null){
lEnc = lEnc.trim();
if(lEnc.length() == 0){
ret = null;
}else if(lEnc.charAt(0) == '#'){ //it must be a comment line
//ok, the encoding line is in lEnc
Pattern p = Pattern.compile("coding[:=]+[\\s]*[\\w[\\-]]+[\\s]*");
Matcher matcher = p.matcher(lEnc);
if( matcher.find() ){
lEnc = lEnc.substring(matcher.start()+6);
char c;
while(lEnc.length() > 0 && ((c = lEnc.charAt(0)) == ' ' || c == ':' || c == '=')) {
lEnc = lEnc.substring(1);
}
StringBuffer buffer = new StringBuffer();
while(lEnc.length() > 0 && ((c = lEnc.charAt(0)) != ' ' || c == '-' || c == '*')) {
buffer.append(c);
lEnc = lEnc.substring(1);
}
ret = buffer.toString().trim();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {reader.close();} catch (IOException e1) {}
}
ret = getValidEncoding(ret, fileLocation);
return ret;
}
/**
* @param fileLocation may be null
*/
public static String getValidEncoding(String ret, String fileLocation) throws IllegalCharsetNameException{
if(ret == null){
return ret;
}
final String lower = ret.trim().toLowerCase();
if(lower.startsWith("latin")){
if(lower.indexOf("1") != -1){
return "latin1"; //latin1
}
}
if(lower.startsWith("utf")){
if(lower.endsWith("8")){
return "UTF-8"; //exact match
}
}
if(!Charset.isSupported(ret)){
if(LOG_ENCODING_ERROR){
String msg = "The encoding found: >>"+ret+"<< on "+fileLocation+" is not a valid encoding.";
Log.log(IStatus.ERROR, msg, new UnsupportedEncodingException(msg));
}
return null; //ok, we've been unable to make it supported (better return null than an unsupported encoding).
}
return ret;
}
/**
* Useful to silent it on tests
*/
public static boolean LOG_ENCODING_ERROR = true;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -