use of org.eclipse.kapua.app.console.setting.ConsoleSetting in project kapua by eclipse.
the class GwtDeviceManagementServiceImpl method checkIconResource.
/**
* Checks the source of the icon.
* The component config icon can be one of the well known icon (i.e. MqttDataTransport icon)
* as well as an icon loaded from external source with an HTTP link.
*
* We need to filter HTTP link to protect the console page and also to have content always served from
* EC console. Otherwise browsers can alert the user that content is served from domain different from
* *.everyware-cloud.com and over insicure connection.
*
* To avoid this we will download the image locally on the server temporary directory and give back the page
* a token URL to get the file.
*
* @param icon
* The icon from the OCD of the component configuration.
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws ImageReadException
*/
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
// Check if the resource is an HTTP URL or not
if (iconResource != null && (iconResource.toLowerCase().startsWith("http://") || iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes("UTF-8")));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/").append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
logger.warn("Content lenght exceeded ({}/{}) for URL: {}", new Object[] { contentLength, maxLength, iconResource });
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
logger.warn("Cannot get Content-Length header!");
}
logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
InputStream is = urlConnection.getInputStream();
OutputStream os = new FileOutputStream(tmpFile);
byte[] buffer = new byte[4096];
try {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
logger.warn("Maximum content lenght exceeded ({}) for URL: {}", new Object[] { maxLength, iconResource });
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
} finally {
os.close();
}
logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) || imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) || imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) || imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
logger.info("Image validation passed for URL: {}", iconResource);
} else {
logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = new StringBuilder().append("img://console/file/icons?id=").append(tmpFileName).toString();
logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null && tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
use of org.eclipse.kapua.app.console.setting.ConsoleSetting in project kapua by eclipse.
the class GwtDeviceManagementServiceImpl method findDeviceConfigurations.
//
// Configurations
//
@Override
public List<GwtConfigComponent> findDeviceConfigurations(GwtDevice device) throws GwtKapuaException {
List<GwtConfigComponent> gwtConfigs = new ArrayList<GwtConfigComponent>();
try {
// get the configuration
KapuaLocator locator = KapuaLocator.getInstance();
DeviceConfigurationManagementService deviceConfiguratiomManagementService = locator.getService(DeviceConfigurationManagementService.class);
KapuaId scopeId = KapuaEid.parseShortId(device.getScopeId());
KapuaId deviceId = KapuaEid.parseShortId(device.getId());
DeviceConfiguration deviceConfigurations = deviceConfiguratiomManagementService.get(scopeId, deviceId, null, null, null);
if (deviceConfigurations != null) {
// sort the list alphabetically by service name
List<DeviceComponentConfiguration> configs = deviceConfigurations.getComponentConfigurations();
Collections.sort(configs, new Comparator<DeviceComponentConfiguration>() {
@Override
public int compare(DeviceComponentConfiguration arg0, DeviceComponentConfiguration arg1) {
String name0 = arg0.getId();
String name1 = arg1.getId();
if (name0.contains(".")) {
name0 = name0.substring(name0.lastIndexOf('.'));
}
if (name1.contains(".")) {
name1 = name1.substring(name1.lastIndexOf('.'));
}
return name0.compareTo(name1);
}
});
// prepare results
ConsoleSetting consoleConfig = ConsoleSetting.getInstance();
List<String> serviceIgnore = consoleConfig.getList(String.class, ConsoleSettingKeys.DEVICE_CONFIGURATION_SERVICE_IGNORE);
for (DeviceComponentConfiguration config : deviceConfigurations.getComponentConfigurations()) {
// ignore items we want to hide
if (serviceIgnore != null && serviceIgnore.contains(config.getId())) {
continue;
}
KapuaTocd ocd = config.getDefinition();
if (ocd != null) {
GwtConfigComponent gwtConfig = new GwtConfigComponent();
gwtConfig.setId(config.getId());
gwtConfig.setName(ocd.getName());
gwtConfig.setDescription(ocd.getDescription());
if (ocd.getIcon() != null && ocd.getIcon().size() > 0) {
KapuaTicon icon = ocd.getIcon().get(0);
checkIconResource(icon);
gwtConfig.setComponentIcon(icon.getResource());
}
List<GwtConfigParameter> gwtParams = new ArrayList<GwtConfigParameter>();
gwtConfig.setParameters(gwtParams);
for (KapuaTad ad : ocd.getAD()) {
if (ad != null) {
GwtConfigParameter gwtParam = new GwtConfigParameter();
gwtParam.setId(ad.getId());
gwtParam.setName(ad.getName());
gwtParam.setDescription(ad.getDescription());
gwtParam.setType(GwtConfigParameterType.fromString(ad.getType().value()));
gwtParam.setRequired(ad.isRequired());
gwtParam.setCardinality(ad.getCardinality());
if (ad.getOption() != null && ad.getOption().size() > 0) {
Map<String, String> options = new HashMap<String, String>();
for (KapuaToption option : ad.getOption()) {
options.put(option.getLabel(), option.getValue());
}
gwtParam.setOptions(options);
}
gwtParam.setMin(ad.getMin());
gwtParam.setMax(ad.getMax());
if (config.getProperties() != null) {
// handle the value based on the cardinality of the attribute
int cardinality = ad.getCardinality();
Object value = config.getProperties().get(ad.getId());
if (value != null) {
if (cardinality == 0 || cardinality == 1 || cardinality == -1) {
gwtParam.setValue(value.toString());
} else {
// this could be an array value
if (value instanceof Object[]) {
Object[] objValues = (Object[]) value;
List<String> strValues = new ArrayList<String>();
for (Object v : objValues) {
if (v != null) {
strValues.add(v.toString());
}
}
gwtParam.setValues(strValues.toArray(new String[] {}));
}
}
}
gwtParams.add(gwtParam);
}
}
}
gwtConfigs.add(gwtConfig);
}
}
}
} catch (Throwable t) {
KapuaExceptionHandler.handle(t);
}
return gwtConfigs;
}
use of org.eclipse.kapua.app.console.setting.ConsoleSetting in project kapua by eclipse.
the class UploadRequest method doGetIconResource.
private void doGetIconResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String id = request.getParameter("id");
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("id");
}
if (!id.matches("[0-9A-Za-z]{1,}")) {
throw new IllegalArgumentException("id");
}
String tmpPath = System.getProperty("java.io.tmpdir");
StringBuilder filePathSb = new StringBuilder(tmpPath);
if (!tmpPath.endsWith("/")) {
filePathSb.append("/");
}
ConsoleSetting config = ConsoleSetting.getInstance();
filePathSb.append(config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER)).append("/").append(id);
File requestedFile = new File(filePathSb.toString());
if (!requestedFile.exists()) {
throw new IllegalArgumentException("id");
}
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
OutputStream out = response.getOutputStream();
IOUtils.copy(new FileInputStream(requestedFile), out);
}
use of org.eclipse.kapua.app.console.setting.ConsoleSetting in project kapua by eclipse.
the class SkinServlet method doGet.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileReader fr = null;
PrintWriter w = response.getWriter();
String resourceName = request.getPathInfo();
try {
// check to see if we have an external resource directory configured
ConsoleSetting consoleSettings = ConsoleSetting.getInstance();
String resourceDir = consoleSettings.getString(ConsoleSettingKeys.SKIN_RESOURCE_DIR);
if (resourceDir != null && resourceDir.trim().length() != 0) {
File fResourceDir = new File(resourceDir);
if (!fResourceDir.exists()) {
s_logger.warn("Resource Directory {} does not exist", fResourceDir.getAbsolutePath());
return;
}
File fResourceFile = new File(fResourceDir, resourceName);
if (!fResourceFile.exists()) {
s_logger.warn("Resource File {} does not exist", fResourceFile.getAbsolutePath());
return;
}
// write the requested resource
fr = new FileReader(fResourceFile);
char[] buffer = new char[1024];
int iRead = fr.read(buffer);
while (iRead != -1) {
w.write(buffer, 0, iRead);
iRead = fr.read(buffer);
}
}
} catch (Exception e) {
s_logger.error("Error loading skin resource", e);
} finally {
if (fr != null)
fr.close();
if (w != null)
w.close();
}
}
Aggregations