package art.servers.controller; import art.library.interop.InteropParameter; import art.library.interop.InteropParameters; import art.library.interop.InteropResponse; import art.library.interop.serialization.Serialization; import art.library.interop.serialization.SerializationException; import art.library.model.devices.Device; import art.library.model.devices.DeviceInformation; import art.library.model.devices.DeviceRealtime; import art.library.model.devices.application.ApplicationRealtime; import art.library.model.devices.user.User; import art.library.model.devices.user.UserPermission; import art.library.model.devices.user.configuration.ConfigurationLockLogin; import art.library.model.general.ModelFile; import art.library.model.transactions.traces.Trace; import art.library.model.transactions.traces.TraceResult; import art.library.utils.licence.Licence; import art.library.utils.resources.Resources; import art.servers.ServerException; import art.servers.Shared; import art.servers.types.HttpAuthentication; import art.servers.types.HttpToken; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; import java.util.stream.Stream; public class ListenerImplementation { public InteropResponse logout(InteropParameters parameters, String address) throws SerializationException { String language = (String)parameters.getParameterValue("language"); String username = (String)parameters.getParameterValue("username"); String resource = Shared.getMessage(language, "Username") + " : " + username; resource += ", " + Shared.getMessage(language, "Address") + " : " + address; Shared.traceInformation(Shared.getApplicationName(), Shared.getMessage(language, "Logout"), resource, null, language); return(new InteropResponse(true)); } public InteropResponse login(InteropParameters parameters, String type, String address) throws SerializationException { String language = (String)parameters.getParameterValue("language"); ConfigurationLockLogin lockLogin = new ConfigurationLockLogin(); lockLogin.maximumAddressAttempts = 5; lockLogin.maximumUserAttempts = 5; lockLogin.minutesUserLocked = 5; lockLogin.minutesAddressLocked = 5; return(login(parameters, type, address, lockLogin)); } public InteropResponse login(InteropParameters parameters, String type, String address, ConfigurationLockLogin lockLogin) throws SerializationException { String language = (String)parameters.getParameterValue("language"); String username = (String)parameters.getParameterValue("username"); String password = (String)parameters.getParameterValue("password"); HttpAuthentication authentication = null; String resource = null; try { resource = Shared.getMessage(language, "Username") + " : " + username; resource += ", " + Shared.getMessage(language, "Address") + " : " + address; authentication = login(username, password, address, lockLogin); if (type.equalsIgnoreCase("json")) { HttpToken httptoken = authentication.getHttpToken(); if ((httptoken.resultCode == Shared.RESULT_OK) || (httptoken.resultCode == Shared.ERROR_FIRST_ACCESS)) { Shared.traceInformation(Shared.getApplicationName(), "Login", username, authentication, language); } else if (httptoken.resultCode == Shared.ERROR_WRONG_PASSWORD) { Shared.traceError(Shared.getApplicationName(), Shared.getMessage(language, "Login"), resource, new SerializationException(Shared.getMessage(language, "Wrong username or password")), authentication, language); } else if (httptoken.resultCode == Shared.ERROR_BLOCKED_ADDRESS) { Shared.traceError(Shared.getApplicationName(), Shared.getMessage(language, "Login"), resource, new SerializationException(Shared.getMessage(language, "Blocked address")), authentication, language); } else if (httptoken.resultCode == Shared.ERROR_BLOCKED_USER) { Shared.traceError(Shared.getApplicationName(), Shared.getMessage(language, "Login"), resource, new SerializationException(Shared.getMessage(language, "Blocked user")), authentication, language); } InteropResponse response = new InteropResponse(httptoken); return response; } else { HttpToken httptoken = authentication.getHttpToken(); if ((httptoken.resultCode == Shared.RESULT_OK) || (httptoken.resultCode == Shared.ERROR_FIRST_ACCESS)) { Shared.traceInformation(Shared.getApplicationName(), "Login", username, authentication, language); } else if (httptoken.resultCode == Shared.ERROR_WRONG_PASSWORD) { Shared.traceError(Shared.getApplicationName(), Shared.getMessage(language, "Login"), resource, new SerializationException(Shared.getMessage(language, "Wrong username or password")), authentication, language); } else if (httptoken.resultCode == Shared.ERROR_BLOCKED_ADDRESS) { Shared.traceError(Shared.getApplicationName(), Shared.getMessage(language, "Login"), resource, new SerializationException(Shared.getMessage(language, "Blocked address")), authentication, language); } else if (httptoken.resultCode == Shared.ERROR_BLOCKED_USER) { Shared.traceError(Shared.getApplicationName(), Shared.getMessage(language, "Login"), resource, new SerializationException(Shared.getMessage(language, "Blocked user")), authentication, language); } InteropResponse response = new InteropResponse(httptoken.token); response.mime = "text/plain"; return response; } } catch (Exception exception) { Shared.traceError(Shared.getApplicationName(), Shared.getMessage(language, "Login"), resource, exception, authentication, language); throw new SerializationException(Shared.getMessage(language, "Authentication error")); } } public HttpAuthentication login(String username, String password, String address) throws Exception { ConfigurationLockLogin lockLogin = new ConfigurationLockLogin(); lockLogin.maximumAddressAttempts = 5; lockLogin.maximumUserAttempts = 5; lockLogin.minutesUserLocked = 5; lockLogin.minutesAddressLocked = 5; return(login(username, password, address, lockLogin)); } private HttpAuthentication login(String username, String password, String address, ConfigurationLockLogin lockLogin) throws Exception { // Check user autenthication User user = null; // TODO: esto cada vez es muy ineficiente, revisar....... try { user = (User)Shared.model.getDeviceExternal(Licence.encrypt(username)); } catch (Exception e) { try { Shared.printstack(username, e); user = (User)Shared.model.getDeviceExternal(username); } catch (Exception ex) { // TODO Check blocked address Shared.printstack(username, e); HttpAuthentication authentication = new HttpAuthentication(username, password, address, Shared.ERROR_WRONG_PASSWORD, Shared.getMessage("Authentication error")); return(authentication); } } // TODO : volver a poner /* if (user.getDeviceInformation().password.equals(Licence.encrypt(password)) == false) { // Check blocked users // Increase in 1 userstatus.loginErrors // If loginErrors >= 5 then // block user // if (userstatus.unlockTimestamp > 0) nothing to do // else user.unlockTimestamp = currenttime + configuration.minutesBlocked // return error_wrong_password User newuser = Serialization.clone(user); UserStatus status = newuser.getDeviceStatus(); if (status == null) { newuser.status = new UserStatus(); status = newuser.getDeviceStatus(); } status.loginErrors = status.loginErrors + 1; if (status.loginErrors >= lockLogin.maximumUserAttempts) { if (status.unlockTimestamp <= 0) { status.unlockTimestamp = System.currentTimeMillis() + (lockLogin.minutesUserLocked * 60000L); } } Shared.model.updateDevice(user, newuser); HttpAuthentication authentication = new HttpAuthentication(username, password, address, Shared.ERROR_WRONG_PASSWORD, Shared.getMessage("Authentication error, passsword error")); return(authentication); } // Check correct accesses // if (currenttime < userstatus.unlockTimestamp) return error_blocked_user // userstatus.loginErrors = 0 // user.unlockTimestamp = -1 // return ok User newuser = Serialization.clone(user); UserStatus status = newuser.getDeviceStatus(); if (status == null) { newuser.status = new UserStatus(); status = newuser.getDeviceStatus(); } if (System.currentTimeMillis() < status.unlockTimestamp) { HttpAuthentication authentication = new HttpAuthentication(username, password, address, Shared.ERROR_BLOCKED_USER, Shared.getMessage("Authentication error, blocked user")); return(authentication); } if (status.lastLogin < 0) { status.loginErrors = 0; status.unlockTimestamp = -1; status.lastLogin = System.currentTimeMillis(); Shared.model.updateDevice(user, newuser); HttpAuthentication authentication = new HttpAuthentication(username, password, address, Shared.ERROR_FIRST_ACCESS, Shared.getMessage("Authentication error, first access")); return(authentication); } status.loginErrors = 0; status.unlockTimestamp = -1; status.lastLogin = System.currentTimeMillis(); Shared.model.updateDevice(user, newuser); */ HttpAuthentication authentication = new HttpAuthentication(username, password, address, user.getDeviceInformation().group); return authentication; } public InteropResponse art(InteropParameters parameters) throws SerializationException { return artic(parameters); } public InteropResponse artic(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { // Check permissions HttpAuthentication authentication = getHttpAuthentication(parameters); UserPermission permission = Shared.controllerUserPermissions.getUserPermission(authentication.username); if (permission.hasPermissionsParameters(Shared.getApplicationName(), parameters) == false) { throw new SerializationException(Shared.getMessage(language, "Not allowed")); } String operation = (String)parameters.getParameterValue("operation"); Method method = this.getClass().getMethod(operation, parameters.getClass()); InteropResponse response = (InteropResponse)method.invoke(this, parameters); return response; } catch (NoSuchMethodException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, "Bad operation"), sw.toString()); } catch (InvocationTargetException e) { if (e.getCause() instanceof SerializationException) throw (SerializationException)e.getCause(); Throwable cause = e.getCause(); StringWriter sw = new StringWriter(); cause.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, cause.getMessage()), sw.toString()); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, e.getMessage()), sw.toString()); } } public InteropResponse articweb(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String operation = (String)parameters.getParameterValue("operation"); Method method = this.getClass().getMethod(operation, parameters.getClass()); InteropResponse response = (InteropResponse)method.invoke(this, parameters); return response; } catch (NoSuchMethodException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, "Bad operation"), sw.toString()); } catch (InvocationTargetException e) { if (e.getCause() instanceof SerializationException) throw (SerializationException)e.getCause(); Throwable cause = e.getCause(); StringWriter sw = new StringWriter(); cause.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, cause.getMessage()), sw.toString()); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, e.getMessage()), sw.toString()); } } public InteropResponse gis(String uri) throws SerializationException { // Implemented by bridge application throw new SerializationException("Not available"); } public InteropResponse saml(InteropParameters parameters) throws SerializationException { // Implemented by bridge application throw new SerializationException("Not available"); } public InteropResponse get(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); String operation = null; try { operation = (String)parameters.getParameterValue("operation"); if ((operation.indexOf("get") != 0) && (operation.indexOf("list") != 0)) { throw new Exception("Not allowed"); } Method method = this.getClass().getMethod(operation, parameters.getClass()); InteropResponse response = (InteropResponse)method.invoke(this, parameters); return response; } catch (NoSuchMethodException e) { Shared.printstack("Listener", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, "Bad operation"), sw.toString()); } catch (InvocationTargetException e) { if (e.getCause() instanceof SerializationException) throw (SerializationException)e.getCause(); Throwable cause = e.getCause(); StringWriter sw = new StringWriter(); cause.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, cause.getMessage()), sw.toString()); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, e.getMessage()), sw.toString()); } } public InteropResponse set(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String operation = (String)parameters.getParameterValue("operation"); Method method = this.getClass().getMethod(operation, parameters.getClass()); InteropResponse response = (InteropResponse)method.invoke(this, parameters); return response; } catch (NoSuchMethodException e) { Shared.printstack("Listener", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, "Bad operation"), sw.toString()); } catch (InvocationTargetException e) { if (e.getCause() instanceof SerializationException) throw (SerializationException)e.getCause(); Throwable cause = e.getCause(); StringWriter sw = new StringWriter(); cause.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, cause.getMessage()), sw.toString()); } catch (Exception e) { Shared.printstack("Listener", e); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, e.getMessage()), sw.toString()); } } public InteropResponse session(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String operation = (String)parameters.getParameterValue("operation"); Method method = this.getClass().getMethod(operation, parameters.getClass()); InteropResponse response = (InteropResponse)method.invoke(this, parameters); return response; } catch (NoSuchMethodException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, "Bad operation"), sw.toString()); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (!(cause instanceof ServerException)) cause.printStackTrace(); StringWriter sw = new StringWriter(); cause.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, cause.getMessage()), sw.toString()); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); throw new SerializationException(Shared.getMessage(language, e.getMessage())); } } // public InteropResponse getGroups(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { List lgroup = Shared.model.getGroups(); String[] result = lgroup.toArray(new String[lgroup.size()]); return new InteropResponse(result); } catch (Exception e) { throw getException(language, e); } } // http:///gddkia-lublin-dk.pl:7017/get?operation=getDevices×tamp=0 // http:///gddkia-lublin-dk.pl:7017/get?operation=getDevices&identifier=location-krzewica-1&from=0&to=99999999999999 // http:///gddkia-lublin-dk.pl:7017/get?operation=getDevices&when=1522308992106; // http:///gddkia-lublin-dk.pl:7017/get?operation=getDevices&when=2018-03-28T10:15:00.000Z; public InteropResponse getDevices(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("identifier"); if (identifier == null) identifier = (parameters.hasParameter("device") == true) ? (String)parameters.getParameterValue("device") : null; String username = (String)parameters.getParameterValue("username"); User user = null; if (username != null) { try{user = (User)Shared.model.getDeviceExternal(identifier);} catch (Exception e){}; if (user == null) { try{user = (User)Shared.model.getDeviceExternal(Licence.encrypt(identifier));} catch (Exception e){}; } } if (parameters.hasParameter("timestamp")) { long timestamp = getTimestamp((String)parameters.getParameterValue("timestamp")); Device[] devices = checkDevices(user, Shared.model.getDevices(identifier, timestamp)); return new InteropResponse(devices); } else if (parameters.hasParameter("groups")) { String[] lGroup = getStringArray(parameters.getParameter("groups")); return new InteropResponse(Shared.model.getDevices(lGroup)); } else if ((parameters.hasParameter("from")) && (parameters.hasParameter("to"))) { long timestamp1 = getTimestamp((String)parameters.getParameterValue("from")); long timestamp2 = getTimestamp((String)parameters.getParameterValue("to")); return new InteropResponse(Shared.model.getDevices(identifier, (long)timestamp1, (long)timestamp2)); } else if (parameters.hasParameter("when")) { long timestamp = getTimestamp((String)parameters.getParameterValue("when")); return new InteropResponse(Shared.model.getDevicesWhen(identifier, (long)timestamp)); } else if (parameters.hasParameter("next")) { long timestamp = getTimestamp((String)parameters.getParameterValue("next")); return new InteropResponse(Shared.model.getDevicesNext(identifier, (long)timestamp)); } else { return new InteropResponse(Shared.model.getDevices(0)); } } catch (Exception e) { throw getException(language, e); } } public InteropResponse getDevicesInformation(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDevicesInformation((Device[])getDevices(parameters).getValue())); } public InteropResponse getDevicesConfiguration(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDevicesConfiguration((Device[])getDevices(parameters).getValue())); } public InteropResponse getDevicesStatus(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDevicesStatus((Device[])getDevices(parameters).getValue())); } public InteropResponse getDevicesAlarms(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDevicesAlarms((Device[])getDevices(parameters).getValue())); } public InteropResponse getDevicesStatusAlarms(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDevicesStatusAlarms((Device[])getDevices(parameters).getValue())); } public InteropResponse getDevice(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("identifier"); if (identifier == null) identifier = (parameters.hasParameter("device") == true) ? (String)parameters.getParameterValue("device") : null; return new InteropResponse(Shared.model.getDevice(identifier)); } catch (Exception e) { throw getException(language, e); } } public InteropResponse getDeviceInformation(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDeviceInformation((Device)getDevice(parameters).getValue()[0])); } public InteropResponse getDeviceConfiguration(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDeviceConfiguration((Device)getDevice(parameters).getValue()[0])); } public InteropResponse getDeviceStatus(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDeviceStatus((Device)getDevice(parameters).getValue()[0])); } public InteropResponse getDeviceAlarms(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDeviceAlarms((Device)getDevice(parameters).getValue()[0])); } public InteropResponse getDeviceStatusAlarms(InteropParameters parameters) throws SerializationException { return new InteropResponse(getDeviceStatusAlarms((Device)getDevice(parameters).getValue()[0])); } public InteropResponse existDevice(InteropParameters parameters) throws SerializationException { String language = (String) parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("identifier"); if (identifier == null) identifier = (parameters.hasParameter("device") == true) ? (String)parameters.getParameterValue("device") : null; return new InteropResponse(Shared.model.existsDevice(identifier)); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse addDevice (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); String bodyContent = null; try { Class clazzDevice = Class.forName(Shared.model.deviceClassName); bodyContent = (String)parameters.getParameterValue("body-content"); Device device = (Device)Serialization.deserialize(clazzDevice, bodyContent); addDevices(language, bodyContent); Shared.model.updateDevice(new Device[]{device}); return new InteropResponse(new Boolean(true)); } catch (ClassCastException exception) { } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } return addDevices(language, bodyContent); } public InteropResponse addDevices (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); String bodyContent = null; try { System.out.println("1.AddDevices: " + Shared.model.deviceClassName); Class clazzDevice = Class.forName(Shared.model.deviceClassName); System.out.println("2.AddDevices: " + clazzDevice); // bodyContent = (String)parameters.getParameterValue("body-content"); Class clazzArray = (Class)Array.newInstance(clazzDevice, 0).getClass(); Device[] ldevice = parameters.getBodyContentValue(clazzArray); // System.out.println("3.AddDevices: " + bodyContent); // Device[] ldevice = (Device[])Serialization.deserialize(clazzArray, bodyContent); System.out.println("4.AddDevices: " + ldevice); if ((ldevice != null) && (ldevice.length > 0)) { System.out.println("5.AddDevices: " + ldevice[0]); if (ldevice[0] != null) { System.out.println("6.AddDevices: " + ldevice[0].getIdentifier()); Shared.model.addDevices(Stream.of(ldevice).map(dev -> dev.getDeviceInformation()).toArray(DeviceInformation[]::new)); Shared.model.updateDevice(ldevice); return new InteropResponse(new Boolean(true)); } } } catch (ClassCastException exception) { exception.printStackTrace(); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } return addDevices(language, bodyContent); } private InteropResponse addDevices (String language, String bodyContent) throws SerializationException { try { Class clazzInformation = Class.forName(Shared.model.deviceInformationClassName); Class clazzArray = (Class)Array.newInstance(clazzInformation, 0).getClass(); DeviceInformation[] linformation = (DeviceInformation[])(Serialization.deserialize(clazzArray, bodyContent)); Shared.model.addDevices(linformation); return new InteropResponse(new Boolean(true)); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse deleteDevice (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = null; if (parameters.hasParameter("device") == true) { identifier = (String)parameters.getParameterValue("device"); } else if (parameters.hasParameter("identifier") == true) { identifier = (String)parameters.getParameterValue("identifier"); } Shared.model.deleteDevices(new String[]{identifier}); return new InteropResponse(new Boolean(true)); } catch (ServerException exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage())); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse deleteDevices (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String[] lidentifier = new String[0]; if (parameters.hasParameter("devices") == true) { lidentifier = ((String)parameters.getParameterValue("devices")).split(","); } else if (parameters.hasParameter("identifiers") == true) { lidentifier = ((String)parameters.getParameterValue("identifiers")).split(","); } else { lidentifier = (String[])Serialization.deserialize(String[].class, (String)parameters.getParameterValue("body-content")); } Shared.model.deleteDevices(lidentifier); return new InteropResponse(new Boolean(true)); } catch (ServerException exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage())); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse getDeviceRealtime(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("identifier"); if (identifier == null) identifier = (parameters.hasParameter("device") == true) ? (String)parameters.getParameterValue("device") : null; long timestamp = (parameters.hasParameter("timestamp") == true) ? Long.parseLong((String)parameters.getParameterValue("timestamp")) : 0; DeviceRealtime realtime = Shared.model.getDevice(identifier).getDeviceRealtime(); if (realtime.lastTimestampUpdate > timestamp) return new InteropResponse(realtime); } catch (Exception e) { throw getException(language, e); } throw new SerializationException("Realtime does not exists"); } public InteropResponse getDevicesRealtime(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); long timestamp = (parameters.hasParameter("timestamp") == true) ? Long.parseLong((String)parameters.getParameterValue("timestamp")) : 0; try { List lrealtime = new ArrayList(); Device[] ldevice = art.servers.Shared.model.getDevicesCopy(); for (Device device : ldevice) { DeviceRealtime realtime = device.getDeviceRealtime(); if (realtime != null) { if (realtime.lastTimestampUpdate > timestamp) { realtime.identifier = device.getIdentifier(); lrealtime.add(realtime); } } } return new InteropResponse(lrealtime.toArray(new DeviceRealtime[lrealtime.size()])); } catch (Exception e) { throw getException(language, e); } } private Device[] getDevicesInformation(Device[] ldevice) throws SerializationException { Device[] result = new Device[ldevice.length]; for (int i=0; i // public InteropResponse getSymbols(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { if (parameters.hasParameter("timestamp")) { long timestamp = Long.parseLong((String)parameters.getParameterValue("timestamp")); return new InteropResponse(Shared.model.getSymbols(timestamp)); } else { return new InteropResponse(Shared.model.getSymbols(0)); } } catch (Exception e) { throw getException(language, e); } } // // public InteropResponse listScalableVectorGraphics (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("identifier"); if (identifier == null) identifier = (String)parameters.getParameterValue("device"); File folder = new File("data/" + Shared.getApplicationName() + "/svgs/" + identifier + "/"); List lfiles = new ArrayList(); for (File file : folder.listFiles()) { ModelFile modelFile = new ModelFile(); modelFile.name = file.getName().substring(0, file.getName().lastIndexOf('.')); modelFile.mime = "image/svg+xml"; lfiles.add(modelFile); } InteropResponse response = new InteropResponse(lfiles); return response; } catch (Exception e) { throw getException(language, e); } } public InteropResponse getScalableVectorGraphics (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("identifier"); if (identifier == null) identifier = (String)parameters.getParameterValue("device"); String name = (String)parameters.getParameterValue("name"); if (name != null) { String filename = "data/" + Shared.getApplicationName() + "/svgs/" + identifier + "/" + name + ".svg"; byte[] data = Resources.getExternalFileBytes(filename); if (data.length == 0) data = Resources.getResourceBytes(filename); InteropResponse response = new InteropResponse(data); response.mime = "image/svg+xml"; return response; } else { File folder = new File("data/" + Shared.getApplicationName() + "/svgs/" + identifier + "/"); List lfiles = new ArrayList(); for (File file : folder.listFiles()) { ModelFile modelFile = new ModelFile(); modelFile.data = Files.readAllBytes(file.toPath()); modelFile.name = file.getName().substring(0, file.getName().lastIndexOf('.')); modelFile.mime = "image/svg+xml"; lfiles.add(modelFile); } InteropResponse response = new InteropResponse(lfiles); return response; } } catch (Exception e) { throw getException(language, e); } } public InteropResponse addScalableVectorGraphics (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("identifier"); if (identifier == null) identifier = (String)parameters.getParameterValue("device"); String name = (String)parameters.getParameterValue("name"); byte[] data = parameters.getParameterValue("body-content"); String filename = "data/" + Shared.getApplicationName() + "/svgs/" + identifier + "/" + name + ".svg"; File file = new File(filename); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); fos.write(data); fos.close(); return new InteropResponse(new Boolean(true)); } catch (Exception e) { throw getException(language, e); } } public InteropResponse removeScalableVectorGraphics (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("identifier"); if (identifier == null) identifier = (String)parameters.getParameterValue("device"); String name = (String)parameters.getParameterValue("name"); String filename = "data/" + Shared.getApplicationName() + "/svgs/" + identifier + "/" + name + ".svg"; File file = new File(filename); return new InteropResponse(new Boolean(file.delete())); } catch (Exception e) { throw getException(language, e); } } // // public InteropResponse getApplication(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { if (parameters.hasParameter("timestamp")) { long timestamp = Long.parseLong((String)parameters.getParameterValue("timestamp")); return new InteropResponse(Shared.model.getApplication(timestamp)); } else if ((parameters.hasParameter("from")) && (parameters.hasParameter("to"))) { long timestamp1 = Long.parseLong((String)parameters.getParameterValue("from")); long timestamp2 = Long.parseLong((String)parameters.getParameterValue("to")); return new InteropResponse(Shared.model.getApplication((long)timestamp1, (long)timestamp2)); } else if (parameters.getParametersNumber() == 1) { return new InteropResponse(Shared.model.getApplication(0)); } else { throw new Exception("Bad parameters"); } } catch (Exception e) { throw getException(language, e); } } // // public InteropResponse listDocuments(InteropParameters parameters) throws SerializationException { String language = parameters.getParameterValue("language"); try { String folder = (String)parameters.getParameterValue("folder"); List ldocument = new ArrayList(); File directory = new File("documents/" + folder); if (directory.exists() == false) throw new ServerException("No documents"); for (File file : directory.listFiles()) ldocument.add(file.getName()); InteropResponse response = new InteropResponse(ldocument.toArray(new String[ldocument.size()])); return response; } catch (ServerException exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage())); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse getDocument(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String name = (String)parameters.getParameterValue("name"); String folder = (String)parameters.getParameterValue("folder"); File file = new File("documents/" + folder + "/" + name); if (file.exists() == false) throw new ServerException("Document does not exists"); byte[] data = new byte[(int)file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(data); fis.close(); InteropResponse response = new InteropResponse(data); return response; } catch (ServerException exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage())); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse addDocument(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String name = parameters.getParameterValue("name"); String folder = (String)parameters.getParameterValue("folder"); byte[] data = parameters.getParameterValue("body-content"); File file = new File("documents/" + folder + "/" + name); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); fos.write(data); fos.close(); return new InteropResponse(new Boolean(true)); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse deleteDocument(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String name = (parameters.hasParameter("name") == true) ? (String)parameters.getParameterValue("name") : null; String folder = (String)parameters.getParameterValue("folder"); File file = new File("documents/" + folder + "/" + name); if (file.exists() == true) return new InteropResponse(new Boolean(file.delete())); throw new ServerException("Document does not exists"); } catch (ServerException exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage())); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } // // public InteropResponse listMaps(InteropParameters parameters) throws SerializationException { String language = parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("device"); List maps = new ArrayList(); File folder = new File("data/" + Shared.getApplicationName() + "/maps/" + identifier); if (folder.exists() == false) throw new SerializationException(Shared.getMessage(language, "No maps")); for (File file : folder.listFiles()) maps.add(file.getName().replace(".svg", "")); InteropResponse response = new InteropResponse(maps.toArray(new String[maps.size()])); return response; } catch (SerializationException exception) { throw exception; } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse getMap(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("device"); String name = (String)parameters.getParameterValue("name"); File file = new File("data/" + Shared.getApplicationName() + "/maps/" + identifier + "/" + name + ".svg"); if (file.exists() == false) throw new SerializationException(Shared.getMessage(language, "Map does not exists")); byte[] data = new byte[(int)file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(data); fis.close(); InteropResponse response = new InteropResponse(data); response.mime = "image/svg+xml"; return response; } catch (SerializationException exception) { throw exception; } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse addMap(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("device"); String name = parameters.getParameterValue("name"); byte[] data = parameters.getParameterValue("body-content"); File file = new File("data/" + Shared.getApplicationName() + "/maps/" + identifier + "/" + name + ".svg"); file.getParentFile().mkdirs(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bos.write(data); bos.close(); return new InteropResponse(new Boolean(true)); } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse deleteMap(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String identifier = (String)parameters.getParameterValue("device"); String name = parameters.getParameterValue("name"); File file = new File("data/" + Shared.getApplicationName() + "/maps/" + identifier + "/" + name + ".svg"); if (file.exists() == true) return new InteropResponse(new Boolean(file.delete())); throw new SerializationException(Shared.getMessage(language, "Map does not exists")); } catch (SerializationException exception) { throw exception; } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } // // public InteropResponse getTraceValues (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { String field = (String)parameters.getParameterValue("field"); List traces = Shared.model.getTraceValues(field, Shared.getApplicationName()); InteropResponse response = new InteropResponse(traces, true); return response; } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } public InteropResponse getTraces (InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { TraceResult result = new TraceResult(); if (parameters.hasParameter("timestamp") == true) { long timestamp = getTimestamp((String)parameters.getParameterValue("timestamp")); ApplicationRealtime realtime = (ApplicationRealtime)Shared.controllerStatus.getApplication().getDeviceRealtime(); result.traces = realtime.getTraces(timestamp); result.timestampfrom = timestamp; result.application = Shared.getApplicationName(); } else { result.timestampfrom = getTimestamp((String)parameters.getParameterValue("from")); result.timestampto = getTimestamp((String)parameters.getParameterValue("to")); result.type = (parameters.hasParameter("type") == true) ? Integer.parseInt((String)parameters.getParameterValue("type")) : Trace.TRACE_NONE; result.username = (String)parameters.getParameterValue("username"); result.application = Shared.getApplicationName(); result.service = (String)parameters.getParameterValue("controller"); result.offset = (parameters.hasParameter("offset") == true) ? Integer.parseInt((String)parameters.getParameterValue("offset")) : 0; result.limit = (parameters.hasParameter("limit") == true) ? Integer.parseInt((String)parameters.getParameterValue("limit")) : 1000; result.limit = Math.min(1000, result.limit); } InteropResponse response = new InteropResponse(Shared.model.getTraces(result), false); return response; } catch (Exception exception) { throw new SerializationException(Shared.getMessage(language, exception.getMessage()), exception); } } // // public InteropResponse heartbeat(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { return new InteropResponse(new Boolean(true)); } catch (Exception e) { throw getException(language, e); } } public InteropResponse restart(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { Shared.exit(); return new InteropResponse(new Boolean(true)); } catch (Exception e) { throw getException(language, e); } } public InteropResponse disable(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { Shared.controllerStatus.getApplication().alarms.clear(); Shared.controllerStatus.getApplication().setAlarm("alarm_disabled", true); Shared.model.clearDevices(); return new InteropResponse(new Boolean(true)); } catch (Exception e) { throw getException(language, e); } } public InteropResponse enable(InteropParameters parameters) throws SerializationException { String language = (String)parameters.getParameterValue("language"); try { Shared.model.readDevices(); Shared.controllerStatus.getApplication().setAlarm("alarm_disabled", false); return new InteropResponse(new Boolean(true)); } catch (Exception e) { throw getException(language, e); } } public static InteropResponse shell(InteropParameters parameters) { try { String command = (String)parameters.getParameterValue("command"); Process process = Runtime.getRuntime().exec(command); process.getOutputStream().close(); BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream())); String error = ""; String line; while ((line = stderr.readLine()) != null) error = error + line + "\r\n"; stderr.close(); if (error.length() == 0) return new InteropResponse(true); } catch (Exception e) { } return new InteropResponse(false); } protected HttpAuthentication getHttpAuthentication(InteropParameters parameters) throws SerializationException { try { String[] login = ((String)parameters.getParameterValue("token")).split(","); String username = login[0]; String password = login[1]; String computer = (String)parameters.getParameterValue("computer"); HttpAuthentication authentication = login(username, password, computer); return authentication; } catch (Exception exception) { } try { String token = Licence.decrypt((String)parameters.getParameterValue("token")); HttpAuthentication authentication = (HttpAuthentication)Serialization.deserialize(HttpAuthentication.class, token); return authentication; } catch (Exception exception) { } throw new SerializationException("Authentication token error"); } // private Device[] checkDevices (User user, Device[] devices) { try { if (user == null) return(devices); List list = new ArrayList(); for (Device device : devices) { if ((user.getDeviceInformation().municipality != null) && (device.getDeviceInformation().municipality != null) && (user.getDeviceInformation().municipality.equalsIgnoreCase(device.getDeviceInformation().municipality))) { list.add(device); } } return(list.toArray(new Device[0])); } catch (Exception e) { return(devices); } } // protected static SerializationException getException(String language, Exception exception) { StringWriter sw = new StringWriter(); exception.printStackTrace(new PrintWriter(sw)); return new SerializationException(Shared.getMessage(language, exception.getMessage()), sw.toString()); } protected static String[] getStringArray(InteropParameter parameter) { if (parameter.getValue() instanceof String[]) { return (String[])parameter.getValue(); } return ((String)parameter.getValue()).split(","); } public static long getTimestamp(String timestamp) { try { if ((timestamp.contains("/") == false) && (timestamp.contains("-") == false)) { if (timestamp.length() == 4) return new SimpleDateFormat("HHmm").parse(timestamp).getTime(); if (timestamp.length() == 6) return new SimpleDateFormat("HHmmss").parse(timestamp).getTime(); if (timestamp.length() == 9) return new SimpleDateFormat("HHmmssSSS").parse(timestamp).getTime(); if (timestamp.length() == 8) return new SimpleDateFormat("yyyyMMdd").parse(timestamp).getTime(); if (timestamp.length() == 10) return new SimpleDateFormat("yyyyMMddHH").parse(timestamp).getTime(); if (timestamp.length() == 12) return new SimpleDateFormat("yyyyMMddHHmm").parse(timestamp).getTime(); if (timestamp.length() == 14) return new SimpleDateFormat("yyyyMMddHHmmss").parse(timestamp).getTime(); if (timestamp.length() == 17) return new SimpleDateFormat("yyyyMMddHHmmssSSS").parse(timestamp).getTime(); } if (timestamp.indexOf("Z") == 23) { SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); ISO8601DATEFORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); return ISO8601DATEFORMAT.parse(timestamp).getTime(); } if ((timestamp.indexOf("/") == 4) && (timestamp.length() == 7)) return new SimpleDateFormat("yyyy/MM").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 2) && (timestamp.length() == 7)) return new SimpleDateFormat("MM/yyyy").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 4) && (timestamp.length() == 7)) return new SimpleDateFormat("yyyy-MM").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 2) && (timestamp.length() == 7)) return new SimpleDateFormat("MM-yyyy").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 4) && (timestamp.length() == 10)) return new SimpleDateFormat("yyyy/MM/dd").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 2) && (timestamp.length() == 10)) return new SimpleDateFormat("dd/MM/yyyy").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 4) && (timestamp.length() == 10)) return new SimpleDateFormat("yyyy-MM-dd").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 2) && (timestamp.length() == 10)) return new SimpleDateFormat("dd-MM-yyyy").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 4) && (timestamp.length() == 16)) return new SimpleDateFormat("yyyy/MM/dd HH:mm").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 2) && (timestamp.length() == 16)) return new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 4) && (timestamp.length() == 16)) return new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 2) && (timestamp.length() == 16)) return new SimpleDateFormat("dd-MM-yyyy HH:mm").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 4) && (timestamp.length() == 19)) return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 2) && (timestamp.length() == 19)) return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 4) && (timestamp.length() == 19)) return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 2) && (timestamp.length() == 19)) return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 4) && (timestamp.length() == 23)) return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").parse(timestamp).getTime(); if ((timestamp.indexOf("/") == 2) && (timestamp.length() == 23)) return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 4) && (timestamp.length() == 23)) return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(timestamp).getTime(); if ((timestamp.indexOf("-") == 2) && (timestamp.length() == 23)) return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS").parse(timestamp).getTime(); return Long.parseLong(timestamp); } catch (Exception exception) { } return 0; } // }