use of com.servoy.j2db.persistence.Media in project servoy-client by Servoy.
the class SharedMediaResource method getResource.
private ResourceState getResource(final String iconId, final String solutionName) {
return new ResourceState() {
private String contentType;
private int length;
byte[] array = null;
@Override
public Time lastModifiedTime() {
try {
IRootObject solution = ApplicationServerRegistry.get().getLocalRepository().getActiveRootObject(solutionName, IRepository.SOLUTIONS);
if (solution != null)
return Time.valueOf(solution.getLastModifiedTime());
} catch (Exception e) {
Debug.trace(e);
}
return time;
}
@Override
public byte[] getData() {
if (array == null) {
boolean closeFS = false;
try {
final IRepository repository = ApplicationServerRegistry.get().getLocalRepository();
FlattenedSolution fs = null;
try {
if (Session.exists() && ((WebClientSession) Session.get()).getWebClient() != null) {
fs = ((WebClientSession) Session.get()).getWebClient().getFlattenedSolution();
}
if (fs == null) {
SolutionMetaData solutionMetaData = (SolutionMetaData) repository.getRootObjectMetaData(solutionName, IRepository.SOLUTIONS);
if (solutionMetaData == null)
return new byte[0];
closeFS = true;
IApplicationServer as = ApplicationServerRegistry.getService(IApplicationServer.class);
fs = new FlattenedSolution(solutionMetaData, new AbstractActiveSolutionHandler(as) {
@Override
public IRepository getRepository() {
return repository;
}
});
}
Media m = fs.getMedia(iconId);
if (m == null) {
try {
Integer iIconID = new Integer(iconId);
m = fs.getMedia(iIconID.intValue());
} catch (NumberFormatException ex) {
Debug.error("no media found for: " + iconId);
}
}
if (m != null) {
array = m.getMediaData();
contentType = m.getMimeType();
}
} finally {
if (closeFS && fs != null) {
fs.close(null);
}
}
if (array != null) {
if (contentType == null) {
contentType = MimeTypes.getContentType(array);
}
length = array.length;
}
} catch (Exception ex) {
Debug.error(ex);
}
}
return array == null ? new byte[0] : array;
}
/**
* @see wicket.markup.html.DynamicWebResource.ResourceState#getLength()
*/
@Override
public int getLength() {
return length;
}
@Override
public String getContentType() {
return contentType;
}
};
}
use of com.servoy.j2db.persistence.Media in project servoy-client by Servoy.
the class AngularIndexPageWriter method writeIndexPage.
public static void writeIndexPage(String page, HttpServletRequest request, HttpServletResponse response, String solutionName, String contentSecurityPolicyNonce) throws IOException, ServletException {
if (request.getCharacterEncoding() == null)
request.setCharacterEncoding("UTF8");
String uri = request.getRequestURI();
String clientnr = getClientNr(uri, request);
Pair<FlattenedSolution, Boolean> pair = getFlattenedSolution(solutionName, clientnr, request, response);
FlattenedSolution fs = pair.getLeft();
if (fs != null) {
StringBuilder sb = new StringBuilder(756);
String indexHtml = page;
final String path = Settings.getInstance().getProperty("servoy.context.path", request.getContextPath() + '/');
sb.append("<base href=\"");
sb.append(path);
sb.append("\">");
ContentSecurityPolicyConfig contentSecurityPolicyConfig = getContentSecurityPolicyConfig(request);
if (contentSecurityPolicyNonce != null) {
indexHtml = indexHtml.replace("<script ", "<script nonce='" + contentSecurityPolicyNonce + '\'');
}
String titleText = fs.getSolution().getTitleText();
if (StringUtils.isBlank(titleText)) {
titleText = fs.getSolution().getName();
} else if (titleText.equals("<empty>") || titleText.contains("i18n:") || titleText.contains(TagParser.TAGCHAR)) {
titleText = "";
}
sb.append("\n <title>");
sb.append(titleText);
sb.append("</title>");
if (fs.getMedia("manifest.json") != null) {
String url = "resources/" + FLATTENED_SOLUTION_ACCESS + "/" + fs.getName() + "/manifest.json";
sb.append("\n <link rel=\"manifest\" href=\"");
sb.append(url);
sb.append("\">");
}
Media headExtension = fs.getMedia("head-index-contributions.html");
if (headExtension != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(headExtension.getMediaData()), "UTF8"))) {
String line;
for (int count = 0; count < 1000 && (line = reader.readLine()) != null; count++) {
if (line.trim().startsWith("<meta") || line.trim().startsWith("<link")) {
sb.append("\n ");
sb.append(line);
}
}
} catch (Exception e) {
Debug.error(e);
}
}
sb.append("\n <script ");
if (contentSecurityPolicyConfig != null) {
sb.append("nonce='");
sb.append(contentSecurityPolicyConfig.getNonce());
sb.append("' ");
}
sb.append("src=\"solution/");
sb.append(solutionName);
sb.append('/');
sb.append(clientnr);
sb.append("/main/startup.js?");
sb.append(HTTPUtils.generateQueryString(request.getParameterMap(), request.getCharacterEncoding()));
sb.append("\"></script>");
indexHtml = indexHtml.replace("<base href=\"/\">", sb.toString());
String requestLanguage = request.getHeader("accept-language");
if (requestLanguage != null) {
indexHtml = indexHtml.replace("lang=\"en\"", "lang=\"" + request.getLocale().getLanguage() + "\"");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setContentLengthLong(indexHtml.length());
response.getWriter().write(indexHtml);
if (pair.getRight().booleanValue())
fs.close(null);
}
return;
}
use of com.servoy.j2db.persistence.Media in project servoy-client by Servoy.
the class MediaPropertyType method getMediaUrl.
public static String getMediaUrl(Object value, FlattenedSolution flattenedSolution, INGApplication application) {
String url = null;
Media media = null;
if (value instanceof CharSequence) {
value = ((CharSequence) value).toString();
}
if (value instanceof Integer) {
if (((Integer) value).intValue() == 0) {
// 0 means no media
return null;
}
media = flattenedSolution.getMedia(((Integer) value).intValue());
} else if (value instanceof String && ((String) value).toLowerCase().startsWith(MediaURLStreamHandler.MEDIA_URL_DEF)) {
media = flattenedSolution.getMedia(((String) value).substring(MediaURLStreamHandler.MEDIA_URL_DEF.length()));
} else {
if (value != null) {
media = flattenedSolution.getMedia(value.toString());
if (media == null) {
media = (Media) flattenedSolution.searchPersist(value.toString());
}
}
}
if (media != null) {
url = "resources/" + MediaResourcesServlet.FLATTENED_SOLUTION_ACCESS + "/" + media.getRootObject().getName() + "/" + media.getName();
Dimension imageSize = ImageLoader.getSize(media.getMediaData());
boolean paramsAdded = false;
if (imageSize != null) {
paramsAdded = true;
url += "?imageWidth=" + imageSize.width + "&imageHeight=" + imageSize.height;
}
if (application != null) {
Solution sc = flattenedSolution.getSolutionCopy(false);
if (sc != null && sc.getMedia(media.getName()) != null) {
if (paramsAdded)
url += "&";
else
url += "?";
url += "clientnr=" + application.getWebsocketSession().getSessionKey().getClientnr() + "&lm:" + sc.getLastModifiedTime();
}
}
} else if (value instanceof String && ((String) value).startsWith("resources/" + MediaResourcesServlet.FLATTENED_SOLUTION_ACCESS)) {
url = (String) value;
} else if (value != null) {
Debug.warn("Invalid media value received: " + value + ", cannot resolve it.");
}
return url;
}
use of com.servoy.j2db.persistence.Media in project servoy-client by Servoy.
the class ComponentFactory method createGraphicalComponent.
private static IComponent createGraphicalComponent(IApplication application, Form form, GraphicalComponent label, IScriptExecuter el, IDataProviderLookup dataProviderLookup) {
int style_halign = -1;
int style_valign = -1;
int textTransform = 0;
int mediaid = 0;
Pair<IStyleSheet, IStyleRule> styleInfo = getStyleForBasicComponent(application, label, form);
if (styleInfo != null) {
IStyleSheet ss = styleInfo.getLeft();
IStyleRule s = styleInfo.getRight();
if (ss != null && s != null) {
style_valign = ss.getVAlign(s);
style_halign = ss.getHAlign(s);
boolean parseMedia = true;
// anything else then then the css through the templategenerator is used. (See TemplateGenerator.createGraphicalComponentHTML)
if (application.getApplicationType() == IApplication.WEB_CLIENT) {
parseMedia = s.getValue(CSS.Attribute.BACKGROUND_REPEAT.toString()) == null && s.getValue(CSS.Attribute.BACKGROUND_POSITION.toString()) == null;
}
if (parseMedia) {
Object mediaUrl = s.getValue(CSS.Attribute.BACKGROUND_IMAGE.toString());
if (mediaUrl != null && mediaUrl.toString() != null) {
String mediaUrlString = mediaUrl.toString();
int start = mediaUrlString.indexOf(MediaURLStreamHandler.MEDIA_URL_DEF);
if (start != -1) {
String name = mediaUrlString.substring(start + MediaURLStreamHandler.MEDIA_URL_DEF.length());
if (name.endsWith("')") || name.endsWith("\")"))
name = name.substring(0, name.length() - 2);
if (name.endsWith(")"))
name = name.substring(0, name.length() - 1);
Media media = application.getFlattenedSolution().getMedia(name);
if (media != null) {
mediaid = media.getID();
}
}
}
}
String transform = s.getValue(CSS.Attribute.TEXT_TRANSFORM.toString());
if (transform != null) {
if ("uppercase".equals(transform)) {
textTransform = ILabel.UPPERCASE;
} else if ("lowercase".equals(transform)) {
textTransform = ILabel.LOWERCASE;
} else if ("capitalize".equals(transform)) {
textTransform = ILabel.CAPITALIZE;
}
}
}
}
ILabel l;
AbstractRuntimeLabel<? extends ILabel> scriptable;
IStylePropertyChangesRecorder jsChangeRecorder = application.getItemFactory().createChangesRecorder();
if (ComponentFactory.isButton(label)) {
IButton button;
if (label.getDataProviderID() == null && !label.getDisplaysTags()) {
scriptable = new RuntimeScriptButton(jsChangeRecorder, application);
button = application.getItemFactory().createScriptButton((RuntimeScriptButton) scriptable, getWebID(form, label));
} else {
scriptable = new RuntimeDataButton(jsChangeRecorder, application);
button = application.getItemFactory().createDataButton((RuntimeDataButton) scriptable, getWebID(form, label));
IDataProvider dp = null;
try {
dp = dataProviderLookup == null ? null : dataProviderLookup.getDataProvider(label.getDataProviderID());
} catch (RepositoryException e) {
Debug.error(e);
}
((IDisplayData) button).setDataProviderID(dp == null ? label.getDataProviderID() : dp.getDataProviderID());
((IDisplayTagText) button).setTagText(application.getI18NMessageIfPrefixed(label.getText()));
((IDisplayData) button).setNeedEntireState(label.getDisplaysTags());
}
((AbstractRuntimeButton<IButton>) scriptable).setComponent(button, label);
button.setMediaOption(label.getMediaOptions());
if (label.getRolloverImageMediaID() > 0) {
try {
button.setRolloverIcon(label.getRolloverImageMediaID());
button.setRolloverEnabled(true);
} catch (Exception ex) {
Debug.error(ex);
}
}
l = button;
} else {
if (label.getDataProviderID() == null && !label.getDisplaysTags()) {
scriptable = new RuntimeScriptLabel(jsChangeRecorder, application);
l = application.getItemFactory().createScriptLabel((RuntimeScriptLabel) scriptable, getWebID(form, label), (label.getOnActionMethodID() > 0));
} else {
scriptable = new RuntimeDataLabel(jsChangeRecorder, application);
l = application.getItemFactory().createDataLabel((RuntimeDataLabel) scriptable, getWebID(form, label), (label.getOnActionMethodID() > 0));
IDataProvider dp = null;
try {
dp = dataProviderLookup == null ? null : dataProviderLookup.getDataProvider(label.getDataProviderID());
} catch (RepositoryException e) {
Debug.error(e);
}
((IDisplayData) l).setDataProviderID(dp == null ? label.getDataProviderID() : dp.getDataProviderID());
((IDisplayTagText) l).setTagText(application.getI18NMessageIfPrefixed(label.getText()));
((IDisplayData) l).setNeedEntireState(label.getDisplaysTags());
}
((AbstractHTMLSubmitRuntimeLabel<ILabel>) scriptable).setComponent(l, label);
l.setMediaOption(label.getMediaOptions());
if (label.getRolloverImageMediaID() > 0) {
try {
l.setRolloverIcon(label.getRolloverImageMediaID());
} catch (Exception ex) {
Debug.error(ex);
}
}
}
String mnemonic = application.getI18NMessageIfPrefixed(label.getMnemonic());
if (mnemonic != null && mnemonic.length() > 0) {
l.setDisplayedMnemonic(mnemonic.charAt(0));
}
l.setTextTransform(textTransform);
if (el != null && (label.getOnActionMethodID() > 0 || label.getOnDoubleClickMethodID() > 0 || label.getOnRightClickMethodID() > 0)) {
l.addScriptExecuter(el);
if (label.getOnActionMethodID() > 0)
l.setActionCommand(Integer.toString(label.getOnActionMethodID()), Utils.parseJSExpressions(label.getFlattenedMethodArguments("onActionMethodID")));
if (label.getOnDoubleClickMethodID() > 0)
l.setDoubleClickCommand(Integer.toString(label.getOnDoubleClickMethodID()), Utils.parseJSExpressions(label.getFlattenedMethodArguments("onDoubleClickMethodID")));
if (label.getOnRightClickMethodID() > 0)
l.setRightClickCommand(Integer.toString(label.getOnRightClickMethodID()), Utils.parseJSExpressions(label.getFlattenedMethodArguments("onRightClickMethodID")));
}
if (label.getLabelFor() == null || (form.getView() != FormController.TABLE_VIEW && form.getView() != FormController.LOCKED_TABLE_VIEW)) {
int onRenderMethodID = label.getOnRenderMethodID();
AbstractBase onRenderPersist = label;
if (onRenderMethodID <= 0) {
onRenderMethodID = form.getOnRenderMethodID();
onRenderPersist = form;
}
if (onRenderMethodID > 0) {
RenderEventExecutor renderEventExecutor = scriptable.getRenderEventExecutor();
renderEventExecutor.setRenderCallback(Integer.toString(onRenderMethodID), Utils.parseJSExpressions(onRenderPersist.getFlattenedMethodArguments("onRenderMethodID")));
IForm rendererForm = application.getFormManager().getForm(form.getName());
IScriptExecuter rendererScriptExecuter = rendererForm instanceof FormController ? ((FormController) rendererForm).getScriptExecuter() : null;
renderEventExecutor.setRenderScriptExecuter(rendererScriptExecuter);
}
}
l.setRotation(label.getRotation());
l.setFocusPainted(label.getShowFocus());
l.setCursor(Cursor.getPredefinedCursor(label.getRolloverCursor()));
try {
int halign = label.getHorizontalAlignment();
if (halign != -1) {
l.setHorizontalAlignment(halign);
} else if (style_halign != -1) {
l.setHorizontalAlignment(style_halign);
}
} catch (RuntimeException e) {
// just ignore...Debug.error(e);
}
int valign = label.getVerticalAlignment();
if (valign != -1) {
l.setVerticalAlignment(valign);
} else if (style_valign != -1) {
l.setVerticalAlignment(style_valign);
}
try {
if (!label.getDisplaysTags()) {
l.setText(application.getI18NMessageIfPrefixed(label.getText()));
}
} catch (RuntimeException e1) {
// ignore
}
l.setToolTipText(application.getI18NMessageIfPrefixed(label.getToolTipText()));
if (label.getImageMediaID() > 0) {
try {
l.setMediaIcon(label.getImageMediaID());
} catch (Exception e) {
Debug.error(e);
}
} else if (mediaid > 0) {
try {
l.setMediaIcon(mediaid);
} catch (Exception e) {
Debug.error(e);
}
}
if (label.getDataProviderID() != null) {
scriptable.setComponentFormat(ComponentFormat.getComponentFormat(label.getFormat(), label.getDataProviderID(), dataProviderLookup, application));
}
applyBasicComponentProperties(application, l, label, styleInfo);
Border border = null;
Insets insets = null;
if (label.getBorderType() != null) {
border = ComponentFactoryHelper.createBorder(label.getBorderType());
}
if (label.getMargin() != null) {
insets = label.getMargin();
}
if (styleInfo != null && (border == null || insets == null)) {
IStyleSheet ss = styleInfo.getLeft();
IStyleRule s = styleInfo.getRight();
if (ss != null && s != null) {
if (border == null && ss.hasBorder(s)) {
border = ss.getBorder(s);
}
if (insets == null && ss.hasMargin(s)) {
insets = ss.getMargin(s);
}
}
}
if (border != null && insets != null) {
l.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(insets.top, insets.left, insets.bottom, insets.right)));
} else if (border == null && insets != null && l instanceof IButton) {
((IButton) l).setMargin(insets);
} else // supports setMargin, then fake the margins through empty border. (issue 166391)
if (border == null && insets != null) {
l.setBorder(BorderFactory.createEmptyBorder(insets.top, insets.left, insets.bottom, insets.right));
}
if (l instanceof IAnchoredComponent) {
((IAnchoredComponent) l).setAnchors(label.getAnchors());
}
return l;
}
use of com.servoy.j2db.persistence.Media in project servoy-client by Servoy.
the class MediaURLStreamHandler method openConnection.
@Override
public URLConnection openConnection(URL u) throws IOException {
final IServiceProvider app = this.application == null ? J2DBGlobals.getServiceProvider() : this.application;
String fname = u.getFile();
if (// $NON-NLS-1$
fname.startsWith("/")) {
fname = fname.substring(1);
}
if (// $NON-NLS-1$
fname.indexOf("?") != -1) {
fname = fname.substring(0, fname.indexOf("?"));
}
final String filename = fname;
if (filename.startsWith(MEDIA_URL_BLOBLOADER)) {
URLConnection urlc = new URLConnection(u) {
private byte[] array;
// $NON-NLS-1$
private String mimeType = "application/binary";
@Override
public void connect() throws IOException {
if (url != null) {
array = getBlobLoaderMedia(app, url.getQuery());
connected = array != null;
mimeType = getBlobLoaderMimeType(url.getQuery());
}
}
@Override
public String getHeaderField(String name) {
if (// $NON-NLS-1$
"content-length".equals(name)) {
if (array == null) {
// $NON-NLS-1$
return "0";
} else {
return Integer.toString(array.length);
}
} else if (// $NON-NLS-1$
"content-type".equals(name)) {
if (mimeType == null && array != null) {
return MimeTypes.getContentType(array);
} else {
return mimeType;
}
}
return super.getHeaderField(name);
}
@Override
public InputStream getInputStream() throws IOException {
if (!connected)
connect();
if (array != null) {
ByteArrayInputStream bais = new ByteArrayInputStream(array);
return bais;
} else {
return new InputStream() {
@Override
public int available() throws IOException {
return 0;
}
@Override
public int read() throws IOException {
return -1;
}
};
}
}
@Override
public String toString() {
// $NON-NLS-1$
return "MediaURL:" + url;
}
};
return urlc;
} else {
URLConnection urlc = new HttpURLConnection(u) {
private Media m;
private byte[] array;
private String etag;
private boolean useCachedVersion = false;
@Override
public void connect() throws IOException {
m = getMedia(filename, app);
if (m != null) {
array = m.getMediaData();
etag = getRequestProperty("If-None-Match");
if (("" + array.hashCode()).equals(etag)) {
array = null;
useCachedVersion = true;
} else {
etag = "" + array.hashCode();
}
connected = true;
}
}
@Override
public String getHeaderField(String name) {
if (// $NON-NLS-1$
"content-length".equals(name)) {
if (array == null) {
// $NON-NLS-1$
return "0";
} else {
return Integer.toString(array.length);
}
} else if (// $NON-NLS-1$
"content-type".equals(name)) {
if (m == null) {
return null;
} else {
return m.getMimeType();
}
}
return super.getHeaderField(name);
}
@Override
public InputStream getInputStream() throws IOException {
if (!connected)
connect();
if (array != null) {
ByteArrayInputStream bais = new ByteArrayInputStream(array);
return bais;
} else {
return new InputStream() {
@Override
public int available() throws IOException {
return 0;
}
@Override
public int read() throws IOException {
return -1;
}
};
}
}
@Override
public String toString() {
// $NON-NLS-1$
return "MediaURL:" + url;
}
@Override
public String getHeaderField(int n) {
if (n == 0) {
return "HTTP/1.1 200 OK";
}
return super.getHeaderField(n);
}
@Override
public Map<String, List<String>> getHeaderFields() {
HashMap<String, List<String>> mp = new HashMap<String, List<String>>();
ArrayList<String> al;
al = new ArrayList<String>();
al.add(etag);
// $NON-NLS-1$
mp.put("ETag", al);
al = new ArrayList<String>();
// $NON-NLS-1$
al.add("no-cache");
// $NON-NLS-1$
mp.put("Cache-Control", al);
return mp;
}
@Override
public int getResponseCode() throws IOException {
if (useCachedVersion) {
return HTTP_NOT_MODIFIED;
} else if (m == null) {
return HTTP_NOT_FOUND;
}
return HTTP_OK;
}
@Override
public void disconnect() {
}
@Override
public boolean usingProxy() {
return false;
}
};
return urlc;
}
}
Aggregations