2 Commits

Author SHA1 Message Date
05f01247e2 feat: add online editor, work in progress 2026-01-30 19:48:30 +01:00
e274352f98 refactor: move html in asset file 2026-01-30 16:49:54 +01:00
7 changed files with 660 additions and 100 deletions

View File

@@ -0,0 +1,247 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
font-family: sans-serif;
padding: 20px;
background: #eee;
margin-bottom: 100px;
}
.card {
background: white;
padding: 20px;
margin-bottom: 30px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 10px;
border-bottom: 1px solid #ddd;
text-align: left;
}
input[type='text'],
input[type='number'] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 100%;
box-sizing: border-box;
}
.img-p {
width: 60px;
height: 60px;
object-fit: cover;
background: #f0f0f0;
border-radius: 5px;
}
.btn-add {
background: #0049AF;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
margin-top: 10px;
border-radius: 5px;
font-weight: bold;
}
.btn-save {
background: #2E7D32;
color: white;
padding: 15px 30px;
border: none;
border-radius: 50px;
cursor: pointer;
font-size: 18px;
font-weight: bold;
position: fixed;
bottom: 30px;
left: 50%;
transform: translateX(-50%);
z-index: 1000;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
width: auto;
white-space: nowrap;
}
.btn-del {
background: #d32f2f;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
padding: 5px 10px;
}
.link-mod {
background: none;
border: none;
color: #0049AF;
text-decoration: underline;
cursor: pointer;
padding: 0;
font-size: 12px;
-webkit-appearance: none;
outline: none;
}
.actions-bar {
position: fixed;
bottom: 30px;
left: 50%;
transform: translateX(-50%);
z-index: 1000;
display: flex;
gap: 15px;
}
.btn-cancel {
background: #F54927;
color: white;
padding: 15px 30px;
border: none;
border-radius: 50px;
cursor: pointer;
font-size: 18px;
font-weight: bold;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
white-space: nowrap;
}
.btn-cat {
background: #0049AF;
color: white;
padding: 15px 25px;
border: none;
border-radius: 50px;
cursor: pointer;
font-size: 18px;
font-weight: bold;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
}
.btn-back {
background: #000000;
color: white;
padding: 15px 25px;
border: none;
border-radius: 50px;
cursor: pointer;
font-size: 18px;
font-weight: bold;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
}
.input-h2 {
font-size: 1.5rem !important;
font-weight: bold !important;
border: none !important;
background: transparent !important;
color: #555 !important;
width: auto;
max-width: 70%;
border-bottom: 1px dashed #ccc !important;
outline: none;
/* Enlève le contour bleu au clic */
}
.input-h2:focus {
border-bottom: 2px solid #0049AF;
color: #0049AF;
}
</style>
</head>
<body>
<h1>Éditeur de Catalogue</h1>
<form action="/save_editor" method="POST">
{{GENERATED_CONTENT}}
<div class="actions-bar">
<button type="button" class="btn-back" onclick="window.location.href= '/'">← Retour </button>
<button type="button" class="btn-cancel" onclick="handleCancel(event)">✖ Tout annuler</button>
<button type="button" class="btn-cat" onclick="addCategory()">+ Catégorie</button>
<input type="submit" value="💾 Enregistrer tout" class="btn-save" style="position:static; transform:none;">
</div>
</form>
<script>
function addRow(cat) {
var t = document.getElementById('table-' + cat);
var r = t.insertRow(-1);
var id = Date.now();
r.innerHTML = '<td><input type="file" id="f_' + id + '" style="display:none" onchange="uImg(this)">' +
'<button type="button" class="link-mod" onclick="document.getElementById(\'f_' + id + '\').click()">Ajouter</button>' +
'<input type="hidden" name="new|' + cat + '|' + id + '|img" value=""></td>' +
'<td><input type="text" name="new|' + cat + '|' + id + '|name" placeholder="Nom..." required></td>' +
'<td><input type="number" name="new|' + cat + '|' + id + '|min" value="0" min="0" required></td>' +
'<td><input type="number" name="new|' + cat + '|' + id + '|max" value="0" min="0" required></td>' +
'<td><button type="button" class="btn-del" onclick="var l=this.parentNode.parentNode; l.parentNode.removeChild(l);">×</button></td>';
}
function uImg(el) {
var f = el.files[0];
if (!f) return;
var row = el.parentNode.parentNode;
var id = f.name.split('.').slice(0, -1).join('.');
row.querySelector('input[type="hidden"]').value = id;
var fd = new FormData();
fd.append('images', f);
fetch('/upload_images', { method: 'POST', body: fd }).then(function () { alert('Image envoyée : ' + id); });
}
function handleCancel(e) {
// Empêche le formulaire de faire quoi que ce soit
if (e) e.preventDefault();
if (confirm("Attention : toutes vos modifications seront perdues. Continuer ?")) {
// Le ?t= force le navigateur à oublier les saisies en cours
window.location.href = "/edit?t=" + Date.now();
}
}
function addCategory() {
var name = prompt("Nom de la nouvelle catégorie ?");
if (!name || name.trim() === "") return;
// On crée un ID temporaire basé sur le temps
var tempId = "newcat_" + Date.now();
// On crée la structure HTML de la carte
var container = document.createElement('div');
container.className = 'card';
container.innerHTML =
'<h2>' +
'<input type="text" class="input-h2" name="cat|' + tempId + '|name" value="' + name + '">' +
' <button type="button" class="btn-del" onclick="if(confirm(\'Supprimer cette catégorie ?\')) this.closest(\'.card\').remove()">×</button>' +
'</h2>' +
'<table id="table-' + tempId + '">' +
'<tr><th>Image</th><th>Nom</th><th>Prix Min</th><th>Prix Max</th><th></th></tr>' +
'</table>' +
'<button type="button" class="btn-add" onclick="addRow(\'' + tempId + '\')">+ Ajouter article</button>';
// On l'insère avant la barre d'actions (en bas de la liste)
var form = document.querySelector('form');
var actionBar = document.querySelector('.actions-bar');
form.insertBefore(container, actionBar);
// On scrolle vers la nouvelle catégorie
container.scrollIntoView({ behavior: 'smooth' });
}
</script>
</body>

