HmiStyleResource.java

package com.workbenchclassic.hmi;

import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.json.JSONArray;
import org.json.JSONObject;

/** Manage FULL ios.css snapshots in cust/CUST (no mutation of the deployed WAR). */
@Path("/hmi/v1/styles")
@Produces(MediaType.APPLICATION_JSON)
public final class HmiStyleResource {
    @Context private SecurityContext security;
    @Context private ServletContext servletContext;
    @Context private HttpServletRequest request;
    private String user(){return security.getUserPrincipal()==null?null:security.getUserPrincipal().getName();}
    private boolean designer(){return security.isUserInRole("hmi-admin")||security.isUserInRole("hmi-designer")||security.isUserInRole("hmi-publisher");}
    private boolean publisher(){return security.isUserInRole("hmi-admin")||security.isUserInRole("hmi-publisher");}
    private boolean csrf(){HttpSession s=request.getSession(false);if(s==null)return false;Object token=s.getAttribute("HMI_CSRF");String got=request.getHeader("X-CSRF-Token");return token instanceof String&&got!=null&&java.security.MessageDigest.isEqual(((String)token).getBytes(java.nio.charset.StandardCharsets.UTF_8),got.getBytes(java.nio.charset.StandardCharsets.UTF_8));}
    private Response json(Object obj){return Response.ok(obj.toString(),MediaType.APPLICATION_JSON).header("Cache-Control","no-store").build();}
    private Response fail(int status,String reason){return Response.status(status).type(MediaType.APPLICATION_JSON).entity(new JSONObject().put("error",reason).toString()).build();}
    private Response gate(boolean write,boolean publish){if(user()==null)return fail(401,"GlassFish login required");if(!HmiSchemaBootstrap.isReady())return fail(503,"HMI database not initialized");if(!(publish?publisher():designer()))return fail(403,"Role required");if(write&&!csrf())return fail(403,"CSRF token invalid");return null;}
    private String table(){return HmiDb.schemaPrefix()+"HMI_APP_CSS_REVISION";}
    private static String read(ResultSet rs,int col)throws Exception {try(Reader r=rs.getCharacterStream(col)){return r==null?"":HmiStyles.read(r);}}
    private static void content(PreparedStatement p,int i,String value)throws SQLException{p.setCharacterStream(i,new StringReader(value),value.length());}
    private static String publishedId(Connection c,String table)throws SQLException{
        try(PreparedStatement p=c.prepareStatement("SELECT ID FROM "+table+" WHERE STATUS='PUBLISHED' ORDER BY VERSION_NO DESC");ResultSet rs=p.executeQuery()) {return rs.next()?rs.getString(1):"";}
    }
    @GET @Path("ios")
    public Response view(){Response g=gate(false,false);if(g!=null)return g;try(Connection c=HmiDb.open()){
      JSONObject out=new JSONObject().put("original",HmiStyles.original(servletContext));JSONArray versions=new JSONArray();
      try(PreparedStatement p=c.prepareStatement("SELECT ID, VERSION_NO, STATUS, UPDATED_BY, UPDATED_AT FROM "+table()+" ORDER BY VERSION_NO DESC");ResultSet rs=p.executeQuery()){
       int count=0;while(rs.next()&&count++<60)versions.put(new JSONObject().put("id",rs.getString(1)).put("version",rs.getInt(2)).put("status",rs.getString(3)).put("author",rs.getString(4)).put("updatedAt",String.valueOf(rs.getTimestamp(5))));}
      out.put("versions",versions).put("publishedId",publishedId(c,table()));
      String published=null;
      try(PreparedStatement p=c.prepareStatement("SELECT CSS_CONTENT FROM "+table()+" WHERE STATUS='PUBLISHED' ORDER BY VERSION_NO DESC")){
        try(ResultSet rs=p.executeQuery()){if(rs.next())published=read(rs,1);}
      }
      out.put("published",published==null?out.getString("original"):published);
      return json(out);
    }catch(Exception ex){servletContext.log("CSS read failed",ex);return fail(500,"Stylesheet unavailable");}}
    @GET @Path("ios/{id}")
    public Response version(@PathParam("id")String id){Response g=gate(false,false);if(g!=null)return g;if(!id.matches("[A-Za-z0-9-]{1,64}"))return fail(400,"Invalid revision");
      try(Connection c=HmiDb.open();PreparedStatement p=c.prepareStatement("SELECT CSS_CONTENT FROM "+table()+" WHERE ID=?")){p.setString(1,id);try(ResultSet rs=p.executeQuery()){return rs.next()?json(new JSONObject().put("id",id).put("css",read(rs,1))):fail(404,"Revision missing");}}
      catch(Exception ex){servletContext.log("CSS version failed",ex);return fail(500,"Read failed");}}
    @POST @Path("ios/drafts") @Consumes(MediaType.APPLICATION_JSON)
    public Response draft(String jsonBody){Response g=gate(true,false);if(g!=null)return g;
      try{JSONObject input=new JSONObject(jsonBody);String css=input.getString("css");HmiStyles.validate(css);
       try(Connection c=HmiDb.open()){c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);c.setAutoCommit(false);
        try{int next=1;try(PreparedStatement p=c.prepareStatement("SELECT MAX(VERSION_NO) FROM "+table());ResultSet rs=p.executeQuery()){if(rs.next())next=rs.getInt(1)+1;}
          String id=UUID.randomUUID().toString();try(PreparedStatement p=c.prepareStatement("INSERT INTO "+table()+"(ID,VERSION_NO,STATUS,CSS_CONTENT,UPDATED_BY,UPDATED_AT) VALUES(?,?,?,?,?,?)")){
           p.setString(1,id);p.setInt(2,next);p.setString(3,"DRAFT");content(p,4,css);p.setString(5,user());p.setTimestamp(6,Timestamp.from(Instant.now()));p.executeUpdate();}
          audit(c,"ios.css.draft",id);c.commit();return json(new JSONObject().put("id",id).put("version",next));
        }catch(Exception ex){c.rollback();throw ex;}
       }
      }catch(IllegalArgumentException ex){return fail(400,ex.getMessage());}
      catch(Exception ex){servletContext.log("CSS draft failed",ex);return fail(500,"Draft could not be saved");}}
    @POST @Path("ios/{id}/publish") @Consumes(MediaType.APPLICATION_JSON)
    public Response publish(@PathParam("id")String id,String jsonBody){Response g=gate(true,true);if(g!=null)return g;
     if(!id.matches("[A-Za-z0-9-]{1,64}"))return fail(400,"Invalid revision");
     try{JSONObject body=new JSONObject(jsonBody);String expected=body.optString("expectedPublishedId","");
      try(Connection c=HmiDb.open()){c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);c.setAutoCommit(false);
       try{
        String actual=publishedId(c,table());if(!actual.equals(expected)){c.rollback();return fail(409,"Published revision has changed; reload before publishing");}
        try(PreparedStatement exists=c.prepareStatement("SELECT STATUS FROM "+table()+" WHERE ID=?")){exists.setString(1,id);try(ResultSet rs=exists.executeQuery()){if(!rs.next()){c.rollback();return fail(404,"Unknown revision");}}}
        try(PreparedStatement p=c.prepareStatement("UPDATE "+table()+" SET STATUS='ARCHIVED' WHERE STATUS='PUBLISHED'")){p.executeUpdate();}
        try(PreparedStatement p=c.prepareStatement("UPDATE "+table()+" SET STATUS='PUBLISHED' WHERE ID=?")){p.setString(1,id);if(p.executeUpdate()!=1)throw new SQLException("Revision not found");}
        audit(c,"ios.css.published",id);c.commit();return json(new JSONObject().put("ok",true).put("id",id));
       }catch(Exception e){c.rollback();throw e;}
      }
     }catch(Exception ex){servletContext.log("CSS publish failed",ex);return fail(500,"Publish failed");}}
    private void audit(Connection c,String action,String id)throws SQLException{
      try(PreparedStatement p=c.prepareStatement("INSERT INTO "+HmiDb.schemaPrefix()+"HMI_APP_AUDIT(ID,ACTOR,ACTION_NAME,ENTITY_ID,DETAILS,CREATED_AT) VALUES(?,?,?,?,?,?)")){
       p.setString(1,UUID.randomUUID().toString());p.setString(2,user());p.setString(3,action);p.setString(4,id);p.setString(5,"Online style editor");p.setTimestamp(6,Timestamp.from(Instant.now()));p.executeUpdate();}
    }
}