Skip to content

Commit

Permalink
Adding Multi-property-editor support in repo-editor.
Browse files Browse the repository at this point in the history
updated parent pom to resolve revision.
  • Loading branch information
cjayswal committed Nov 25, 2024
1 parent 8e3924d commit 96947f5
Show file tree
Hide file tree
Showing 4 changed files with 191 additions and 17 deletions.
27 changes: 26 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@
</executions>
<dependencies></dependencies>
</plugin>
<plugin>
<!--<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.5</version>
Expand All @@ -325,6 +325,31 @@
</goals>
</execution>
</executions>
</plugin>-->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<updatePomFile>true</updatePomFile>
<flattenMode>resolveCiFriendliesOnly</flattenMode>
</configuration>
<executions>
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.LocaleUtils;

public class FileUtil extends FileUtils {
private static int counter = -1; /* Protected by tmpFileLock */
Expand Down Expand Up @@ -302,4 +303,12 @@ public static String getRelativePath(File fileOrFolder, File baseFolder) {
return baseFolder.toURI().relativize(fileOrFolder.toURI()).getPath();
}

public static boolean isLocale(String name) {
String ext = getExtention(name);
try {
return StringUtil.isNotBlank(ext) && LocaleUtils.toLocale(ext).toString().equalsIgnoreCase(ext);
} catch (Exception e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package com.qmetry.qaf.automation.tools;

import static com.qmetry.qaf.automation.util.FileUtil.checkCreateDir;
import static com.qmetry.qaf.automation.util.FileUtil.getExtention;
import static com.qmetry.qaf.automation.util.FileUtil.isLocale;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import com.google.common.io.Files;
import com.qmetry.qaf.automation.util.StringUtil;

public class MultiPropertiesEditorHelper {

/**
* Example return value:
* <pre>
* <code>
* [
* {"key":"some.prop","en_US":"valForUS","fr_FR":"valInFR"},
* {"key":"another.prop","en_US":"val2ForUS","fr_FR":"val2InFR"},
* ...
* ]
* </code></pre>
*
* @param filePath
* @return
*/

@SuppressWarnings("unchecked")
public static Collection<Map<String, Object>> getContent(String filePath) {
File[] files = getFiles(filePath);
Map<String, Map<String, Object>> entries = new LinkedHashMap<String, Map<String,Object>>();

for(File file: files) {
try {
PropertiesConfiguration p = new PropertiesConfiguration();
p.setEncoding(StandardCharsets.UTF_8.name());
p.load(file);

String colName = getExtention(file.getName());
p.getKeys().forEachRemaining((k)->{
Map<String, Object> entry = entries.get(k);
if(null == entry) {
entry = new HashMap<String, Object>();
entry.put("key", (String)k);
entries.put((String)k, entry);
}
entry.put(colName, p.getString((String)k));
});

} catch (Exception e) {
System.err.println("Unable to read " + file + e.getMessage());
}
}

return entries.values();
}

public static void saveContent(Collection<Map<String, Object>> data, String path) {
Path filePath = Path.of(path);
String name = filePath.getFileName().toString();
String parent = filePath.getParent().toString();
saveContent(data, name, parent);
}

public static void saveContent(Collection<Map<String, Object>> data, String name, String parent) {
Map<String, PropertiesConfiguration> properties = new HashMap<String, PropertiesConfiguration>();

data.iterator().forEachRemaining(entry -> {
String key = (String) entry.remove("key");
if (StringUtil.isNotBlank(key)) {
entry.entrySet().forEach(colEntry -> {
String colName = colEntry.getKey();
PropertiesConfiguration p = properties.get(colName);
if (null == p) {
try {
checkCreateDir(parent);
File target = new File(parent, String.join(".", name, colName));
target.createNewFile();
p = new PropertiesConfiguration();
p.setEncoding(StandardCharsets.UTF_8.toString());
p.load(target);
p.setFile(target);
properties.put(colName, p);
} catch (IOException | ConfigurationException e) {
throw new RuntimeException(e);
}

}
p.setProperty(key, colEntry.getValue());
});
}
});

properties.values().forEach(p->{
try {
p.save();
//p.save
} catch (ConfigurationException e2) {
throw new RuntimeException(e2);
}
});

}

public static File[] getFiles(String name, boolean locale) {
if(!locale || !isLocale(name) ) return new File[] {};

File f = new File(name);
f.getParentFile().listFiles((dir,fname)->{
return (!locale || isLocale(fname)) && Files.getNameWithoutExtension(fname).equalsIgnoreCase(Files.getNameWithoutExtension(name));
});
return null;
}

public static File[] getFiles(String name) {
return getFiles(name, isLocale(name));
}




}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
Expand Down Expand Up @@ -151,7 +152,7 @@ private static HttpServer createServer(int port) {
break;
case "get_content":
res.setEntity(new StringEntity(
JSONUtil.toString(getContent(queryParams.get("path"))),
JSONUtil.toString(getContent(queryParams.get("path"),Boolean.getBoolean(queryParams.getOrDefault("multi","false")))),
ContentType.APPLICATION_JSON));
break;
case "save_wsc":
Expand All @@ -163,7 +164,7 @@ private static HttpServer createServer(int port) {
break;
case "save_loc":
String data = IOUtils.toString(req.getEntity().getContent(), StandardCharsets.UTF_8);
saveContent(JSONUtil.toObject(data, List.class), queryParams.get("path"));
saveContent(JSONUtil.toObject(data, List.class), queryParams.get("path"), Boolean.getBoolean(queryParams.getOrDefault("multi","false")));
break;

case "load_resource":
Expand Down Expand Up @@ -461,8 +462,8 @@ private static Map<String, String> rename(Map<String, String> queryParams) throw
File newFile = new File(parent, newName);
if (!FileUtil.getExtention(newName).equalsIgnoreCase(FileUtil.getExtention(old)) && (isWSC(newName) || isLOC(newName))) {
try {
List<Map<String, Object>> content = getContent(oldFile.getPath());
saveContent(content, newFile.getPath());
Collection<Map<String, Object>> content = getContent(oldFile.getPath(), false);
saveContent(content, newFile.getPath(),false);
oldFile.delete();
} catch (Exception e) {
throw new RuntimeException("Unable to change file type: " + e.getMessage());
Expand Down Expand Up @@ -605,9 +606,9 @@ private static Object[] getNodes(String id) {
}).toArray();
}
//".wsc",".loc",".proto","json", "properties", "xml","txt", "csv"
String[] allowedTypes = QAF_CONTEXT.getStringArray("repoeditor.filetypes", ".wsc",".loc",".proto","properties",".locj",".wscj");
String[] allowedTypes = QAF_CONTEXT.getStringArray("repoeditor.filetypes", ".wsc",".loc",".proto","properties",".locj",".wscj", ".bdd", ".bdl", ".feature");
Object[] nodes = Files.list(parent.toPath())
.filter(p -> p.toFile().isDirectory() || StringUtil.endsWithAny(p.toString(), allowedTypes))
.filter(p -> p.toFile().isDirectory() || StringUtil.endsWithAny(p.toString(), allowedTypes) || FileUtil.isLocale(p.toString()))
.map(p -> {
Map<String, Object> node = new HashMap<String, Object>();
node.put("text", p.toFile().getName());
Expand All @@ -629,9 +630,11 @@ private static Object[] getNodes(String id) {
}

@SuppressWarnings("unchecked")
private static List<Map<String, Object>> getContent(String file) {
private static Collection<Map<String, Object>> getContent(String file, boolean isMulti) {
List<Map<String, Object>> fileContent = new LinkedList<Map<String, Object>>();

if(isMulti) {
return MultiPropertiesEditorHelper.getContent(file);
}
if(file.endsWith(".wscj")) {
Map<String, Object> content = JSONUtil.getJsonObjectFromFile(file, Map.class);
if(null==content)
Expand Down Expand Up @@ -692,17 +695,21 @@ private static List<Map<String, Object>> getContent(String file) {
return fileContent;
}
private static Map<String, Object> getWSCFile(String file){
List<Map<String, Object>> content = getContent(file);
return content.isEmpty()?JSONUtil.toMap("{}"):content.get(0);
Collection<Map<String, Object>> content = getContent(file,false);
return content.isEmpty()?JSONUtil.toMap("{}"):content.iterator().next();
}

private static void saveContent(List<Map<String, Object>> data, String file) throws IOException {
private static void saveContent(Collection<Map<String, Object>> data, String file, boolean isMulti) throws IOException {
if(isMulti) {
File f = new File(file);
MultiPropertiesEditorHelper.saveContent(data, f.getName(), f.getParent());
}
Gson gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create();
String fileContent = null;
if(file.endsWith(".wscj")) {
JSONUtil.writeJsonObjectToFile(file, data.get(0));
JSONUtil.writeJsonObjectToFile(file, data.iterator().next());
}else if(file.endsWith(".wsc")) {
fileContent = data.get(0).entrySet().stream().map((e) -> e.getKey() +"=" + gson.toJson(e.getValue()).replace("\\", "\\\\")).collect(Collectors.joining("\n"));
fileContent = data.iterator().next().entrySet().stream().map((e) -> e.getKey() +"=" + gson.toJson(e.getValue()).replace("\\", "\\\\")).collect(Collectors.joining("\n"));
}
else if(file.endsWith(".loc")) {
fileContent = data.stream().map(e->e.remove("key").toString()+"="+gson.toJson(e).replace("\\", "\\\\")).collect(Collectors.joining("\n"));
Expand All @@ -714,15 +721,15 @@ else if(file.endsWith(".loc")) {

if(null!=fileContent) {
FileUtil.writeStringToFile(new File(file), fileContent, ApplicationProperties.LOCALE_CHAR_ENCODING.getStringVal("UTF-8"));
//to keep track added/updated wsc and properties
QAF_CONTEXT.load(new String[] {file});
}
//to keep track added/updated wsc and properties
QAF_CONTEXT.load(new String[] {file});
}

private static void saveWSCFile(Map<String, Object> data,String file) throws IOException{
List<Map<String, Object>> fileContent = new LinkedList<Map<String, Object>>();
fileContent.add(data);
saveContent(fileContent,file);
saveContent(fileContent, file, false);
}

private static QAFRequestHandler handleExecuteRequest = (req, res, ctx) -> {
Expand Down

0 comments on commit 96947f5

Please sign in to comment.