74 lines
2.1 KiB
Java
74 lines
2.1 KiB
Java
package de.hsel.spm.baudas.web.depiction;
|
|
|
|
import com.google.gson.Gson;
|
|
import de.hsel.spm.baudas.BauDas;
|
|
import org.jetbrains.annotations.NotNull;
|
|
import org.jetbrains.annotations.Nullable;
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import javax.servlet.http.HttpServletResponse;
|
|
import java.io.IOException;
|
|
import java.io.PrintWriter;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.util.Map;
|
|
import java.util.UUID;
|
|
import java.util.regex.Pattern;
|
|
|
|
/**
|
|
* handle all common methods for depictions.
|
|
*
|
|
* @author Johannes Theiner
|
|
* @version 0.1
|
|
* @since 1.0
|
|
**/
|
|
interface Depiction {
|
|
|
|
/**
|
|
* set all default values and handle caching.
|
|
*
|
|
* @param request request object
|
|
* @param response response object
|
|
* @param cache cached results
|
|
* @return validated uuid
|
|
*/
|
|
@Nullable
|
|
default UUID init(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Map<UUID, Map> cache) {
|
|
try {
|
|
request.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
|
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
|
response.setContentType("application/json");
|
|
PrintWriter out = response.getWriter();
|
|
|
|
|
|
Gson gson = new Gson();
|
|
|
|
UUID uuid = validateAndConvert(request.getParameter("id"));
|
|
if (uuid == null) return null;
|
|
|
|
if (cache.containsKey(uuid)) {
|
|
out.println(gson.toJson(cache.get(uuid)));
|
|
return null;
|
|
}
|
|
return uuid;
|
|
} catch (IOException e) {
|
|
BauDas.getLogger().throwing(this.getClass().getName(), this.getClass().getEnclosingMethod().getName(), e);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* validates and converts uuid.
|
|
*
|
|
* @param id potential uuid
|
|
* @return UUID object
|
|
*/
|
|
@Nullable
|
|
default UUID validateAndConvert(String id) {
|
|
boolean match = Pattern.matches("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}", id);
|
|
if (id == null || !match) {
|
|
return null;
|
|
}
|
|
|
|
return UUID.fromString(id);
|
|
}
|
|
} |