Commits

Robert Massaioli [Atlassian] committed 51c52f1

Ran the autoformatter over all of the code.

Comments (0)

Files changed (5)

LibAndroTranslation/src/shoozhoo/libandrotranslation/GoogleLanguageClient.java

 
 /*
  * Google Language API Client
- *
+ * 
  * http://code.google.com/intl/ja/apis/language/
  */
-public abstract class GoogleLanguageClient extends AsyncTask<String, Void, JSONObject>{
-	private static final String GoogleLanguageURL = "https://ajax.googleapis.com/ajax/services/language/translate";
-	private static final String JsonParamData = "responseData";
-	private static final String JsonParamTranslated = "translatedText";
-	private static final String JsonParamStatus = "responseStatus";
-	private static final String JsonParamDetails = "responseDetails";
-
-
-	private DefaultHttpClient client;
-	private String toLang;
-
-	public GoogleLanguageClient(String toLang){
-		this.toLang = toLang;
-		this.client = new DefaultHttpClient();
-		this.client.getParams().setIntParameter("http.socket.timeout", 10*1000);
-		this.client.getParams().setIntParameter("http.connection.timeout", 10*1000);
-	}
-
-	@Override
-	protected JSONObject doInBackground(String... params) {
-		try{
-			String str = params[0];
-			HttpResponse res = transRequest(str, this.toLang);
-			if(res.getStatusLine().getStatusCode()!=200){
-				JSONObject jo = new JSONObject();
-				jo.put(JsonParamData, null);
-				jo.put(JsonParamStatus, res.getStatusLine().getStatusCode());
-				jo.put(JsonParamDetails, res.getStatusLine().getReasonPhrase());
-				return jo;
-			}
-
-			String strJson = EntityUtils.toString(res.getEntity());
-			//AppTransUtil.log("Res "+strJson);
-			JSONObject jo = new JSONObject(strJson);
-			return jo;
-
-		}catch (Exception e) {
-			LibAndTransUtil.log("Translation request error.", e);
-			JSONObject jo = new JSONObject();
-			try{
-				jo.put(JsonParamData, null);
-				jo.put(JsonParamStatus, 0);
-				jo.put(JsonParamDetails, e.getMessage());
-				return jo;
-			}catch (Exception ex) {
-				LibAndTransUtil.log("Json error.", ex);
-				return null;
-			}
-		}
-	}
-
-	/*
-	 * status 200 is OK. Other errors.
-	 */
-	public abstract void onExecute(String translation, int status, String details);
-
-	@Override
-	protected void onPostExecute(JSONObject result) {
-		if(result==null){
-			onExecute(null, 0, null);
-			return;
-		}
-
-		/* Response JSON Example
-		 * {
-		 *  "responseData": {
-		 *    "translatedText": "Hola, mi amigo!"
-		 *  },
-		 *   "responseDetails": null,
-		 *  "responseStatus": 200
-		 * }
-		 */
-		try{
-			String trans = null;
-			JSONObject o = null;
-			try{
-				o = result.getJSONObject(JsonParamData);
-			}catch (Exception e) {}
-			if(o!=null){
-				trans = o.getString(JsonParamTranslated);
-			}
-			int status = result.getInt(JsonParamStatus);
-			String details = result.getString(JsonParamDetails);
-			onExecute(trans, status, details);
-
-		}catch (Exception e) {
-			LibAndTransUtil.log("Json error", e);
-			onExecute(null, 0, e.getMessage());
-			return;
-		}
-	}
-
-	private HttpResponse transRequest(String str, String toLang) throws IOException{
-		StringBuilder buf = new StringBuilder(GoogleLanguageURL);
-		buf.append("?v=1.0");
-		try{
-			buf.append("&q="+URLEncoder.encode(str, "UTF-8"));
-		}catch (Exception e) {}
-		buf.append("&langpair=%7C"+toLang); // the source language is auto-detect
-		LibAndTransUtil.log("Req "+buf.toString());
-		HttpGet req = new HttpGet(buf.toString());
-		return httpExecute(req);
-	}
-
-	private HttpResponse httpExecute(HttpRequestBase base) throws IOException{
-		try{
-			return this.client.execute(base);
-		}catch (IOException e) {
-			base.abort();
-			throw e;
-		}
-	}
+public abstract class GoogleLanguageClient extends AsyncTask<String, Void, JSONObject> {
+    private static final String GoogleLanguageURL   = "https://ajax.googleapis.com/ajax/services/language/translate";
+    private static final String JsonParamData       = "responseData";
+    private static final String JsonParamTranslated = "translatedText";
+    private static final String JsonParamStatus     = "responseStatus";
+    private static final String JsonParamDetails    = "responseDetails";
+
+    private DefaultHttpClient   client;
+    private String              toLang;
+
+    public GoogleLanguageClient(String toLang) {
+        this.toLang = toLang;
+        this.client = new DefaultHttpClient();
+        this.client.getParams().setIntParameter("http.socket.timeout", 10 * 1000);
+        this.client.getParams().setIntParameter("http.connection.timeout", 10 * 1000);
+    }
+
+    @Override
+    protected JSONObject doInBackground(String... params) {
+        try {
+            String str = params[0];
+            HttpResponse res = transRequest(str, this.toLang);
+            if (res.getStatusLine().getStatusCode() != 200) {
+                JSONObject jo = new JSONObject();
+                jo.put(JsonParamData, null);
+                jo.put(JsonParamStatus, res.getStatusLine().getStatusCode());
+                jo.put(JsonParamDetails, res.getStatusLine().getReasonPhrase());
+                return jo;
+            }
+
+            String strJson = EntityUtils.toString(res.getEntity());
+            // AppTransUtil.log("Res "+strJson);
+            JSONObject jo = new JSONObject(strJson);
+            return jo;
+
+        } catch (Exception e) {
+            LibAndTransUtil.log("Translation request error.", e);
+            JSONObject jo = new JSONObject();
+            try {
+                jo.put(JsonParamData, null);
+                jo.put(JsonParamStatus, 0);
+                jo.put(JsonParamDetails, e.getMessage());
+                return jo;
+            } catch (Exception ex) {
+                LibAndTransUtil.log("Json error.", ex);
+                return null;
+            }
+        }
+    }
+
+    /*
+     * status 200 is OK. Other errors.
+     */
+    public abstract void onExecute(String translation, int status, String details);
+
+    @Override
+    protected void onPostExecute(JSONObject result) {
+        if (result == null) {
+            onExecute(null, 0, null);
+            return;
+        }
+
+        /*
+         * Response JSON Example { "responseData": { "translatedText": "Hola, mi amigo!" }, "responseDetails": null, "responseStatus": 200 }
+         */
+        try {
+            String trans = null;
+            JSONObject o = null;
+            try {
+                o = result.getJSONObject(JsonParamData);
+            } catch (Exception e) {}
+            if (o != null) {
+                trans = o.getString(JsonParamTranslated);
+            }
+            int status = result.getInt(JsonParamStatus);
+            String details = result.getString(JsonParamDetails);
+            onExecute(trans, status, details);
+
+        } catch (Exception e) {
+            LibAndTransUtil.log("Json error", e);
+            onExecute(null, 0, e.getMessage());
+            return;
+        }
+    }
+
+    private HttpResponse transRequest(String str, String toLang) throws IOException {
+        StringBuilder buf = new StringBuilder(GoogleLanguageURL);
+        buf.append("?v=1.0");
+        try {
+            buf.append("&q=" + URLEncoder.encode(str, "UTF-8"));
+        } catch (Exception e) {}
+        buf.append("&langpair=%7C" + toLang); // the source language is auto-detect
+        LibAndTransUtil.log("Req " + buf.toString());
+        HttpGet req = new HttpGet(buf.toString());
+        return httpExecute(req);
+    }
+
+    private HttpResponse httpExecute(HttpRequestBase base) throws IOException {
+        try {
+            return this.client.execute(base);
+        } catch (IOException e) {
+            base.abort();
+            throw e;
+        }
+    }
 
 }

LibAndroTranslation/src/shoozhoo/libandrotranslation/LibAndTransException.java

 
 public class LibAndTransException extends Exception {
 
-	/**
+    /**
 	 *
 	 */
-	private static final long serialVersionUID = -4279277193105213343L;
+    private static final long serialVersionUID = -4279277193105213343L;
 
-	public LibAndTransException() {
-		super();
-	}
+    public LibAndTransException() {
+        super();
+    }
 
-	public LibAndTransException(String detailMessage, Throwable throwable) {
-		super(detailMessage, throwable);
-	}
+    public LibAndTransException(String detailMessage, Throwable throwable) {
+        super(detailMessage, throwable);
+    }
 
-	public LibAndTransException(String detailMessage) {
-		super(detailMessage);
-	}
+    public LibAndTransException(String detailMessage) {
+        super(detailMessage);
+    }
 
-	public LibAndTransException(Throwable throwable) {
-		super(throwable);
-	}
+    public LibAndTransException(Throwable throwable) {
+        super(throwable);
+    }
 
 }

LibAndroTranslation/src/shoozhoo/libandrotranslation/LibAndTransUtil.java

 import android.util.Log;
 
 public class LibAndTransUtil {
-	public static void log(String s){
-		Log.i("LibAndroTrans", s);
-	}
-	public static void log(String s, Throwable t){
-		Log.i("LibAndroTrans", s, t);
-	}
-	public static void safeclose(Closeable c){
-		if(c!=null){
-			try{
-				c.close();
-			}catch (Exception e) {}
-		}
-	}
-
-	private static String KEY_APPTRANSLATION = "KEY_APPTRANSLATION";
-	private static String KEY_LANG = "KEY_LANG";
-	public static String getTranslationLang(Context ctx){
-		SharedPreferences pref = ctx.getSharedPreferences(KEY_APPTRANSLATION, Context.MODE_PRIVATE);
-		if(pref==null){
-			return "";
-		}
-		return pref.getString(KEY_LANG, Locale.getDefault().getLanguage());
-	}
-	public static void saveTranslationLang(Context ctx, String lang){
-		SharedPreferences pref = ctx.getSharedPreferences(KEY_APPTRANSLATION, Context.MODE_PRIVATE);
-		Editor editor = pref.edit();
-		editor.putString(KEY_LANG, lang);
-		editor.commit();
-	}
+    public static void log(String s) {
+        Log.i("LibAndroTrans", s);
+    }
+
+    public static void log(String s, Throwable t) {
+        Log.i("LibAndroTrans", s, t);
+    }
+
+    public static void safeclose(Closeable c) {
+        if (c != null) {
+            try {
+                c.close();
+            } catch (Exception e) {}
+        }
+    }
+
+    private static String KEY_APPTRANSLATION = "KEY_APPTRANSLATION";
+    private static String KEY_LANG           = "KEY_LANG";
+
+    public static String getTranslationLang(Context ctx) {
+        SharedPreferences pref = ctx.getSharedPreferences(KEY_APPTRANSLATION, Context.MODE_PRIVATE);
+        if (pref == null) {
+            return "";
+        }
+        return pref.getString(KEY_LANG, Locale.getDefault().getLanguage());
+    }
+
+    public static void saveTranslationLang(Context ctx, String lang) {
+        SharedPreferences pref = ctx.getSharedPreferences(KEY_APPTRANSLATION, Context.MODE_PRIVATE);
+        Editor editor = pref.edit();
+        editor.putString(KEY_LANG, lang);
+        editor.commit();
+    }
 }

LibAndroTranslation/src/shoozhoo/libandrotranslation/StringRes.java

 import android.os.Parcel;
 import android.os.Parcelable;
 
-public class StringRes implements Parcelable{
-	private String resourceName;
-	private int resId;
-	private String defString;
-	private String userString;
-
-	public StringRes(String resName, int resId, String defStr, String userString){
-		this.resourceName = resName;
-		this.resId = resId;
-		this.defString = defStr;
-		this.userString = userString;
-	}
-
-	public String getResourceName() {
-		return resourceName;
-	}
-	public void setResourceName(String resourceName) {
-		this.resourceName = resourceName;
-	}
-	public int getResId() {
-		return resId;
-	}
-	public void setResId(int resId) {
-		this.resId = resId;
-	}
-	public String getDefString() {
-		return defString;
-	}
-	public void setDefString(String defString) {
-		this.defString = defString;
-	}
-	public String getUserString() {
-		return userString;
-	}
-	public void setUserString(String userString) {
-		this.userString = userString;
-	}
-
-	public static final Parcelable.Creator<StringRes> CREATOR
-	= new Parcelable.Creator<StringRes>() {
-		public StringRes createFromParcel(Parcel in) {
-			return new StringRes(in);
-		}
-
-		public StringRes[] newArray(int size) {
-			return new StringRes[size];
-		}
-	};
-
-	private StringRes(Parcel in){
-		resourceName = in.readString();
-		resId = in.readInt();
-		defString = in.readString();
-		userString = in.readString();
-	}
-
-	public int describeContents() {
-		return 0;
-	}
-
-	public void writeToParcel(Parcel dest, int flags) {
-		dest.writeString(resourceName);
-		dest.writeInt(resId);
-		dest.writeString(defString);
-		dest.writeString(userString);
-	}
+public class StringRes implements Parcelable {
+    private String resourceName;
+    private int    resId;
+    private String defString;
+    private String userString;
 
+    public StringRes(String resName, int resId, String defStr, String userString) {
+        this.resourceName = resName;
+        this.resId = resId;
+        this.defString = defStr;
+        this.userString = userString;
+    }
+
+    public String getResourceName() {
+        return resourceName;
+    }
+
+    public void setResourceName(String resourceName) {
+        this.resourceName = resourceName;
+    }
+
+    public int getResId() {
+        return resId;
+    }
+
+    public void setResId(int resId) {
+        this.resId = resId;
+    }
+
+    public String getDefString() {
+        return defString;
+    }
+
+    public void setDefString(String defString) {
+        this.defString = defString;
+    }
+
+    public String getUserString() {
+        return userString;
+    }
+
+    public void setUserString(String userString) {
+        this.userString = userString;
+    }
+
+    public static final Parcelable.Creator<StringRes> CREATOR = new Parcelable.Creator<StringRes>() {
+                                                                  public StringRes createFromParcel(Parcel in) {
+                                                                      return new StringRes(in);
+                                                                  }
+
+                                                                  public StringRes[] newArray(int size) {
+                                                                      return new StringRes[size];
+                                                                  }
+                                                              };
+
+    private StringRes(Parcel in) {
+        resourceName = in.readString();
+        resId = in.readInt();
+        defString = in.readString();
+        userString = in.readString();
+    }
+
+    public int describeContents() {
+        return 0;
+    }
+
+    public void writeToParcel(Parcel dest, int flags) {
+        dest.writeString(resourceName);
+        dest.writeInt(resId);
+        dest.writeString(defString);
+        dest.writeString(userString);
+    }
 
 }

LibAndroTranslation/src/shoozhoo/libandrotranslation/StringResources.java

 import android.util.Xml;
 
 public class StringResources {
-	public static final String USER_SAVE_DIR = Environment.getExternalStorageDirectory()+"/MyTranslation";
-
-	private List<String> pkgList = new ArrayList<String>();
-
-	// key:packageName
-	private Map<String,List<StringRes>> resources = new TreeMap<String, List<StringRes>>();
-
-	private Map<Integer, StringRes> id2res = new HashMap<Integer, StringRes>();
-	private boolean ignoreSelfResource = true;
-	private String dir = USER_SAVE_DIR;
-	private List<String> ignorePatterns = new ArrayList<String>();
-
-	public StringResources(String packageName){
-		pkgList.add(packageName);
-	}
-
-	public StringResources(List<String> packageList){
-		pkgList.addAll(packageList);
-	}
-
-	/*
-	 * Translation file is saved this dir.
-	 */
-	public void setDir(String d){
-		this.dir = d;
-	}
-	public void addIgnorePattern(String pattern){
-		this.ignorePatterns.add(pattern);
-	}
-	public void setIgnorePatterns(List<String> patterns){
-		if(patterns==null){
-			this.ignorePatterns.clear();
-		}else{
-			this.ignorePatterns = patterns;
-		}
-	}
-
-	/*
-	 * True when specified resource name is ignore pattern.
-	 */
-	private boolean matchIgnorePattern(String resName){
-		if(resName==null){
-			return false;
-		}
-		for (String pattern : this.ignorePatterns) {
-			if(resName.matches(pattern)){
-				return true;
-			}
-		}
-		return false;
-	}
-
-
-	/*
-	 * Get user translation string from R.id .
-	 */
-//	public String getString(int resId){
-//		if(id2res.isEmpty()){
-//			return null;
-//		}
-//		StringRes res = id2res.get(resId);
-//		if(res==null){
-//			return null;
-//		}
-//		return res.getUserString();
-//	}
-
-	/*
-	 * All clear user translation.
-	 */
-	public void clear(){
-		for(String key : resources.keySet()){
-			List<StringRes> list = resources.get(key);
-			for (StringRes strRes : list) {
-				strRes.setUserString("");
-			}
-		}
-	}
-
-	/*
-	 * Update user translation.
-	 */
-	public void updateStringResource(StringRes res){
-		if(res==null){
-			return;
-		}
-		for(String key : resources.keySet()){
-			List<StringRes> list = resources.get(key);
-			for (StringRes strRes : list) {
-				if(strRes.getResourceName().equals(res.getResourceName())){
-					strRes.setUserString(res.getUserString());
-					return;
-				}
-			}
-		}
-	}
-
-	/*
-	 * Load R.string and user translation file.
-	 */
-	public void loadStringResources(Context ctx) throws LibAndTransException{
-		LibAndTransUtil.log("Pkg "+this.pkgList.size());
-		for (String pkg : this.pkgList) {
-			List<StringRes> rstrList = this.readRString(ctx, pkg);
-
-			Map<String, String> userResMap = readUserResource(ctx, pkg);
-			for (StringRes res : rstrList) {
-				String translation = userResMap.get(res.getResourceName());
-				if(translation!=null){
-					res.setUserString(translation);
-					id2res.put(res.getResId(), res);
-				}
-			}
-			resources.put(pkg, rstrList);
-		}
-	}
-
-	/*
-	 * Get R.string and user translation.
-	 */
-	public List<StringRes> getStringResources(){
-		List<StringRes> rval = new ArrayList<StringRes>();
-		for (List<StringRes> list : resources.values()) {
-			rval.addAll(list);
-		}
-		return rval;
-	}
-
-
-	/*
-	 * Get R.string by reflection.
-	 */
-	private List<StringRes> readRString(Context ctx, String pkg) throws LibAndTransException{
-		LibAndTransUtil.log("readRString "+pkg);
-		List<StringRes> rval = new ArrayList<StringRes>();
-		String fName = null;
-		try{
-			Class<?> cls = Class.forName(pkg+".R$string");
-			Field[] flds = cls.getFields();
-			for (Field f : flds) {
-				try{
-					int id = f.getInt(null);
-					fName = f.getName();
-					StringRes res = new StringRes(fName,id, ctx.getString(id), "");
-					if(matchIgnorePattern(res.getResourceName())
-							||(this.ignoreSelfResource
-									&& res.getResourceName().startsWith("zzlibandrotranslation_"))){
-						continue;
-					}
-					rval.add(res);
-				}catch (Exception e) {
-					LibAndTransUtil.log("##### R.string.("+fName+") reflection error.",e);
-				}
-			}
-		}catch (Exception e) {
-			throw new LibAndTransException("readRString Error.",e);
-		}
-		return rval;
-
-	}
-
-	/*
-	 * Read user translations from property file.
-	 */
-	private Map<String, String> readUserResource(Context ctx, String pkg) throws LibAndTransException{
-		HashMap<String, String> rval = new HashMap<String, String>();
-		File f = userResourceFile(ctx, pkg, this.dir);
-		if(!f.exists()){
-			return rval;
-		}
-		Properties prop = new Properties();
-
-		FileInputStream fis = null;
-		BufferedInputStream bis = null;
-		try{
-			fis = new FileInputStream(f);
-			bis = new BufferedInputStream(fis);
-			prop.load(bis);
-
-			for(Object key : prop.keySet()){
-				String skey = (String)key;
-				rval.put(skey, prop.getProperty(skey, ""));
-			}
-			return rval;
-		}catch (Exception e) {
-			LibAndTransUtil.log(e.getMessage());
-			throw new LibAndTransException("", e);
-		}finally{
-			LibAndTransUtil.safeclose(bis);
-			LibAndTransUtil.safeclose(fis);
-		}
-	}
-
-	/*
-	 * Save user translations to property file.
-	 */
-	public void saveUserResource(Context ctx) throws LibAndTransException{
-		for (String pkg : this.pkgList) {
-			saveUserResource(ctx, pkg);
-		}
-	}
-	private void saveUserResource(Context ctx, String pkg) throws LibAndTransException{
-		List<StringRes> list = this.resources.get(pkg);
-		if(list==null){
-			return;
-		}
-		File d = new File(this.dir);
-		d.mkdirs();
-		File f = userResourceFile(ctx, pkg, this.dir);
-		Properties prop = new Properties();
-		for (StringRes res : list) {
-			if(res.getUserString()==null || res.getUserString().matches("\\s*")){
-				continue;
-			}
-			prop.setProperty(res.getResourceName(), res.getUserString());
-		}
-		FileOutputStream fos = null;
-		try{
-			fos = new FileOutputStream(f);
-			prop.save(fos, "AppTrans");
-		}catch (Exception e) {
-			LibAndTransUtil.log(e.getMessage());
-			throw new LibAndTransException("", e);
-		}finally{
-			LibAndTransUtil.safeclose(fos);
-		}
-
-	}
-
-	public Uri getTranslationXmlFile(Context ctx, String pkg){
-		return save2xml(ctx, pkg);
-	}
-
-	/*
-	 * Save to XML file, and return its Uri.
-	 */
-	private Uri save2xml(Context ctx, String pkg){
-		List<StringRes> list = this.resources.get(pkg);
-		if(list==null){
-			return null;
-		}
-		File d = new File(this.dir);
-		d.mkdirs();
-
-		XmlSerializer serializer = Xml.newSerializer();
-		FileWriter fw = null;
-		try {
-			File file = xmlFile(ctx, pkg, this.dir);
-			fw = new FileWriter(file);
-			try{
-				serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
-			}catch (Exception e) {}
-			serializer.setOutput(fw);
-			serializer.startDocument("UTF-8", true);
-			serializer.startTag("", "resources");
-			for (StringRes res : list) {
-				if(res.getUserString()==null || res.getUserString().matches("\\s*")){
-					continue;
-				}
-				serializer.startTag("", "string");
-				serializer.attribute("", "name", res.getResourceName());
-				String text = res.getUserString().replaceAll("\"", "\\\\\"");
-				serializer.text("\""+text+"\"");
-				serializer.endTag("", "string");
-			}
-			serializer.endTag("", "resources");
-			serializer.endDocument();
-			return Uri.fromFile(file);
-		} catch (Exception e) {
-			throw new RuntimeException(e);
-		} finally{
-			LibAndTransUtil.safeclose(fw);
-		}
-
-	}
-	private static File xmlFile(Context ctx, String pkg, String dir){
-		return new File(dir, "string_"+ctx.getPackageName()+".xml");
-	}
-	private static File userResourceFile(Context ctx, String pkg, String dir){
-		return new File(dir, ctx.getPackageName()+"_"+pkg+".properties");
-	}
-
-	public boolean isIgnoreSelfResource() {
-		return ignoreSelfResource;
-	}
-
-	/*
-	 * If you want to translation LibAndroTranslation's resource, set true.
-	 */
-	public void setIgnoreSelfResource(boolean ignoreSelfResource) {
-		this.ignoreSelfResource = ignoreSelfResource;
-	}
+    public static final String           USER_SAVE_DIR      = Environment.getExternalStorageDirectory() + "/MyTranslation";
+
+    private List<String>                 pkgList            = new ArrayList<String>();
+
+    // key:packageName
+    private Map<String, List<StringRes>> resources          = new TreeMap<String, List<StringRes>>();
+
+    private Map<Integer, StringRes>      id2res             = new HashMap<Integer, StringRes>();
+    private boolean                      ignoreSelfResource = true;
+    private String                       dir                = USER_SAVE_DIR;
+    private List<String>                 ignorePatterns     = new ArrayList<String>();
+
+    public StringResources(String packageName) {
+        pkgList.add(packageName);
+    }
+
+    public StringResources(List<String> packageList) {
+        pkgList.addAll(packageList);
+    }
+
+    /*
+     * Translation file is saved this dir.
+     */
+    public void setDir(String d) {
+        this.dir = d;
+    }
+
+    public void addIgnorePattern(String pattern) {
+        this.ignorePatterns.add(pattern);
+    }
+
+    public void setIgnorePatterns(List<String> patterns) {
+        if (patterns == null) {
+            this.ignorePatterns.clear();
+        } else {
+            this.ignorePatterns = patterns;
+        }
+    }
+
+    /*
+     * True when specified resource name is ignore pattern.
+     */
+    private boolean matchIgnorePattern(String resName) {
+        if (resName == null) {
+            return false;
+        }
+        for (String pattern : this.ignorePatterns) {
+            if (resName.matches(pattern)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /*
+     * Get user translation string from R.id .
+     */
+    // public String getString(int resId){
+    // if(id2res.isEmpty()){
+    // return null;
+    // }
+    // StringRes res = id2res.get(resId);
+    // if(res==null){
+    // return null;
+    // }
+    // return res.getUserString();
+    // }
+
+    /*
+     * All clear user translation.
+     */
+    public void clear() {
+        for (String key : resources.keySet()) {
+            List<StringRes> list = resources.get(key);
+            for (StringRes strRes : list) {
+                strRes.setUserString("");
+            }
+        }
+    }
+
+    /*
+     * Update user translation.
+     */
+    public void updateStringResource(StringRes res) {
+        if (res == null) {
+            return;
+        }
+        for (String key : resources.keySet()) {
+            List<StringRes> list = resources.get(key);
+            for (StringRes strRes : list) {
+                if (strRes.getResourceName().equals(res.getResourceName())) {
+                    strRes.setUserString(res.getUserString());
+                    return;
+                }
+            }
+        }
+    }
+
+    /*
+     * Load R.string and user translation file.
+     */
+    public void loadStringResources(Context ctx) throws LibAndTransException {
+        LibAndTransUtil.log("Pkg " + this.pkgList.size());
+        for (String pkg : this.pkgList) {
+            List<StringRes> rstrList = this.readRString(ctx, pkg);
+
+            Map<String, String> userResMap = readUserResource(ctx, pkg);
+            for (StringRes res : rstrList) {
+                String translation = userResMap.get(res.getResourceName());
+                if (translation != null) {
+                    res.setUserString(translation);
+                    id2res.put(res.getResId(), res);
+                }
+            }
+            resources.put(pkg, rstrList);
+        }
+    }
+
+    /*
+     * Get R.string and user translation.
+     */
+    public List<StringRes> getStringResources() {
+        List<StringRes> rval = new ArrayList<StringRes>();
+        for (List<StringRes> list : resources.values()) {
+            rval.addAll(list);
+        }
+        return rval;
+    }
+
+    /*
+     * Get R.string by reflection.
+     */
+    private List<StringRes> readRString(Context ctx, String pkg) throws LibAndTransException {
+        LibAndTransUtil.log("readRString " + pkg);
+        List<StringRes> rval = new ArrayList<StringRes>();
+        String fName = null;
+        try {
+            Class<?> cls = Class.forName(pkg + ".R$string");
+            Field[] flds = cls.getFields();
+            for (Field f : flds) {
+                try {
+                    int id = f.getInt(null);
+                    fName = f.getName();
+                    StringRes res = new StringRes(fName, id, ctx.getString(id), "");
+                    if (matchIgnorePattern(res.getResourceName()) || (this.ignoreSelfResource && res.getResourceName().startsWith("zzlibandrotranslation_"))) {
+                        continue;
+                    }
+                    rval.add(res);
+                } catch (Exception e) {
+                    LibAndTransUtil.log("##### R.string.(" + fName + ") reflection error.", e);
+                }
+            }
+        } catch (Exception e) {
+            throw new LibAndTransException("readRString Error.", e);
+        }
+        return rval;
+
+    }
+
+    /*
+     * Read user translations from property file.
+     */
+    private Map<String, String> readUserResource(Context ctx, String pkg) throws LibAndTransException {
+        HashMap<String, String> rval = new HashMap<String, String>();
+        File f = userResourceFile(ctx, pkg, this.dir);
+        if (!f.exists()) {
+            return rval;
+        }
+        Properties prop = new Properties();
+
+        FileInputStream fis = null;
+        BufferedInputStream bis = null;
+        try {
+            fis = new FileInputStream(f);
+            bis = new BufferedInputStream(fis);
+            prop.load(bis);
+
+            for (Object key : prop.keySet()) {
+                String skey = (String) key;
+                rval.put(skey, prop.getProperty(skey, ""));
+            }
+            return rval;
+        } catch (Exception e) {
+            LibAndTransUtil.log(e.getMessage());
+            throw new LibAndTransException("", e);
+        } finally {
+            LibAndTransUtil.safeclose(bis);
+            LibAndTransUtil.safeclose(fis);
+        }
+    }
+
+    /*
+     * Save user translations to property file.
+     */
+    public void saveUserResource(Context ctx) throws LibAndTransException {
+        for (String pkg : this.pkgList) {
+            saveUserResource(ctx, pkg);
+        }
+    }
+
+    private void saveUserResource(Context ctx, String pkg) throws LibAndTransException {
+        List<StringRes> list = this.resources.get(pkg);
+        if (list == null) {
+            return;
+        }
+        File d = new File(this.dir);
+        d.mkdirs();
+        File f = userResourceFile(ctx, pkg, this.dir);
+        Properties prop = new Properties();
+        for (StringRes res : list) {
+            if (res.getUserString() == null || res.getUserString().matches("\\s*")) {
+                continue;
+            }
+            prop.setProperty(res.getResourceName(), res.getUserString());
+        }
+        FileOutputStream fos = null;
+        try {
+            fos = new FileOutputStream(f);
+            prop.save(fos, "AppTrans");
+        } catch (Exception e) {
+            LibAndTransUtil.log(e.getMessage());
+            throw new LibAndTransException("", e);
+        } finally {
+            LibAndTransUtil.safeclose(fos);
+        }
+
+    }
+
+    public Uri getTranslationXmlFile(Context ctx, String pkg) {
+        return save2xml(ctx, pkg);
+    }
+
+    /*
+     * Save to XML file, and return its Uri.
+     */
+    private Uri save2xml(Context ctx, String pkg) {
+        List<StringRes> list = this.resources.get(pkg);
+        if (list == null) {
+            return null;
+        }
+        File d = new File(this.dir);
+        d.mkdirs();
+
+        XmlSerializer serializer = Xml.newSerializer();
+        FileWriter fw = null;
+        try {
+            File file = xmlFile(ctx, pkg, this.dir);
+            fw = new FileWriter(file);
+            try {
+                serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
+            } catch (Exception e) {}
+            serializer.setOutput(fw);
+            serializer.startDocument("UTF-8", true);
+            serializer.startTag("", "resources");
+            for (StringRes res : list) {
+                if (res.getUserString() == null || res.getUserString().matches("\\s*")) {
+                    continue;
+                }
+                serializer.startTag("", "string");
+                serializer.attribute("", "name", res.getResourceName());
+                String text = res.getUserString().replaceAll("\"", "\\\\\"");
+                serializer.text("\"" + text + "\"");
+                serializer.endTag("", "string");
+            }
+            serializer.endTag("", "resources");
+            serializer.endDocument();
+            return Uri.fromFile(file);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            LibAndTransUtil.safeclose(fw);
+        }
+
+    }
+
+    private static File xmlFile(Context ctx, String pkg, String dir) {
+        return new File(dir, "string_" + ctx.getPackageName() + ".xml");
+    }
+
+    private static File userResourceFile(Context ctx, String pkg, String dir) {
+        return new File(dir, ctx.getPackageName() + "_" + pkg + ".properties");
+    }
+
+    public boolean isIgnoreSelfResource() {
+        return ignoreSelfResource;
+    }
+
+    /*
+     * If you want to translation LibAndroTranslation's resource, set true.
+     */
+    public void setIgnoreSelfResource(boolean ignoreSelfResource) {
+        this.ignoreSelfResource = ignoreSelfResource;
+    }
 }
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.