Skip to content

Commit

Permalink
Move Javascript to external files javamelody#782
Browse files Browse the repository at this point in the history
  • Loading branch information
nlbhuf committed Aug 28, 2020
1 parent ddf10cc commit 22b4932
Show file tree
Hide file tree
Showing 15 changed files with 250 additions and 207 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -553,11 +553,11 @@ public static void writeDataUnavailableForApplication(String application,
public static void showAlertAndRedirectTo(HttpServletResponse resp, String message,
String redirectTo) throws IOException {
final PrintWriter writer = createWriterFromOutputStream(resp);
writer.write("<script type='text/javascript'>alert('");
writer.write(I18N.javascriptEncode(message));
writer.write("');location.href='");
writer.write(redirectTo);
writer.write("';</script>");

final String msgAttribute = HtmlReport.createHtmlAttributeIfValuePresent("data-message", I18N.javascriptEncode(message));
final String redirectAttribute = HtmlReport.createHtmlAttributeIfValuePresent("data-redirect-to", redirectTo);

writer.write("<script type='text/javascript' src='?resource=showMessageAndRedirect.js' " + msgAttribute + " " + redirectAttribute + "' ></script>");
writer.close();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
import net.bull.javamelody.internal.model.UpdateChecker;
import net.bull.javamelody.internal.model.VirtualMachine;

import static net.bull.javamelody.internal.web.html.HtmlReport.createHtmlAttributeIfValuePresent;

/**
* Rapport html principal.
* @author Emeric Vernat
Expand Down Expand Up @@ -88,6 +90,7 @@ void toHtml() throws IOException {
}

void toHtml(String message, String anchorNameForRedirect) throws IOException {
writeln("<script type='text/javascript' src='?resource=coreReport.js'></script>");
writeAlerts();
if (collectorServer != null) {
writeApplicationsLinks();
Expand Down Expand Up @@ -239,16 +242,6 @@ private void writeAnchor(String anchorName, String menuText) throws IOException
}

private void writeMenu() throws IOException {
writeln("<script type='text/javascript'>");
writeln("function toggle(id) {");
writeln("var el = document.getElementById(id);");
writeln("if (el.getAttribute('class') == 'menuHide') {");
writeln(" el.setAttribute('class', 'menuShow');");
writeln("} else {");
writeln(" el.setAttribute('class', 'menuHide');");
writeln("} }");
writeln("</script>");

writeln("<div class='noPrint'> ");
writeln("<div id='menuBox' class='menuHide'>");
writeln(" <ul id='menuTab'><li><a href='javascript:toggle(\"menuBox\");'><img id='menuToggle' src='?resource=menu.png' alt='menu' /></a></li></ul>");
Expand Down Expand Up @@ -337,27 +330,10 @@ static void writeAddAndRemoveApplicationLinks(String currentApplication,
void writeMessageIfNotNull(String message, String partToRedirectTo,
String anchorNameForRedirect) throws IOException {
if (message != null) {
writeln("<script type='text/javascript'>");
// writeDirectly pour ne pas gérer de traductions si le message contient '#'
writeDirectly("alert(\"" + htmlEncodeButNotSpace(javascriptEncode(message)) + "\");");
writeln("");
// redirect vers une url évitant que F5 du navigateur ne refasse l'action au lieu de faire un refresh
if (partToRedirectTo == null) {
if (anchorNameForRedirect == null) {
writeln("location.href = '?'");
} else {
writeln("if (location.href.indexOf('?') != -1) {");
writeDirectly(
"location.href = location.href.substring(0, location.href.indexOf('?')) + '#"
+ anchorNameForRedirect + "';");
writeln("} else {");
writeDirectly("location.href = '#" + anchorNameForRedirect + "';");
writeln("}");
}
} else {
writeln("location.href = '?part=" + partToRedirectTo + '\'');
}
writeln("</script>");
final String messageAttribute = createHtmlAttributeIfValuePresent("data-message", htmlEncodeButNotSpace(javascriptEncode(message)));
final String redirectAttribute = createHtmlAttributeIfValuePresent("data-part-to-redirect-to", partToRedirectTo);
final String anchorAttribute = createHtmlAttributeIfValuePresent("data-anchor-name-for-redirect", anchorNameForRedirect);
writeln("<script type='text/javascript' src='?resource=showMessage.js' " + messageAttribute + "" + redirectAttribute + "" + anchorAttribute + "' ></script>");
}
}

Expand All @@ -381,18 +357,6 @@ private void writeGraphs() throws IOException {
if (!otherJRobins.isEmpty()) {
writeln("<div align='right'>");
writeShowHideLink("detailsGraphs", "#Autres_courbes#");
writeln("<script type='text/javascript'>");
writeln("function loadImages(elementId) {");
writeln(" var descendents = document.getElementById(elementId).getElementsByTagName('*');");
writeln(" for (var i = 0; i < descendents.length; i++) {");
writeln(" var element = descendents[i];");
writeln(" if (element instanceof HTMLImageElement && element.src == '') {");
writeln(" element.src = element.dataset.src;");
writeln(" }");
writeln(" }");
writeln("}");
writeln("document.getElementById('detailsGraphsA').href=\"javascript:loadImages('detailsGraphs');showHide('detailsGraphs');\";");
writeln("</script>");
writeln(END_DIV);
writeln("<div id='detailsGraphs' style='display: none;'><div>");
writeGraphs(otherJRobins, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@
*/
class HtmlCounterRequestGraphReport extends HtmlAbstractReport {
private static final int MAX_REQUEST_NAME_LENGTH = 5000;
private static final String SCRIPT_BEGIN = "<script type='text/javascript'>";
private static final String SCRIPT_END = "</script>";
private static int uniqueByPageAndGraphSequence;
private final Range range;
private final DecimalFormat systemErrorFormat = I18N.createPercentFormat();
Expand Down Expand Up @@ -162,7 +160,7 @@ void writeRequestAndGraphDetail(Collector collector, CollectorServer collectorSe
writeln("</div></td></tr></table>");
writeln("</div>");

writeGraphDetailScript(graphName);
writeln("<script type='text/javascript' src='?resource=graphReport.js'></script>");
}
if (request != null && request.getStackTrace() != null) {
writeln("<blockquote><blockquote><b>Stack-trace</b><br/><font size='-1'>");
Expand Down Expand Up @@ -456,59 +454,6 @@ private void writeCounterIcon(CounterRequest request) throws IOException {
}
}

private void writeGraphDetailScript(String graphName) throws IOException {
writeln(SCRIPT_BEGIN);
writeln("function handleHideMaximumClick(checkbox) {");
writeln(" var img = document.getElementById('img');");
writeln(" if (checkbox.checked) {");
writeln(" img.src = img.src + '\\u0026max=false\\u0026r=' + Math.random();");
writeln(" } else {");
writeln(" img.src = img.src.replace('\\u0026max=false','');");
writeln(" }");
writeln("}");
writeln("function scaleImage(v, min, max) {");
writeln(" var images = document.getElementsByClassName('synthèse');");
writeln(" w = (max - min) * v + min;");
writeln(" for (i = 0; i < images.length; i++) {");
writeln(" images[i].style.width = w + 'px';");
writeln(" }");
writeln("}");

// 'animate' our slider
writeln("var slider = new Control.Slider('handle', 'track', {axis:'horizontal', alignX: 0, increment: 2});");

// resize the image as the slider moves. The image quality would deteriorate, but it
// would not be final anyway. Once slider is released the image is re-requested from the server, where
// it is rebuilt from vector format
writeln("slider.options.onSlide = function(value) {");
writeln(" scaleImage(value, initialWidth, initialWidth / 2 * 3);");
writeln("}");

// this is where the slider is released and the image is reloaded
// we use current style settings to work the required image dimensions
writeln("slider.options.onChange = function(value) {");
// chop off "px" and round up float values
writeln(" width = Math.round(Element.getStyle('img','width').replace('px','')) - 80;");
writeln(" height = Math.round(width * initialHeight / initialWidth) - 48;");
// reload the images
// rq : on utilise des caractères unicode pour éviter des warnings
writeln(" document.getElementById('img').src = '?graph="
+ htmlEncodeButNotSpace(urlEncode(graphName))
+ "\\u0026width=' + width + '\\u0026height=' + height;");
writeln(" document.getElementById('img').style.width = '';");
writeln("}");
writeln("window.onload = function() {");
writeln(" if (navigator.appName == 'Microsoft Internet Explorer') {");
writeln(" initialWidth = document.getElementById('img').width;");
writeln(" initialHeight = document.getElementById('img').height;");
writeln(" } else {");
writeln(" initialWidth = Math.round(Element.getStyle('img','width').replace('px',''));");
writeln(" initialHeight = Math.round(Element.getStyle('img','height').replace('px',''));");
writeln(" }");
writeln("}");
writeln(SCRIPT_END);
}

private Map<String, CounterRequest> mapAllRequestsById() {
final Map<String, CounterRequest> result = new HashMap<String, CounterRequest>();
for (final Counter counter : counters) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ private void writeCustomPeriodDiv(Range currentRange, String graphName, String p
final String pattern = "yyyy-MM-dd";
final DateFormat dateFormat = new SimpleDateFormat(pattern, Locale.US);
final String max = dateFormat.format(new Date());
writeln("<form name='customPeriodForm' method='get' action='' onsubmit='return validateCustomPeriodForm();'>");

writeln("<form name='customPeriodForm' method='get' action='' onsubmit='return"
+ " validateCustomPeriodForm([\"customPeriodStartDate\", \"customPeriodEndDate\"],\"" + getStringForJavascript("dates_mandatory") + "\");'>");
writeln("<br/><b><label for='customPeriodStartDate'>#startDate#</label></b>&nbsp;&nbsp;");
writeln("<input type='date' id='customPeriodStartDate' name='startDate' size='10' required max='"
+ max + "' ");
Expand Down Expand Up @@ -98,33 +100,13 @@ private void writeCustomPeriodDiv(Range currentRange, String graphName, String p
writeln("<input type='hidden' name='part' value='" + part + "'/>");
writeln("<input type='hidden' name='graph' value='" + urlEncode(graphName) + "'/>");
}
writeln("<script type='text/javascript'>");
// On teste si l'élément <input type='date'> se transforme en <input type='text'
writeln("var test = document.createElement('input'); test.type = 'date';");
// Si c'est le cas, cela signifie que l'élément (html5) n'est pas pris en charge
writeln("if(test.type === 'text') {");
// si pas html5, on vide le champ pattern car il n'est pas au bon format
// et on affiche le format en langue du navigateur
writeln(" document.customPeriodForm.pattern.value = '';");
writeln(" document.getElementById('customPeriodPattern').style.display='inline';");
if (currentRange.getStartDate() != null) {
writeln(" document.customPeriodForm.startDate.value = '"
+ localeDateFormat.format(currentRange.getStartDate()) + "';");
}
if (currentRange.getEndDate() != null) {
writeln(" document.customPeriodForm.endDate.value = '"
+ localeDateFormat.format(currentRange.getEndDate()) + "';");
}
writeln("}");
writeln("function validateCustomPeriodForm() {");
writeln(" periodForm = document.customPeriodForm;");
writelnCheckMandatory("periodForm.startDate", "dates_mandatory");
writelnCheckMandatory("periodForm.endDate", "dates_mandatory");
writeln(" periodForm.period.value=periodForm.startDate.value + '"
+ Range.CUSTOM_PERIOD_SEPARATOR + "' + periodForm.endDate.value;");
writeln(" return true;");
writeln("}");
writeln("</script>");

String startDate = currentRange.getStartDate() == null ? "" : localeDateFormat.format(currentRange.getStartDate());
String endDate = currentRange.getEndDate() == null ? "" : localeDateFormat.format(currentRange.getEndDate());
final String startDateAttribute = HtmlReport.createHtmlAttributeIfValuePresent("data-start-date", startDate);
final String endDateAttribute = HtmlReport.createHtmlAttributeIfValuePresent("data-end-date", endDate);

writeln("<script type='text/javascript' src='?resource=customPeriod.js' " + startDateAttribute + " " + endDateAttribute + "'></script>");
writeln("</form><br/>");
writeln("</div>");
}
Expand Down Expand Up @@ -202,15 +184,12 @@ void writeAddAndRemoveApplicationLinks(String currentApplication,
+ "\"/> " + removeApplicationLabel + "</a>");
writeln("<div id='addApplication' style='display: none;'>");
}
writeln("<script type='text/javascript'>");
writeln("function validateAppForm() {");
writelnCheckMandatory("document.appForm.appName", "app_name_mandatory");
writelnCheckMandatory("document.appForm.appUrls", "app_urls_mandatory");
writeln(" return true;");
writeln("}");
writeln("</script>");
writeln("<script type='text/javascript' src='?resource=htmlForms.js'></script>");

writeln("<br/> <br/>");
writeln("<form name='appForm' method='post' action='' onsubmit='return validateAppForm();'>");
writeln("<form name='appForm' method='post' action='' onsubmit='return"
+ " validateElementNotEmpty(\"appName\", \"" + getStringForJavascript("app_name_mandatory")+ "\") &&"
+ " validateElementNotEmpty(\"appUrls\", \"" + getStringForJavascript("app_urls_mandatory") + "\");'>");
writeln("<br/><b><label for='appName'>#app_name_to_monitor#</label> :</b>&nbsp;&nbsp;<input type='text' size='15' id='appName' name='appName' required/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
writeln("<b><label for='appUrls'>#app_urls#</label> :</b>&nbsp;&nbsp;<input type='text' size='50' id='appUrls' name='appUrls' required/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
writeln("<input type='submit' value='#add#'/><br/>");
Expand All @@ -221,14 +200,9 @@ void writeAddAndRemoveApplicationLinks(String currentApplication,

if (applications.size() > 1) {
writeln("<div id='addAggregation' style='display: none;'>");
writeln("<script type='text/javascript'>");
writeln("function validateAggregationForm() {");
writelnCheckMandatory("document.aggregationForm.appName", "app_name_mandatory");
writeln(" return true;");
writeln("}");
writeln("</script>");
writeln("<br/> <br/>");
writeln("<form name='aggregationForm' method='post' action='' onsubmit='return validateAggregationForm();'>");
writeln("<form name='aggregationForm' method='post' action='' onsubmit='return"
+ " validateElementNotEmpty(\"appName\", \"" + getStringForJavascript("app_name_mandatory")+"\");'>");
writeln("<br/><b><label for='appName'>#aggregation_name_to_monitor#</label> :</b>&nbsp;&nbsp;<input type='text' size='15' id='appName' name='appName' required/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
writeln("<br/><b>#aggregated_apps# :</b>");
writeln("<table summary=''>");
Expand All @@ -246,15 +220,6 @@ void writeAddAndRemoveApplicationLinks(String currentApplication,
writeln("</div>\n");
}
}

private void writelnCheckMandatory(String fieldFullName, String msgKey) throws IOException {
writeln(" if (" + fieldFullName + ".value.length == 0) {");
writeln(" alert('" + getStringForJavascript(msgKey) + "');");
writeln(" " + fieldFullName + ".focus();");
writeln(" return false;");
writeln(" }");
}

@Override
void toHtml() {
throw new UnsupportedOperationException();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,7 @@ void writeHashPassword(String algorithm, String password) throws IOException {
final String hash = encodePassword(algorithm, password);
writeln("<input type='text' id='hash' value='" + hash + "' size='80' />");
writeln("<button onclick='copyHash()'>Copy</button>");
writeln("<script type='text/javascript'>");
writeln("function copyHash() {");
writeln("document.getElementById('hash').select();");
writeln("document.getElementById('hash').setSelectionRange(0, 99999); /*For mobile devices*/");
writeln("document.execCommand('copy');");
writeln("}");
writeln("</script>");
writeln("<script type='text/javascript' src='?resource=copyHash.js'></script>");
writeln("<br/><br/>");
}
writeln("<form action='' method='post' style='padding: 10px;'>");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,6 @@
* @author Emeric Vernat
*/
public class HtmlReport extends HtmlAbstractReport {
private static final String SCRIPT_BEGIN = "<script type='text/javascript'>";
private static final String SCRIPT_END = "</script>";
private static final URL THEMED_MONITORING_CSS = HtmlReport.class
.getResource("/net/bull/javamelody/resource/themedMonitoring.css");
private static final URL THEMED_MONITORING_JS = HtmlReport.class
Expand Down Expand Up @@ -115,6 +113,14 @@ public static void writeAddAndRemoveApplicationLinks(String currentApplication,
HtmlCoreReport.writeAddAndRemoveApplicationLinks(currentApplication, applications, writer);
}

public static String createHtmlAttributeIfValuePresent(String attributeName,
String value) {
if (value == null || value.length() == 0) {
return "";
}
return String.format(" %s=\"%s\" ", attributeName, value);
}

public void writeAllCurrentRequestsAsPart() throws IOException {
writeHtmlHeader();
final List<Counter> counters = collector.getRangeCountersToBeDisplayed(range);
Expand Down Expand Up @@ -219,58 +225,19 @@ private void writeHtmlHeader(boolean includeSlider, boolean includeCssInline)
writeln("<script type='text/javascript' src='?resource=themedMonitoring.js'></script>");
}
writeln("<script type='text/javascript' src='?resource=customizableMonitoring.js'></script>");
writeJavaScript();
writeln("<script type='text/javascript' src='?resource=htmlReport.js'></script>");
writeln("</head><body>");
}

public void writeHtmlFooter() throws IOException {
final String analyticsId = Parameter.ANALYTICS_ID.getValue();
if (analyticsId != null && !"disabled".equals(analyticsId)) {
writeDirectly(SCRIPT_BEGIN);
writeDirectly(
"var gaJsHost = (('https:' == document.location.protocol) ? 'https://ssl.' : 'http://www.');\n");
writeDirectly(
"document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n");
writeDirectly(SCRIPT_END);
writeDirectly(SCRIPT_BEGIN);
writeDirectly(" try{\n");
writeDirectly("var pageTracker = _gat._getTracker('" + analyticsId + "');\n");
writeDirectly("pageTracker._trackPageview();\n");
writeDirectly("} catch(err) {}\n");
writeDirectly(SCRIPT_END);
writeDirectly("\n");
final String analyticsIdAttribute = HtmlReport.createHtmlAttributeIfValuePresent("data-analytics-id", analyticsId);
writeln("<script type='text/javascript' src='?resource=htmlReportGoogleAnalytics.js' " + analyticsIdAttribute + "'></script>");
}
writeln("</body></html>");
}

private void writeJavaScript() throws IOException {
writeln(SCRIPT_BEGIN);
writeln("function showHide(id){");
writeln(" if (document.getElementById(id).style.display=='none') {");
writeln(" if (document.getElementById(id + 'Img') != null) {");
writeln(" document.getElementById(id + 'Img').src='?resource=bullets/minus.png';");
writeln(" }");
writeln(" try {");
writeln(" Effect.SlideDown(id, { duration: 0.5 });");
writeln(" } catch (e) {");
// si effects.js n'est pas chargé, par exemple dans last_shutdown.html
writeln(" document.getElementById(id).style.display='inline';");
writeln(" }");
writeln(" } else {");
writeln(" if (document.getElementById(id + 'Img') != null) {");
writeln(" document.getElementById(id + 'Img').src='?resource=bullets/plus.png';");
writeln(" }");
writeln(" try {");
writeln(" Effect.SlideUp(id, { duration: 0.5 });");
writeln(" } catch (e) {");
// si effects.js n'est pas chargé, par exemple dans last_shutdown.html
writeln(" document.getElementById(id).style.display='none';");
writeln(" }");
writeln(" }");
writeln("}");
writeln(SCRIPT_END);
}

public void writeMessageIfNotNull(String message, String partToRedirectTo) throws IOException {
htmlCoreReport.writeMessageIfNotNull(message, partToRedirectTo, null);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
function copyHash() {
document.getElementById('hash').select();
document.getElementById('hash').setSelectionRange(0, 99999); /*For mobile devices*/
document.execCommand('copy');
}
Loading

0 comments on commit 22b4932

Please sign in to comment.