View File

@@ -0,0 +1,51 @@
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
body { font-family: sans-serif; line-height: 1.6; padding: 20px; color: #333; max-width: 800px; margin: auto; }
h1 { color: #0049AF; border-bottom: 2px solid #0049AF; }
h2 { color: #555; margin-top: 30px; }
.card { background: #f4f4f4; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #ddd; }
.btn { display: inline-block; width: 280px; height: 45px; line-height: 45px; text-align: center; background: #0049AF; color: white; text-decoration: none; border-radius: 4px; border: none; cursor: pointer; font-weight: bold; box-sizing: border-box; padding: 0; -webkit-appearance: none; font-family: inherit; font-size: 14px; font-style: normal; letter-spacing: normal; margin: 10px 5px; vertical-align: middle;}
.btn-download { background: #2E7D32; }
input[type='file'] { margin: 10px 0; }
.status { font-weight: bold; color: green; }
</style>
</head>
<body>
<h1>Application : stock-pignon</h1>
<h2>Gestion des stocks</h2>
<div class='card'>
<h3>Récupérer les sacoches des adhérent·es</h3>
<p>Télécharger le décompte des pièces sorties de l'atelier.</p>
<a href='/output_json' class='btn'>Voir stock.json</a>
<a href='/output_csv' class='btn'>Voir stock.csv</a>
<a href='/download_output_json' class='btn'>Télécharger stock.json</a>
<a href='/download_output_csv' class='btn'>Télécharger stock.csv</a>
</div>
<h2>Modifier le catalogue</h2>
<div class='card'>
<h3>Gestion du fichier JSON</h3>
<p>Catalogue actuel : <a href='/download_input' class='btn'>Télécharger pieces.json</a></p>
<hr>
<form action='/upload_json' method='post' enctype='multipart/form-data'>
<p><strong>Envoyer un nouveau catalogue :</strong></p>
<input type='file' name='json_file' accept='.json'><br>
<input type='submit' value='Remplacer pieces.json' class='btn'>
</form>
</div>
<div class='card'>
<h3>Gestion des images</h3>
<form action='/upload_images' method='post' enctype='multipart/form-data'>
<p><strong>Ajouter/Modifier des images (PNG/JPG) :</strong></p>
<input type='file' name='images' accept='image/*' multiple><br>
<input type='submit' value='Envoyer les images' class='btn'>
</form>
</div><div class='card'>
<h3>Modifier dans le navigateur</h3>
<p><a href='/edit' class='btn'>Editeur en ligne</a></p>
</div>
</body>
</html>

View File

@@ -14,11 +14,22 @@ public class Category {
@SuppressWarnings("unused")
private List<Item> items;
// Empty constructor for GSON
public Category() {}
// Full constructor for online editor
public Category(String name, List<Item> items) {
this.name = name;
this.items = items;
// Default colors
this.bgColor = "#0049AF";
this.textColor = "#FFFFFF";
}
// Getters
public String getName() { return name; }
public String getBgColor() { return bgColor; }
public String getTextColor() { return textColor; }
// Avoid crash if json isn't readable
public List<Item> getItems() {
return items != null ? items : new ArrayList<>();
}

View File

@@ -1,6 +1,7 @@
// ControlServer.java
package com.stock.pignon;
import android.content.Context;
import android.os.Environment;
import fi.iki.elonen.NanoHTTPD;
@@ -10,9 +11,12 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Scanner;
/**
* Create a web server to remote management of app assets.
@@ -20,13 +24,16 @@ import java.util.List;
// Inherit what is needed to build a web server
public class ControlServer extends NanoHTTPD {
private final Context context;
// Assets folders
private final File storageRoot = Environment.getExternalStorageDirectory();
private final File baseDir = new File(storageRoot, Config.EXTERNAL_DIR_NAME);
private final File imagesDir = new File(baseDir, Config.IMAGES_SUBDIR_NAME);
public ControlServer(int port) {
public ControlServer(Context context, int port) {
super(port);
this.context = context;
}
/**
@@ -37,33 +44,39 @@ public class ControlServer extends NanoHTTPD {
// Get requested address
String uri = session.getUri();
switch (uri) {
case "/download_input":
return downloadFile(Config.INPUT_JSON_NAME);
case "/output_json":
return viewFile(Config.OUTPUT_JSON_NAME);
case "/download_output_json":
return downloadFile(Config.OUTPUT_JSON_NAME);
case "/output_csv":
return viewFile(Config.OUTPUT_CSV_NAME);
case "/download_output_csv":
return downloadFile(Config.OUTPUT_CSV_NAME);
case "/":
case "/index.html":
return newFixedLengthResponse(getHtmlResponse());
if (uri.startsWith("/img_view/")) {
return serveImage(uri.replace("/img_view/", ""));
}
if (session.getMethod() == Method.GET) {
switch (uri) {
// Soon deprecated with online editor
case "/download_input":
return downloadFile(Config.INPUT_JSON_NAME);
// Soon deprecated with online editor
case "/output_json":
return viewFile(Config.OUTPUT_JSON_NAME);
case "/download_output_json":
return downloadFile(Config.OUTPUT_JSON_NAME);
case "/output_csv":
return viewFile(Config.OUTPUT_CSV_NAME);
case "/download_output_csv":
return downloadFile(Config.OUTPUT_CSV_NAME);
case "/edit":
return newFixedLengthResponse(fillEditor());
case "/":
return newFixedLengthResponse(getHtml("index.html"));
}
}
// File upload management
if (session.getMethod() == Method.POST) {
if (uri.equals("/upload_json")) {
return handleJsonUpload(session);
} else if (uri.equals("/upload_images")) {
return handleImagesUpload(session);
switch (uri) {
case "/upload_json":
return handleJsonUpload(session);
case "/upload_images":
return handleImagesUpload(session);
case "/save_editor":
return handleSaveEditor(session);
}
}
@@ -71,62 +84,217 @@ public class ControlServer extends NanoHTTPD {
}
/**
* HTML UI for users
* Read from asset and return html file
*/
private String getHtmlResponse() {
return "<html>" +
"<head>" +
"<meta charset='UTF-8'>" +
"<meta name='viewport' content='width=device-width, initial-scale=1'>" +
"<style>" +
"body { font-family: sans-serif; line-height: 1.6; padding: 20px; color: #333; max-width: 800px; margin: auto; }" +
"h1 { color: #0049AF; border-bottom: 2px solid #0049AF; }" +
"h2 { color: #555; margin-top: 30px; }" +
".card { background: #f4f4f4; padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #ddd; }" +
".btn { display: inline-block; width: 280px; height: 45px; line-height: 45px; text-align: center; background: #0049AF; color: white; text-decoration: none; border-radius: 4px; border: none; cursor: pointer; font-weight: bold; box-sizing: border-box; padding: 0; -webkit-appearance: none; font-family: inherit; font-size: 14px; font-style: normal; letter-spacing: normal; margin: 10px 5px; vertical-align: middle;}" +
".btn-download { background: #2E7D32; }" +
"input[type='file'] { margin: 10px 0; }" +
".status { font-weight: bold; color: green; }" +
"</style>" +
"</head>" +
"<body>" +
"<h1>Application : stock-pignon</h1>" +
"<h2>Gestion des stocks</h2>" +
"<div class='card'>" +
"<h3>Récupérer les sacoches des adhérent·es</h3>" +
"<p>Télécharger le décompte des pièces sorties de l'atelier.</p>" +
"<a href='/output_json' class='btn'>Voir stock.json</a>" +
"<a href='/output_csv' class='btn'>Voir stock.csv</a>" +
"<a href='/download_output_json' class='btn'>Télécharger stock.json</a>" +
"<a href='/download_output_csv' class='btn'>Télécharger stock.csv</a>" +
"</div>" +
"<h2>Modifier le catalogue</h2>" +
"<div class='card'>" +
"<h3>Gestion du fichier JSON</h3>" +
"<p>Catalogue actuel : <a href='/download_input' class='btn'>Télécharger pieces.json</a></p>" +
"<hr>" +
"<form action='/upload_json' method='post' enctype='multipart/form-data'>" +
"<p><strong>Envoyer un nouveau catalogue :</strong></p>" +
"<input type='file' name='json_file' accept='.json'><br>" +
"<input type='submit' value='Remplacer pieces.json' class='btn'>" +
"</form>" +
"</div>" +
"<div class='card'>" +
"<h3>Gestion des images</h3>" +
"<form action='/upload_images' method='post' enctype='multipart/form-data'>" +
"<p><strong>Ajouter/Modifier des images (PNG/JPG) :</strong></p>" +
"<input type='file' name='images' accept='image/*' multiple><br>" +
"<input type='submit' value='Envoyer les images' class='btn'>" +
"</form>" +
"</div>" +
"</body>" +
"</html>";
private String getHtml(String file) {
try {
InputStream is = context.getAssets().open(file);
// Scanner html file from the beginning \\A
Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
String html = s.hasNext() ? s.next() : "";
is.close();
return html;
} catch (IOException e) {
return "<html><body>❌ Erreur de chargement de la page</body></html>";
}
}
/**
* Read from asset and return html file
*/
private String fillEditor() {
// Get data for assets
DataLoader.loadData();
// Create an html string to fill the template
StringBuilder html = new StringBuilder();
// Browse map : 'id' for categories name, 'items' for items list
for (Map.Entry<String, List<Item>> section : DataLoader.getAllSections().entrySet()) {
String id = section.getKey();
List<Item> items = section.getValue();
// For each category, render a HTML card
html.append(renderCategorySection(id, items));
}
return getHtml("editor.html").replace("{{GENERATED_CONTENT}}", html.toString());
}
/**
* Generate HTML section for each category
*/
private String renderCategorySection(String id, List<Item> items) {
StringBuilder sb = new StringBuilder();
sb.append("<div class='card'>");
sb.append("<h2>");
if ("global".equals(id)) {
sb.append("Articles globaux");
// Hidden input to mark cat for server
sb.append("<input type='hidden' name='cat|").append(id).append("|name' value='global'>");
} else {
// Copy H2 theme
sb.append("<input type='text' name='cat|").append(id).append("|name' ")
.append("value=\"").append(id).append("\" ")
.append("style='font-size: 1.5rem; font-weight: bold; border: none; background: transparent; color: #555; width: auto; max-width: 70%; border-bottom: 1px dashed #ccc;'>");
// Delete category button
sb.append(" <button type='button' class='btn-del' style='vertical-align: middle; margin-left: 10px;' ")
.append("onclick=\"if(confirm('Supprimer cette catégorie et tous ses articles ?')) this.closest('.card').remove()\">×</button>");
}
sb.append("</h2>");
// Build table
sb.append("<table id='table-").append(id).append("'>");
sb.append("<tr><th>Image</th><th>Nom</th><th>Prix Min</th><th>Prix Max</th><th></th></tr>");
for (Item item : items) {
sb.append(renderItemRow(id, item));
}
sb.append("</table>");
// Bouton pour ajouter un article dans CETTE table précise
sb.append("<button type='button' class='btn-add' onclick=\"addRow('").append(id).append("')\">+ Ajouter article</button>");
sb.append("</div>");
return sb.toString();
}
/**
* Generate HTML row for each item
*/
private String renderItemRow(String catName, Item item) {
String prefix = "item|" + catName + "|" + item.getName();
return "<tr>" +
"<td><img src='/img_view/" + item.getImage() + "' class='img-p' onerror=\"this.src='https://placehold.co/60?text=?'\">" +
"<br><input type='file' accept='.jpg,.png' style='font-size:10px; width:70px' onchange='uImg(this)'>" +
"<input type='hidden' name='" + prefix + "|img' value='" + item.getImage() + "'></td>" +
"<td><input type='text' name='" + prefix + "|name' value=\"" + item.getName() + "\"></td>" +
"<td><input type='number' name='" + prefix + "|min' value='" + item.getMinPrice() + "'></td>" +
"<td><input type='number' name='" + prefix + "|max' value='" + item.getMaxPrice() + "'></td>" +
// Retro JS compatibility
"<td><button type='button' class='btn-del' onclick='var r=this.parentNode.parentNode; r.parentNode.removeChild(r);'>×</button></td>" +
"</tr>";
}
private Response serveImage(String filename) {
File imgJpg = new File(imagesDir, filename + ".jpg");
File imgPng = new File(imagesDir, filename + ".png");
File file = imgJpg.exists() ? imgJpg : (imgPng.exists() ? imgPng : null);
if (file == null || !file.exists()) return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "No image");
try {
Response res = newChunkedResponse(Response.Status.OK, "image/jpeg", new FileInputStream(file));
// avoid cache if user change image
res.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.addHeader("Pragma", "no-cache");
res.addHeader("Expires", "0");
return res;
} catch (IOException e) {
return newFixedLengthResponse("Error");
}
}
private Response handleSaveEditor(IHTTPSession session) {
try {
// NanoHTTPD reads post request : copy all data then sort parameters
Map<String, String> files = new HashMap<>();
session.parseBody(files);
Map<String, List<String>> params = session.getParameters();
// Temp struct for modified categories
// Key is category is, value is item list
Map<String, List<Item>> categoriesMap = new LinkedHashMap<>();
// Map id and categories names
Map<String, String> categoryNames = new HashMap<>();
// Identify categories with "cat|id123|name"
for (Map.Entry<String, List<String>> paramEntry : params.entrySet()) {
String key = paramEntry.getKey();
if (key.startsWith("cat|") && key.endsWith("|name")) {
String[] parts = key.split("\\|");
String catId = parts[1];
String catName = paramEntry.getValue().get(0);
// Si on ne l'a pas déjà ajouté (sécurité)
if (!categoriesMap.containsKey(catId)) {
categoriesMap.put(catId, new ArrayList<Item>());
categoryNames.put(catId, catName);
}
}
}
// Group field for each items
// Key = "catId|itemId", Value = "name, min, max, img""
Map<String, Map<String, String>> itemDataCollector = new LinkedHashMap<String, Map<String, String>>();
for (String key : params.keySet()) {
if (key.startsWith("item|") || key.startsWith("new|")) {
String[] parts = key.split("\\|"); // [type, catId, itemId, field]
String catId = parts[1];
String itemId = parts[2];
String field = parts[3];
String value = params.get(key).get(0);
String fullId = catId + "|" + itemId;
if (!itemDataCollector.containsKey(fullId)) {
itemDataCollector.put(fullId, new HashMap<String, String>());
}
itemDataCollector.get(fullId).put(field, value);
}
}
for (Map.Entry<String, Map<String, String>> entry : itemDataCollector.entrySet()) {
String catId = entry.getKey().split("\\|")[0];
Map<String, String> fields = entry.getValue();
String name = fields.get("name");
if (name == null) name = "Sans nom";
String img = fields.get("img");
if (img == null) img = "";
int min = 0;
int max = 0;
try {
String minStr = fields.get("min");
if (minStr != null) min = Integer.parseInt(minStr);
String maxStr = fields.get("max");
if (maxStr != null) max = Integer.parseInt(maxStr);
} catch (Exception e) {
// If error, keep 0
}
Item item = new Item(name, img, min, max);
if (categoriesMap.containsKey(catId)) {
categoriesMap.get(catId).add(item);
}
}
// Stop to use cat id and replace with cat name
Map<String, List<Item>> finalData = new LinkedHashMap<>();
for (String catId : categoriesMap.keySet()) {
String realName = categoryNames.get(catId);
finalData.put(realName, categoriesMap.get(catId));
}
// Save data to disk in JSON format
DataLoader.saveData(finalData);
return newFixedLengthResponse("✅ Catalogue enregistré ! <a href='/'>Retour</a>");
} catch (Exception e) {
e.printStackTrace();
return newFixedLengthResponse("❌ Erreur : " + e.getMessage());
}
}
// Soon deprecated with online editor
/**
* Manage JSON sent by remote.
*/
@@ -148,6 +316,7 @@ public class ControlServer extends NanoHTTPD {
}
}
// Soon deprecated with online editor
/**
* Manage multiple images sent by remote.
*/
@@ -193,6 +362,22 @@ public class ControlServer extends NanoHTTPD {
}
}
// Soon deprecated with online editor
/**
* Utility method to copy file byte per byte.
* Not always possible to simply move a file on Android.
*/
private void copyFile(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
/**
* Prepare file and offer as download
*/
@@ -236,19 +421,4 @@ public class ControlServer extends NanoHTTPD {
return newFixedLengthResponse("❌ Erreur de lecture.");
}
}
/**
* Utility method to copy file byte per byte.
* Not always possible to simply move a file on Android.
*/
private void copyFile(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}

View File

@@ -4,11 +4,16 @@ package com.stock.pignon;
import android.os.Environment;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.LinkedHashMap;
public class DataLoader {
private static final String TAG = "DataLoader"; // For readable logs
@@ -56,6 +61,9 @@ public class DataLoader {
}
}
/**
* Create a merge list with global items and items from a specified category for main activity
*/
// Compromise between CPU usage and memory usage : keep cache raw data and combinate global and specific items at call
public static List<Item> getItemsForCategory(String categoryName) {
@@ -72,13 +80,71 @@ public class DataLoader {
return combinedList;
}
/**
* To fill online editor, create a map with all items sorted by category
*/
public static Map<String, List<Item>> getAllSections() {
// LinkedHashMap remember item order instead of HashMap
Map<String, List<Item>> sections = new LinkedHashMap<>();
sections.put("global", cachedGlobals);
for (Category cat : cachedCategories) {
sections.put(cat.getName(), cat.getItems());
}
return sections;
}
/**
* Create a web server to remote management of app assets.
*/
public static List<Category> getCategories() {
return cachedCategories;
}
// Internal class for Gson
/**
* Internal class for GSON
*/
private static class CategoriesWrapper {
List<Item> globalItems;
List<Category> categories;
}
/**
* Write JSON from online editor data
*/
public static void saveData(Map<String, List<Item>> sections) throws Exception {
File dir = new File(Environment.getExternalStorageDirectory(), EXTERNAL_DIR);
File jsonFile = new File(dir, PIECES_FILE);
// To respect original format, we use the same format as GSON
List<Item> globalList = sections.get("global");
if (globalList == null) {
globalList = new ArrayList<Item>();
}
CategoriesWrapper wrapper = new CategoriesWrapper();
wrapper.globalItems = globalList;
wrapper.categories = new ArrayList<Category>();
// Fill each category
for (Map.Entry<String, List<Item>> entry : sections.entrySet()) {
if (!"global".equals(entry.getKey())) {
wrapper.categories.add(new Category(entry.getKey(), entry.getValue()));
}
}
// Convert to pretty JSON, human readable
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
String jsonString = gson.toJson(wrapper);
// Write to disk
try (FileOutputStream fos = new FileOutputStream(jsonFile);
OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8")) {
writer.write(jsonString);
writer.flush();
}
// Update app cache
cachedGlobals = wrapper.globalItems;
cachedCategories = wrapper.categories;
}
}

View File

@@ -14,9 +14,24 @@ public class Item {
// Empty constructor for GSON
public Item() {}
// Full constructor for online editor
public Item(String name, String image, int minPrice, int maxPrice) {
this.name = name;
this.image = image;
this.minPrice = minPrice;
this.maxPrice = maxPrice;
}
// Getters
public String getName() { return name; }
public int getMinPrice() { return minPrice; }
public int getMaxPrice() { return maxPrice; }
public String getImage() { return image; }
// Setters
public void setName(String name) { this.name = name; }
public void setMinPrice(int minPrice) { this.minPrice = minPrice; }
public void setMaxPrice(int maxPrice) { this.maxPrice = maxPrice; }
public void setImage(String image) { this.image = image; }
}

View File

@@ -89,7 +89,7 @@ public class MainActivity extends AppCompatActivity {
}
// Launch server
server = new ControlServer(8080);
server = new ControlServer(this,8080);
try {
server.start();
String url = "http://" + getDeviceIP() + ":8080";