Commit 8c43e7f7 authored by Skylot's avatar Skylot

style: fix code formating

parent 9e24a5ab
......@@ -42,7 +42,7 @@ import jadx.core.xmlgen.ResourcesSaver;
* jadx.load();
* jadx.save();
* </code></pre>
*
* <p>
* Instead of 'save()' you can iterate over decompiled classes:
* <pre><code>
* for(JavaClass cls : jadx.getClasses()) {
......
......@@ -65,9 +65,9 @@ public class ResourceFile {
public String toString() {
return "ResourceFile{name='" + name + '\'' + ", type=" + type + "}";
}
public static ResourceFile createResourceFileInstance(JadxDecompiler decompiler, String name, ResourceType type) {
if(!ZipSecurity.isValidZipEntryName(name)) {
if (!ZipSecurity.isValidZipEntryName(name)) {
return null;
}
return new ResourceFile(decompiler, name, type);
......
......@@ -17,9 +17,9 @@ public class ResourceFileContent extends ResourceFile {
public ResContainer loadContent() {
return ResContainer.singleFile(getName(), content);
}
public static ResourceFileContent createResourceFileContentInstance(String name, ResourceType type, CodeWriter content) {
if(!ZipSecurity.isValidZipEntryName(name)) {
if (!ZipSecurity.isValidZipEntryName(name)) {
return null;
}
return new ResourceFileContent(name, type, content);
......
......@@ -100,7 +100,7 @@ public final class ResourcesLoader {
case ARSC:
return new ResTableParser()
.decodeFiles(inputStream);
.decodeFiles(inputStream);
case IMG:
return ResContainer.singleImageFile(rf.getName(), inputStream);
......
......@@ -289,14 +289,14 @@ public class CodeWriter {
}
public void save(File dir, String subDir, String fileName) {
if(!ZipSecurity.isValidZipEntryName(subDir) || !ZipSecurity.isValidZipEntryName(fileName)) {
if (!ZipSecurity.isValidZipEntryName(subDir) || !ZipSecurity.isValidZipEntryName(fileName)) {
return;
}
save(dir, new File(subDir, fileName).getPath());
}
public void save(File dir, String fileName) {
if(!ZipSecurity.isValidZipEntryName(fileName)) {
if (!ZipSecurity.isValidZipEntryName(fileName)) {
return;
}
save(new File(dir, fileName));
......
......@@ -659,7 +659,7 @@ public class InsnGen {
}
void generateMethodArguments(CodeWriter code, InsnNode insn, int startArgNum,
@Nullable MethodNode callMth) throws CodegenException {
@Nullable MethodNode callMth) throws CodegenException {
int k = startArgNum;
if (callMth != null && callMth.contains(AFlag.SKIP_FIRST_ARG)) {
k++;
......
......@@ -44,5 +44,4 @@ public class Annotation {
public String toString() {
return "Annotation[" + visibility + ", " + atype + ", " + values + "]";
}
}
......@@ -48,5 +48,4 @@ public class AnnotationsList implements IAttribute {
public String toString() {
return Utils.listToString(map.values());
}
}
......@@ -28,5 +28,4 @@ public class MethodParameters implements IAttribute {
public String toString() {
return Utils.listToString(paramList);
}
}
......@@ -78,5 +78,4 @@ public class EnumClassAttr implements IAttribute {
public String toString() {
return "Enum fields: " + fields;
}
}
......@@ -26,5 +26,4 @@ public class ForceReturnAttr implements IAttribute {
public String toString() {
return "FORCE_RETURN " + Utils.listToString(returnInsn.getArguments());
}
}
......@@ -146,5 +146,4 @@ public final class MethodInfo {
return declClass.getFullName() + "." + name
+ "(" + Utils.listToString(args) + "):" + retType;
}
}
......@@ -80,5 +80,4 @@ public class ArithNode extends InsnNode {
+ op.getSymbol() + " "
+ getArg(1);
}
}
......@@ -35,7 +35,6 @@ public final class NamedArg extends InsnArg implements Named {
return false;
}
return name.equals(((NamedArg) o).name);
}
@Override
......
......@@ -27,7 +27,6 @@ public class Edge {
}
Edge edge = (Edge) o;
return source.equals(edge.source) && target.equals(edge.target);
}
@Override
......
......@@ -9,5 +9,4 @@ public interface IBranchRegion extends IRegion {
* NOTE: Contains 'null' elements for indicate empty branches.
*/
List<IContainer> getBranches();
}
......@@ -276,6 +276,7 @@ public class InsnNode extends LineAttrNode {
}
return true;
}
/**
* 'Hard' equals, compare all arguments
*/
......
......@@ -24,7 +24,7 @@ public final class IfInfo {
}
private IfInfo(IfCondition condition, BlockNode thenBlock, BlockNode elseBlock,
Set<BlockNode> mergedBlocks, Set<BlockNode> skipBlocks) {
Set<BlockNode> mergedBlocks, Set<BlockNode> skipBlocks) {
this.condition = condition;
this.thenBlock = thenBlock;
this.elseBlock = elseBlock;
......
......@@ -24,5 +24,4 @@ public class CatchAttr implements IAttribute {
public String toString() {
return tryBlock.toString();
}
}
......@@ -120,5 +120,4 @@ public class ExceptionHandler {
return (catchType == null ? "all"
: catchType.getShortName()) + " -> " + InsnUtils.formatOffset(handleOffset);
}
}
......@@ -25,5 +25,4 @@ public class SplitterBlockAttr implements IAttribute {
public String toString() {
return "Splitter: " + block;
}
}
......@@ -260,7 +260,7 @@ public class CodeShrinker extends AbstractVisitor {
}
private static boolean canMoveBetweenBlocks(InsnNode assignInsn, BlockNode assignBlock,
BlockNode useBlock, InsnNode useInsn) {
BlockNode useBlock, InsnNode useInsn) {
if (!BlockUtils.isPathExists(assignBlock, useBlock)) {
return false;
}
......
......@@ -207,7 +207,6 @@ public class SimplifyVisitor extends AbstractVisitor {
return concatInsn;
} // end of if constructor is for StringBuilder
} // end of if we found a constructor early in the chain
} catch (Exception e) {
LOG.warn("Can't convert string concatenation: {} insn: {}", mth, insn, e);
}
......
......@@ -18,5 +18,4 @@ public abstract class AbstractRegionVisitor implements IRegionVisitor {
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
}
}
......@@ -61,7 +61,7 @@ public class DepthRegionTraversal {
}
private static boolean traverseIterativeStepInternal(MethodNode mth, IRegionIterativeVisitor visitor,
IContainer container) {
IContainer container) {
if (container instanceof IRegion) {
IRegion region = (IRegion) container;
if (visitor.visitRegion(mth, region)) {
......
......@@ -9,5 +9,4 @@ public interface IRegionIterativeVisitor {
* If return 'true' traversal will be restarted.
*/
boolean visitRegion(MethodNode mth, IRegion region);
}
......@@ -14,5 +14,4 @@ public interface IRegionVisitor {
boolean enterRegion(MethodNode mth, IRegion region);
void leaveRegion(MethodNode mth, IRegion region);
}
......@@ -126,7 +126,7 @@ public class LoopRegionVisitor extends AbstractVisitor implements IRegionVisitor
}
private static LoopType checkArrayForEach(MethodNode mth, InsnNode initInsn, InsnNode incrInsn,
IfCondition condition) {
IfCondition condition) {
if (!(incrInsn instanceof ArithNode)) {
return null;
}
......
......@@ -27,5 +27,4 @@ public class SelectTypeVisitor {
ArgType newType = ArgType.merge(dex, t, t.selectFirst());
arg.setType(newType);
}
}
......@@ -149,7 +149,7 @@ public class StringUtils {
}
private static String escapeXmlChar(char c) {
if(c >= 0 && c <= 0x1F) {
if (c >= 0 && c <= 0x1F) {
return "\\" + (int) c;
}
switch (c) {
......
......@@ -30,5 +30,4 @@ public class CodegenException extends JadxException {
public CodegenException(MethodNode mth, String msg, Throwable th) {
super(mth, msg, th);
}
}
......@@ -21,5 +21,4 @@ public class DecodeException extends JadxException {
public DecodeException(MethodNode mth, String msg, Throwable th) {
super(mth, msg, th);
}
}
......@@ -23,5 +23,4 @@ public class JadxException extends Exception {
public JadxException(MethodNode mth, String msg, Throwable th) {
super(ErrorsCounter.formatMsg(mth, msg), th);
}
}
......@@ -74,7 +74,9 @@ public class InputFile {
}
return;
}
if (skipSources) return;
if (skipSources) {
return;
}
throw new DecodeException("Unsupported input file format: " + file);
}
......
......@@ -24,13 +24,12 @@ public class ZipSecurity {
}
return isInSubDirectoryInternal(baseDir, canonFile.getParentFile());
}
public static boolean isInSubDirectory(File baseDir, File file) {
try {
file = file.getCanonicalFile();
baseDir = baseDir.getCanonicalFile();
}
catch(IOException e) {
} catch (IOException e) {
return false;
}
return isInSubDirectoryInternal(baseDir, file);
......
......@@ -55,7 +55,7 @@ public class BinaryXMLParser extends CommonBinaryParser {
private boolean isOneLine = true;
private int namespaceDepth = 0;
private int[] resourceIds;
private RootNode rootNode;
private String appPackageName;
......@@ -180,9 +180,9 @@ public class BinaryXMLParser extends CommonBinaryParser {
int comment = is.readInt32();
int beginPrefix = is.readInt32();
int beginURI = is.readInt32();
String nsValue = getString(beginPrefix);
if(!nsMap.containsValue(nsValue)) {
if (!nsMap.containsValue(nsValue)) {
nsMap.putIfAbsent(getString(beginURI), nsValue);
}
namespaceDepth++;
......@@ -200,9 +200,9 @@ public class BinaryXMLParser extends CommonBinaryParser {
int endPrefix = is.readInt32();
int endURI = is.readInt32();
namespaceDepth--;
String nsValue = getString(endPrefix);
if(!nsMap.containsValue(nsValue)) {
if (!nsMap.containsValue(nsValue)) {
nsMap.putIfAbsent(getString(endURI), nsValue);
}
}
......@@ -313,7 +313,7 @@ public class BinaryXMLParser extends CommonBinaryParser {
String decodedAttr = ManifestAttributes.getInstance().decode(attrName, attrValData);
if (decodedAttr != null) {
memorizePackageName(attrName, decodedAttr);
if(isDeobfCandidateAttr(shortNsName, attrName)) {
if (isDeobfCandidateAttr(shortNsName, attrName)) {
decodedAttr = deobfClassName(decodedAttr);
}
writer.add(StringUtils.escapeXML(decodedAttr));
......@@ -339,16 +339,16 @@ public class BinaryXMLParser extends CommonBinaryParser {
}
return attrName;
}
private String generateNameForNS(String attrUrl) {
for(int i = 1; ; i++) {
for (int i = 1; ; i++) {
String attrName = "ns" + i;
if(!nsMap.containsValue(attrName) && !nsMapGenerated.contains(attrName)) {
if (!nsMap.containsValue(attrName) && !nsMapGenerated.contains(attrName)) {
nsMapGenerated.add(attrName);
// do not add generated value to nsMap
// because attrUrl might be used in a neighbor element, but never defined
writer.add("xmlns:").add(attrName)
.add("=\"").add(attrUrl).add("\" ");
.add("=\"").add(attrUrl).add("\" ");
return attrName;
}
}
......@@ -380,8 +380,8 @@ public class BinaryXMLParser extends CommonBinaryParser {
}
private void decodeAttribute(int attributeNS, int attrValDataType, int attrValData,
String shortNsName, String attrName) {
String shortNsName, String attrName) {
if (attrValDataType == TYPE_REFERENCE) {
// reference custom processing
String name = styleMap.get(attrValData);
......@@ -419,7 +419,7 @@ public class BinaryXMLParser extends CommonBinaryParser {
} else {
String str = valuesParser.decodeValue(attrValDataType, attrValData);
memorizePackageName(attrName, str);
if(isDeobfCandidateAttr(shortNsName, attrName)) {
if (isDeobfCandidateAttr(shortNsName, attrName)) {
str = deobfClassName(str);
}
writer.add(str != null ? StringUtils.escapeXML(str) : "null");
......@@ -454,55 +454,54 @@ public class BinaryXMLParser extends CommonBinaryParser {
writer.decIndent();
}
}
private String getValidTagAttributeName(String originalName) {
if(XMLChar.isValidName(originalName)) {
if (XMLChar.isValidName(originalName)) {
return originalName;
}
if(tagAttrDeobfNames.containsKey(originalName)) {
if (tagAttrDeobfNames.containsKey(originalName)) {
return tagAttrDeobfNames.get(originalName);
}
String generated;
do {
generated = generateTagAttrName();
}
while(tagAttrDeobfNames.containsValue(generated));
while (tagAttrDeobfNames.containsValue(generated));
tagAttrDeobfNames.put(originalName, generated);
return generated;
}
private static String generateTagAttrName() {
final int length = 6;
Random r = new Random();
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= length; i++) {
sb.append((char)(r.nextInt(26) + 'a'));
for (int i = 1; i <= length; i++) {
sb.append((char) (r.nextInt(26) + 'a'));
}
return sb.toString();
}
private String deobfClassName(String className) {
String newName = XmlDeobf.deobfClassName(rootNode, className,
appPackageName);
if(newName != null) {
if (newName != null) {
return newName;
}
return className;
}
private boolean isDeobfCandidateAttr(String shortNsName, String attrName) {
String fullName;
if(shortNsName != null) {
if (shortNsName != null) {
fullName = shortNsName + ":" + attrName;
}
else {
} else {
return false;
}
return "android:name".equals(fullName);
}
private void memorizePackageName(String attrName, String attrValue) {
if("manifest".equals(currentTag) && "package".equals(attrName)) {
if ("manifest".equals(currentTag) && "package".equals(attrName)) {
appPackageName = attrValue;
}
}
......
......@@ -96,5 +96,4 @@ public class CommonBinaryParser extends ParserConstants {
throw new IOException("Decode error: " + message
+ ", position: 0x" + Long.toHexString(is.getPos()));
}
}
......@@ -8,7 +8,6 @@ public class ParserConstants {
protected ParserConstants() {
}
protected static final String ANDROID_NS_URL = "http://schemas.android.com/apk/res/android";
/**
......
......@@ -84,7 +84,7 @@ public class ResTableParser extends CommonBinaryParser {
writer.finish();
return writer;
}
public CodeWriter makeXmlDump() {
CodeWriter writer = new CodeWriter();
writer.startLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
......@@ -93,7 +93,7 @@ public class ResTableParser extends CommonBinaryParser {
Set<String> addedValues = new HashSet<>();
for (ResourceEntry ri : resStorage.getResources()) {
if(addedValues.add(ri.getTypeName() + "." + ri.getKeyName())) {
if (addedValues.add(ri.getTypeName() + "." + ri.getKeyName())) {
String format = String.format("<public type=\"%s\" name=\"%s\" id=\"%s\" />",
ri.getTypeName(), ri.getKeyName(), ri.getId());
writer.startLine(format);
......
......@@ -61,28 +61,28 @@ public class ResourcesSaver implements Runnable {
String ext = FilenameUtils.getExtension(outFile.getName());
try {
outFile = prepareFile(outFile);
if(!ZipSecurity.isInSubDirectory(outDir, outFile)) {
if (!ZipSecurity.isInSubDirectory(outDir, outFile)) {
LOG.error("Path traversal attack detected, invalid resource name: {}",
outFile.getPath());
return;
}
ImageIO.write(image, ext, outFile);
} catch (IOException e) {
LOG.error("Failed to save image: {}", rc.getName(), e);
}
return;
}
if(!ZipSecurity.isInSubDirectory(outDir, outFile)) {
if (!ZipSecurity.isInSubDirectory(outDir, outFile)) {
LOG.error("Path traversal attack detected, invalid resource name: {}",
rc.getFileName());
return;
}
saveToFile(rc, outFile);
}
private void saveToFile(ResContainer rc, File outFile) {
CodeWriter cw = rc.getContent();
if (cw != null) {
......
......@@ -12,25 +12,25 @@ import jadx.core.dex.nodes.RootNode;
*/
public class XmlDeobf {
private static final Map<String, String> deobfMap = new HashMap<>();
private XmlDeobf() {}
public static String deobfClassName(RootNode rootNode, String potencialClassName,
String packageName) {
if(packageName != null && potencialClassName.startsWith(".")) {
String packageName) {
if (packageName != null && potencialClassName.startsWith(".")) {
potencialClassName = packageName + potencialClassName;
}
return getNewClassName(rootNode, potencialClassName);
}
private static String getNewClassName(RootNode rootNode, String old) {
if(deobfMap.isEmpty()) {
for(ClassNode classNode : rootNode.getClasses(true)) {
if(classNode.getAlias() != null) {
if (deobfMap.isEmpty()) {
for (ClassNode classNode : rootNode.getClasses(true)) {
if (classNode.getAlias() != null) {
String oldName = classNode.getClassInfo().getFullName();
String newName = classNode.getAlias().getFullName();
if(!oldName.equals(newName)) {
if (!oldName.equals(newName)) {
deobfMap.put(oldName, newName);
}
}
......
......@@ -92,5 +92,4 @@ public class BackgroundWorker extends SwingWorker<Void, Void> {
protected void done() {
progressPane.setVisible(false);
}
}
......@@ -24,5 +24,4 @@ public class DecompileJob extends BackgroundJob {
public String getInfoString() {
return "Decompiling: ";
}
}
......@@ -158,7 +158,7 @@ public class JadxSettings extends JadxCLIArgs {
this.showInconsistentCode = showInconsistentCode;
}
public LangLocale getLangLocale(){
public LangLocale getLangLocale() {
return this.langLocale;
}
......
......@@ -82,7 +82,7 @@ public class JadxSettingsAdapter {
private static <T> void populate(GsonBuilder builder, String json, Class<T> type, final T into) {
builder.registerTypeAdapter(type, (InstanceCreator<T>) t -> into)
.create()
.fromJson(json, type);
.create()
.fromJson(json, type);
}
}
......@@ -20,7 +20,6 @@ import jadx.gui.utils.NLS;
import static jadx.gui.utils.Utils.FONT_HACK;
public class JadxSettingsWindow extends JDialog {
private static final long serialVersionUID = -1804570470377354148L;
......@@ -72,7 +71,7 @@ public class JadxSettingsWindow extends JDialog {
if (needReload) {
mainWindow.reOpenFile();
}
if (!settings.getLangLocale().equals(prevLang)){
if (!settings.getLangLocale().equals(prevLang)) {
JOptionPane.showMessageDialog(
this,
NLS.str("msg.language_changed", settings.getLangLocale()),
......@@ -194,7 +193,7 @@ public class JadxSettingsWindow extends JDialog {
EditorTheme[] editorThemes = CodeArea.getAllThemes();
JComboBox<EditorTheme> themesCbx = new JComboBox<>(editorThemes);
for (EditorTheme theme: editorThemes) {
for (EditorTheme theme : editorThemes) {
if (theme.getPath().equals(settings.getEditorThemePath())) {
themesCbx.setSelectedItem(theme);
break;
......@@ -275,7 +274,7 @@ public class JadxSettingsWindow extends JDialog {
private SettingsGroup makeOtherGroup() {
JComboBox<LangLocale> languageCbx = new JComboBox<>(NLS.getI18nLocales());
for (LangLocale locale: NLS.getI18nLocales()) {
for (LangLocale locale : NLS.getI18nLocales()) {
if (locale.equals(settings.getLangLocale())) {
languageCbx.setSelectedItem(locale);
break;
......
......@@ -205,7 +205,7 @@ public class JResource extends JLoadableNode implements Comparable<JResource> {
if (ext.equals("html")) {
return SyntaxConstants.SYNTAX_STYLE_HTML;
}
if(ext.equals("arsc")) {
if (ext.equals("arsc")) {
return SyntaxConstants.SYNTAX_STYLE_XML;
}
return null;
......
......@@ -38,7 +38,7 @@ public class JRoot extends JNode {
}
JCertificate certificate = getCertificate(wrapper.getResources());
if(certificate != null) {
if (certificate != null) {
add(certificate);
}
}
......@@ -84,15 +84,12 @@ public class JRoot extends JNode {
if (rf.getZipRef() != null) {
String rfName = rf.getName().toUpperCase();
if (rfName.endsWith(".DSA")||rfName.endsWith(".RSA")) {
if (rfName.endsWith(".DSA") || rfName.endsWith(".RSA")) {
return new JCertificate(rf);
}
}
}
return null;
}
private JResource getResourceByName(JResource rf, String name) {
......
......@@ -302,8 +302,8 @@ public abstract class CommonSearchDialog extends JDialog {
protected static class ResultsModel extends AbstractTableModel {
private static final long serialVersionUID = -7821286846923903208L;
private static final String[] COLUMN_NAMES = {
NLS.str("search_dialog.col_node"),
NLS.str("search_dialog.col_code")
NLS.str("search_dialog.col_node"),
NLS.str("search_dialog.col_code")
};
private final transient ArrayList<JNode> rows = new ArrayList<>();
......
......@@ -293,11 +293,10 @@ public class MainWindow extends JFrame {
if (resFile != null && JResource.isSupportedForView(resFile.getType())) {
tabbedPane.showResource(res);
}
}else if (obj instanceof JCertificate) {
} else if (obj instanceof JCertificate) {
JCertificate cert = (JCertificate) obj;
tabbedPane.showCertificate(cert);
}
else if (obj instanceof JNode) {
} else if (obj instanceof JNode) {
JNode node = (JNode) obj;
JClass cls = node.getRootClass();
if (cls != null) {
......
......@@ -67,7 +67,7 @@ public class Asset {
@Override
public String toString() {
return name
+ ", size: " + String.format("%.2fMB", size / 1024. /1024.)
+ ", size: " + String.format("%.2fMB", size / 1024. / 1024.)
+ ", downloads count: " + downloadCount
+ ", url: " + downloadUrl
+ ", date: " + createdAt;
......
......@@ -41,7 +41,7 @@ public class CodeUsageInfo {
}
private void addUsage(JNode jNode, JavaClass javaClass,
CodeLinesInfo linesInfo, CodePosition codePosition, List<StringRef> lines) {
CodeLinesInfo linesInfo, CodePosition codePosition, List<StringRef> lines) {
UsageInfo usageInfo = usageMap.get(jNode);
if (usageInfo == null) {
usageInfo = new UsageInfo();
......
......@@ -3,32 +3,32 @@ package jadx.gui.utils;
import java.util.Locale;
public class LangLocale {
private Locale locale;
public LangLocale(Locale locale) {
this.locale = locale;
}
public LangLocale(String l, String c) {
this.locale = new Locale(l, c);
}
public Locale get() {
return locale;
}
@Override
public String toString() {
return NLS.str("language.name", this);
}
@Override
public boolean equals(Object obj) {
return obj instanceof LangLocale && locale.equals(((LangLocale) obj).get());
}
@Override
public int hashCode() {
return locale.hashCode();
}
private Locale locale;
public LangLocale(Locale locale) {
this.locale = locale;
}
public LangLocale(String l, String c) {
this.locale = new Locale(l, c);
}
public Locale get() {
return locale;
}
@Override
public String toString() {
return NLS.str("language.name", this);
}
@Override
public boolean equals(Object obj) {
return obj instanceof LangLocale && locale.equals(((LangLocale) obj).get());
}
@Override
public int hashCode() {
return locale.hashCode();
}
}
......@@ -67,21 +67,21 @@ public class Link extends JLabel implements MouseListener {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
new ProcessBuilder()
.command(new String[] {"rundll32", "url.dll,FileProtocolHandler", url})
.start();
.command(new String[]{"rundll32", "url.dll,FileProtocolHandler", url})
.start();
return;
}
if (os.contains("mac")) {
new ProcessBuilder()
.command(new String[] {"open", url})
.start();
.command(new String[]{"open", url})
.start();
return;
}
Map<String, String> env = System.getenv();
if (env.get("BROWSER") != null) {
new ProcessBuilder()
.command(new String[] {env.get("BROWSER"), url})
.start();
.command(new String[]{env.get("BROWSER"), url})
.start();
return;
}
} catch (Exception e) {
......
......@@ -7,10 +7,15 @@ import java.util.Map;
import java.util.ResourceBundle;
import java.util.Vector;
import org.jetbrains.annotations.NotNull;
public class NLS {
private static final Charset JAVA_CHARSET = Charset.forName("ISO-8859-1");
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private static Vector<LangLocale> i18nLocales = new Vector<>();
private static Map<LangLocale, Map<String, String>> i18nMessagesMap;
private static Map<LangLocale, Map<String, String>> i18nMessagesMap = new HashMap<>();
// Use these two fields to avoid invoking Map.get() method twice.
private static Map<String, String> localizedMessagesMap;
......@@ -19,14 +24,7 @@ public class NLS {
private static LangLocale currentLocale;
private static LangLocale localLocale;
private static Charset javaCharset;
private static Charset utf8Charset;
static {
javaCharset = Charset.forName("ISO-8859-1");
utf8Charset = Charset.forName("UTF-8");
i18nMessagesMap = new HashMap<>();
localLocale = new LangLocale(Locale.getDefault());
i18nLocales.add(new LangLocale("en", "US")); // As default language
......@@ -35,8 +33,9 @@ public class NLS {
i18nLocales.forEach(NLS::load);
fallbackMessagesMap = i18nMessagesMap.get(i18nLocales.get(0));
localizedMessagesMap = i18nMessagesMap.get(i18nLocales.get(0));
LangLocale defLang = i18nLocales.get(0);
fallbackMessagesMap = i18nMessagesMap.get(defLang);
localizedMessagesMap = i18nMessagesMap.get(defLang);
}
private NLS() {
......@@ -45,31 +44,39 @@ public class NLS {
private static void load(LangLocale locale) {
ResourceBundle bundle = ResourceBundle.getBundle("i18n/Messages", locale.get());
Map<String, String> resMap = new HashMap<>();
for(String key : bundle.keySet()){
resMap.put(key, new String(
bundle.getString(key).getBytes(javaCharset),
utf8Charset));
for (String key : bundle.keySet()) {
String str = bundle.getString(key);
resMap.put(key, convertCharset(str));
}
i18nMessagesMap.put(locale, resMap);
}
@NotNull
private static String convertCharset(String str) {
return new String(str.getBytes(JAVA_CHARSET), UTF8_CHARSET);
}
public static String str(String key) {
if(localizedMessagesMap.containsKey(key)){
return localizedMessagesMap.get(key);
String str = localizedMessagesMap.get(key);
if (str != null) {
return str;
}
return fallbackMessagesMap.get(key);// definitely exists
return fallbackMessagesMap.get(key); // definitely exists
}
public static String str(String key, LangLocale locale) {
if(i18nMessagesMap.get(locale).containsKey(key)){
return i18nMessagesMap.get(locale).get(key);
Map<String, String> strings = i18nMessagesMap.get(locale);
if (strings != null) {
String str = strings.get(key);
if (str != null) {
return str;
}
}
return fallbackMessagesMap.get(key);// definitely exists
return fallbackMessagesMap.get(key); // definitely exists
}
public static void setLocale(LangLocale locale) {
if(i18nMessagesMap.containsKey(locale)){
if (i18nMessagesMap.containsKey(locale)) {
currentLocale = locale;
} else {
currentLocale = i18nLocales.get(0);
......@@ -77,7 +84,7 @@ public class NLS {
localizedMessagesMap = i18nMessagesMap.get(currentLocale);
}
public static Vector<LangLocale> getI18nLocales(){
public static Vector<LangLocale> getI18nLocales() {
return i18nLocales;
}
......@@ -85,12 +92,11 @@ public class NLS {
return currentLocale;
}
public static LangLocale defaultLocale(){
if(i18nMessagesMap.containsKey(localLocale)){
public static LangLocale defaultLocale() {
if (i18nMessagesMap.containsKey(localLocale)) {
return localLocale;
} else {
// fallback to english if unsupported
return i18nLocales.get(0);
}
// fallback to english if unsupported
return i18nLocales.get(0);
}
}
......@@ -18,6 +18,7 @@ public class LogCollector extends AppenderBase<ILoggingEvent> {
public static final int BUFFER_SIZE = 5000;
private static final LogCollector INSTANCE = new LogCollector();
public static LogCollector getInstance() {
return INSTANCE;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment