Skip to content

Commit

Permalink
javamelody#782 Move Javascript to external files
Browse files Browse the repository at this point in the history
  • Loading branch information
nlbhuf committed Aug 26, 2020
1 parent ddf10cc commit 07045ef
Show file tree
Hide file tree
Showing 15 changed files with 247 additions and 209 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.getAttributeIfValuePresent("data-message", I18N.javascriptEncode(message));
final String redirectAttribute = HtmlReport.getAttributeIfValuePresent("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.getAttributeIfValuePresent;

/**
* 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 @@ -309,8 +302,7 @@ private Map<String, HtmlCounterReport> writeCounters(List<Counter> counters)

private HtmlCounterReport writeCounter(Counter counter) throws IOException {
writeCounterTitle(counter);
final HtmlCounterReport htmlCounterReport = new HtmlCounterReport(counter, range,
getWriter());
final HtmlCounterReport htmlCounterReport = new HtmlCounterReport(counter, range, getWriter());
htmlCounterReport.toHtml();
return htmlCounterReport;
}
Expand All @@ -337,27 +329,11 @@ 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 = getAttributeIfValuePresent("data-message", message);
final String redirectAttribute = getAttributeIfValuePresent("data-part-to-redirect-to", partToRedirectTo);
final String anchorAttribute = getAttributeIfValuePresent("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,11 @@ 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>");
final String startDateAttribute = HtmlReport.getAttributeIfValuePresent("data-start-date",
currentRange.getStartDate() == null ? "" : localeDateFormat.format(currentRange.getStartDate()));
final String endDateAttribute = HtmlReport.getAttributeIfValuePresent("data-end-date",
currentRange.getEndDate() == null ? "" : localeDateFormat.format(currentRange.getEndDate()));
writeln("<script type='text/javascript' src='?resource=customPeriod.js' " + startDateAttribute + " " + endDateAttribute + "'></script>");
writeln("</form><br/>");
writeln("</div>");
}
Expand Down Expand Up @@ -202,15 +182,11 @@ 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 +197,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 +217,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=htmlHashPasswordReport.js'></script>");
writeln("<br/><br/>");
}
writeln("<form action='' method='post' style='padding: 10px;'>");
Expand Down
Loading

0 comments on commit 07045ef

Please sign in to comment.