/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 net.sf.fast.ibatis.util;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.fast.ibatis.build.GenerateFileType;
import net.sf.fast.ibatis.model.FastIbatisConfig;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.Javadoc;
import org.eclipse.jdt.core.dom.TagElement;
import org.eclipse.jdt.core.dom.TextElement;
import org.json.simple.JSONObject;
/**
* <p>
* the Util class.
* </p>
*
* @author dan.zheng
* @version 1.0
*/
public class Utils {
/**
* strip the file extension.
*
* @param baseName
* the base file name.
* @return the stripped file name.
*/
public static String stripFileExtension(String baseName) {
String fileName = baseName;
if (baseName == null || baseName.trim().length() <= 0) {
return fileName;
}
// get the report design name, then extract the name without
// file extension and set it to fileName; otherwise do noting and
// let fileName with the default name
int dotIndex = baseName.lastIndexOf('.');
if (dotIndex > 0) {
fileName = baseName.substring(0, dotIndex);
}
return fileName;
}
/**
* remove the xml tag
*
* @param xmlPath
* the xml path.
* @param xmlFile
* the xml file name.
* @param javaFileName
* the java file name.
* @return
*/
public static String reduceJavaFilePath(String xmlPath, String xmlFile,
String javaFileName) {
int pos = xmlPath.indexOf("xml");
if (pos > -1) {
String str1 = xmlPath.substring(0, pos);
return str1 + javaFileName;
}
return null;
}
/**
* generate the service and dao file according to ibatis xml file name.
*
* @param xmlFile
* the xml file name.
* @param type
* the generate file type
* @return
*/
public static String convertIbatisXml2JavaFile(String xmlFile,
GenerateFileType type) {
if (xmlFile == null || xmlFile.length() == 0)
return null;
if (xmlFile.indexOf("SqlMap") > -1) {// if the file name is not with
// _SqlMap ending,don't do it
return null;
}
xmlFile = stripFileExtension(xmlFile);
StringBuffer sb = new StringBuffer();
if (xmlFile.indexOf("_") == -1) {
sb.append(upFirstChar(xmlFile.toLowerCase()));
} else {
String[] arrs = xmlFile.split("_");
if (arrs != null) {
for (String key : arrs) {
sb.append(upFirstChar(key.toLowerCase()));
}
}
}
String modelStr = sb.toString();
if (type == GenerateFileType.Service_Interface) {// service
return "service" + File.separator + modelStr + "Service.java";
} else if (type == GenerateFileType.Service_Implementation) {// ServiceImpl
return "service" + File.separator + "impl" + File.separator
+ modelStr + "ServiceImpl.java";
} else if (type == GenerateFileType.DAO_Interface) {// DAO
return "dao" + File.separator + modelStr + "DAO.java";
} else if (type == GenerateFileType.DAO_Implementation) {// DAOImpl
return "dao" + File.separator + modelStr + "DAOImpl.java";
}
return null;
}
/**
* convert the comment content to javadoc.
*
* @param ast
* the eclipse ast.
* @param comment
* the method comment content.
* @return
*/
@SuppressWarnings("unchecked")
public static Javadoc getJavadoc(AST ast, String comment) {
if (comment != null && comment.length() > 0) {
Javadoc jc = ast.newJavadoc();
TagElement tag = ast.newTagElement();
TextElement te = ast.newTextElement();
tag.fragments().add(te);
te.setText(formatJavadoc(comment));
jc.tags().add(tag);
return jc;
}
return null;
}
/**
* format the javadoc
*
* @param comment
* comment the method comment content.
* @return the formatted javadoc.
*/
private static String formatJavadoc(String comment) {
StringBuffer sb = new StringBuffer("");
StringTokenizer st = new StringTokenizer(comment, "\n");
for (int i = 0; st.hasMoreTokens(); i++) {
String _tmp = st.nextToken().trim();
if (i > 0 && _tmp != null && _tmp.length() > 0)
sb.append("* ").append(_tmp).append("\n");
else if (i == 0)
sb.append(_tmp).append("\n");
}
return sb.toString().trim();
}
public static IFile getSuitableIFile(String xmlFilePath,
String xmlFileName, GenerateFileType type) {
String a1 = Utils.convertIbatisXml2JavaFile(xmlFileName, type);
String a2 = Utils.reduceJavaFilePath(xmlFilePath, xmlFileName, a1);
IFile a3 = Utils.getModelFileFromPath(a2);
return a3;
}
/**
* judge the pending generated method is exist.
*
* @param cu
* generally,it is means the java class.
* @param outMethodName
* the method name
* @return
*/
public static boolean isMethodExist(ICompilationUnit cu,
String outMethodName) {
IType classType = cu.findPrimaryType();
try {
IMethod[] methods = classType.getMethods();
if (methods != null) {
for (IMethod method : methods) {
String methodName = method.getElementName();
if (methodName != null && methodName.equals(outMethodName))
return true;
}
}
} catch (Exception e) {
}
return false;
}
/**
* write the generated code content to the specific file name.
*
* @param fileName
* the generated file name.
* @param content
* the java class code content.
*/
public static void writeContent(String fileName, String content) {
try {
OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(fileName),"UTF-8");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static String convert(byte[] data, String charset) {
InputStreamReader isr = null;
StringBuilder sb = new StringBuilder();
try {
isr = new InputStreamReader(new ByteArrayInputStream(data), charset);
while (isr.ready()) {
sb.append((char) isr.read());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
/**
* resovle the xml file and return the model name.
*
* @param xmlFile
* the ibatis xml file.
* @return return the resolved model name.
*/
public static String getModelName(String xmlFile) {
if (xmlFile == null || xmlFile.length() == 0)
return null;
if (xmlFile.indexOf("SqlMap") > -1) {
return null;
}
xmlFile = stripFileExtension(xmlFile);
StringBuffer sb = new StringBuffer();
if (xmlFile.indexOf("_") == -1) {
sb.append(upFirstChar(xmlFile.toLowerCase()));
} else {
String[] arrs = xmlFile.split("_");
if (arrs != null) {
for (String key : arrs) {
sb.append(upFirstChar(key.toLowerCase()));
}
}
}
String modelStr = sb.toString();
return modelStr;
}
public static String getMapperFileName(String base, String pattern,
FastIbatisConfig fc) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(base);
if (m.find()) {
if (fc != null) {
fc.setModelName(m.group(1));
}
return m.group();
}
return "";
}
public static String getJsonValue(JSONObject obj, String key,
String defaultValue) {
if (obj == null || obj.get(key) == null) {
return defaultValue;
}
return (String) obj.get(key);
}
public static void findFile(String name, File file, StringBuilder sb) {
File[] list = file.listFiles();
if (list != null) {
for (File fil : list) {
if (fil.isDirectory()) {
findFile(name, fil, sb);
} else if (name.equalsIgnoreCase(fil.getName())) {
sb.append(fil.getAbsolutePath());
}
}
}
}
/**
* uppercase the first character of string.
*
* @param str
* the string
* @return the string with first character uppercase.
*/
public static String upFirstChar(String str) {
if (str == null || str.length() == 0)
return str;
StringBuffer sb = new StringBuffer();
if (str != null && str.length() > 0) {
String ss = str.charAt(0) + "";
sb.append(ss.toUpperCase());
}
sb.append(str.substring(1));
return sb.toString();
}
/**
* lowercase the first character of string.
*
* @param str
* the string
* @return the string with first character lowercase.
*/
public static String lowFirstChar(String str) {
if (str == null || str.length() == 0)
return str;
StringBuffer sb = new StringBuffer();
if (str != null && str.length() > 0) {
String ss = str.charAt(0) + "";
sb.append(ss.toLowerCase());
}
sb.append(str.substring(1));
return sb.toString();
}
/**
* resolve the file path to get the model file.
*
* @param filePath
* the file path.
* @return the model file.
*/
public static IFile getModelFileFromPath(String filePath) {
IFile file = null;
try {
if (filePath != null) {
file = ResourcesPlugin
.getWorkspace()
.getRoot()
.getFileForLocation(
new org.eclipse.core.runtime.Path(filePath));
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
public static IFile getFileFromPath(String filePath) {
IFile file = null;
try {
if (filePath != null) {
file = ResourcesPlugin
.getWorkspace()
.getRoot()
.getFileForLocation(
new org.eclipse.core.runtime.Path(filePath));
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase()+" ");
}
return sb.toString();
}
public static void main(String args[]) throws Exception {
byte[] arr = new byte[]{(byte)0xD6, (byte)0xD0, (byte)0xB9, (byte)0xFA};
byte[] arr1 = convert(arr, "GBK").getBytes("UTF-8");
System.out.println(toHexString(convert(arr, "GBK").getBytes("UTF-8")));
System.out.println(toHexString(convert(arr1, "UTF-8").getBytes()));
System.out.println(convert(arr1, "UTF-8"));
System.out.println("中国");
}
}