Use ACE Editor for Java Language in web - java

I wish to make an online java editor like ideone.com
I wish to use https://ace.c9.io/#nav=about&api=anchor to make my tool.
I have used codeEditor.session.setMode("ace/mode/java"); but stil my tool does not compile java language.
Till now my code is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="lib/css/editor-styles.css">
<title>Online Test</title>
</head>
<body>
<div class="editor">
<div class="editor__wrapper">
<div class="editor__body">
<div id="editorCode" class="editor__code"></div>
</div>
<div class="editor__footer">
<div class="editor__footer--left">
<button class="editor__btn editor__run">Run ></button>
<button class="editor__btn editor__reset">Reset ></button>
</div>
<div class="editor__footer--right">
<div class="editor__console">
<ul class="editor__console-logs"></ul>
</div>
</div>
</div>
</div>
</div>
<!-- Required Ace Libraries -->
<script src="lib/js/ace-editor/src-min/ace.js"></script>
<script src="lib/js/ace-editor/src-min/mode-javascript.js"></script>
<script src="lib/js/ace-editor/src-min/ext-language_tools.js"></script>
<!-- Custom Scripts -->
<script src="lib/js/editor.js"></script>
<script src="lib/js/editor-console.js"></script>
</body>
</html>
// Retrieve Elements
const consoleLogList = document.querySelector('.editor__console-logs');
const executeCodeBtn = document.querySelector('.editor__run');
const resetCodeBtn = document.querySelector('.editor__reset');
Building a Code Editor for the Web - Configuring Ace Editor
Building a Code Editor for the Web - Configuring Ace Editor
JS FILE
// Setup Ace
let codeEditor = ace.edit("editorCode");
let defaultCode = 'console.log("Editor")';
let consoleMessages = [];
let editorLib = {
clearConsoleScreen() {
consoleMessages.length = 0;
// Remove all elements in the log list
while (consoleLogList.firstChild) {
consoleLogList.removeChild(consoleLogList.firstChild);
}
},
printToConsole() {
consoleMessages.forEach(log => {
const newLogItem = document.createElement('li');
const newLogText = document.createElement('pre');
newLogText.className = log.class;
newLogText.textContent = `> ${log.message}`;
newLogItem.appendChild(newLogText);
consoleLogList.appendChild(newLogItem);
})
},
init() {
// Configure Ace
// Theme
codeEditor.setTheme("ace/theme/monokai");
// Set language
codeEditor.session.setMode("ace/mode/java");
// Set Options
codeEditor.setOptions({
fontFamily: 'Inconsolata',
fontSize: '12pt',
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
});
// Set Default Code
codeEditor.setValue(defaultCode);
}
}
// Events
executeCodeBtn.addEventListener('click', () => {
// Clear console messages
editorLib.clearConsoleScreen();
// Get input from the code editor
const userCode = codeEditor.getValue();
// Run the user code
try {
new Function(userCode)();
} catch (err) {
console.error(err);
}
// Print to the console
editorLib.printToConsole();
});
resetCodeBtn.addEventListener('click', () => {
// Clear ace editor
codeEditor.setValue(defaultCode);
// Clear console messages
editorLib.clearConsoleScreen();
})
editorLib.init();

How to add compile feature to it?
Hypothetically ... you get your editor to send the source code to a server that has a Java compiler installed and you run it.
If your app's server side is implemented in Java, you could make use of Java's runtime compilation APIs. See How do I programmatically compile and instantiate a Java class?. (Skip over the part about loading and running the compiled code ... unless you want to do that too.)

Ace is an editor, not a compiler.
You can't use it to compile code.
Ideone use Sphere Engine Compilers to compile...
Refer this documentation : link

Related

Selenium Access options for input drop-down list

I have an input control that acts as a read-only drop-down list (Svelte is framework behind it). How do I get a list of the drop-down options using Selenium and Java please? I have tried the select option:
Select allOptions = new Select(webDriver.getWebDriver().findElement(By.xpath(xpath)));
I got exceptions saying that you cannot select on an input. Because the control is read-only you can't type into it to enter values.
<input readonly="true" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" tabindex="0" type="text" aria-autocomplete="list" id="select-instances" placeholder="Select an instance" class="svelte-abcd" style="">
I have researched answers here, for example this one. You don't get list tags from Svelte. Any suggestions or help would be greatly appreciated.
I would try with sendKeys combination (you can experiment with ArrowDown, Tab, Enter) and then if it is not working for you - with JavaScript. You can set the text and then trigger onchange event if needed.
document.getElementById("select-instances").value = "My value";
or set the placeholder
document.getElementById("select-instances").setAttribute('placeholder','My value');
Reference:
What is JavaScriptExecutor in Selenium?
Open DevTools -> Sources
Click on the input -> Press F8 to stop JS execution in the browser
Inspect dropdown option -> Write down the xpath
public List<string> GetOptionsText(IWebDriver driver)
{
string parentInputXpath = "inputXpath";
string optionXpath = "optionXpath";
List<string> optionsText = new List<string>();
driver.FindElement(By.XPath(parentInputXpath)).Click();
options = driver.FindElement(By.XPath(parentInputXpath)).FindElements(By.XPath(optionXpath)).ToList();
if (options.Count == 0)
throw new NoSuchElementException("Dropdown options not found");
foreach (var option in options)
{
optionsText.Add(option.Text);
}
return optionsText;
}
P.S: It would be also good to add implicit/explicit waits here.
If Possible can you share pic of html code of the dropdown element
Select allOptions = new
Select(webDriver.getWebDriver().findElement(By.xpath(xpath)));
List<WebElement> elements = allOptions.getOptions();
List<String> options = new LinkedList<String();
for(WebElement el: elements)
{
options.Add(el.getText());
}
although I'm not a expert in selenium but just try to solve this problem. I create a index.html file to get the options from the dropdown menu. I only create a drop down menu in this index.html files its code is this:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="row">
<span class="label">Select Text</span>
<span class="box"><input readonly="true" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" tabindex="0" type="text" aria-autocomplete="list" id="datatext" placeholder="Select an instance" class="datatext" >
<select class="contentselect"
id="contentselect">
<option></option>
<option value="one">test1</option>
<option value="two">test2</option>
<option value="two">test3</option>
<option value="two">test4</option>
<option value="two">test5</option>
<option value="two">test6</option>
</select></span>
</div>
<script>
textfield = document.getElementById("datatext");
contentselect = document.getElementById("contentselect");
contentselect.onchange = function () {
var text = contentselect.options[contentselect.selectedIndex].value
if (text != "") {
textfield.value += text;
}
}
</script>
</body>
</html>
Then I create a java file to read all the options from the index.html. Java code looks like:-
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Goal Projects\\Webnovel API\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://127.0.0.1:5500/index.html");
Select allOptions = new Select(driver.findElement(By.xpath("//select[#id='contentselect']")));
List<WebElement> elements = allOptions.getOptions();
List<String> options = new ArrayList<String>();
for (WebElement element : elements) {
options.add(element.getText());
}
for (String s : options) System.out.println(s);
}
Result Output is like this:-
I think you are using wrong xpath you are using input xpath but you should use selection path.
I hope this will help you, Thanks for reading.

How to Capture Image using Web Camera in JSP only (Without using Servlet) and save it into MS SQL Server

I want to capture the image using web camera and store it into MS SQL Server database.
I am able to capture the image using web camera but right now i am trying to pass the image to next page but could not get the image on next jsp to process the image.
Code to capture image
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Web camera - Testing</title>
<script>
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function () {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = {"video": true},
errBack = function (error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if (navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function (stream) {
video.src = stream;
video.play();
}, errBack);
} else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function (stream) {
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if (navigator.mozGetUserMedia) { // WebKit-prefixed
navigator.mozGetUserMedia(videoObj, function (stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function () {
context.drawImage(video, 0, 0, 213, 160);
document.getElementById('canvasImg').src = canvas.toDataURL("image/png");
// document.getElementById('video').style.display = "none"; // hide the live image video portin after click on take picture
});
}, false);
</script>
</head>
<body>
<h1>Capture Image using Camera!</h1>
<!--
Ideally these elements aren't created until it's confirmed that the
client supports video/camera, but for the sake of illustrating the
elements involved, they are created with markup (not JavaScript)
-->
<video id="video" width="213" height="160" autoplay></video>
<button id="snap">Capture Photo</button>
<form action="savetesting.jsp" method="post">
<canvas id="canvas" width="213" height="160" name="ImageFile1" style="display: none;"></canvas>
<img id="canvasImg" name="ImageFile"><img>
<input type="reset" value="Reset"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
but now i am trying to get the captured image using
request.getParameter("ImageFile");
but could not succeed.
Please help me out with this issue, How to get the image on next page then i will try to save the image in MS SQL Server Database but only using JSP (without using Servlet).
Neither canvas nor img are form input fields, even when placed inside form tag. Add
<input type="hidden" name="ImageData" id="ImageData" />
to your form, and
document.getElementById('ImageData').value = canvas.toDataURL("image/png");
to the click event handler of the snap button.
Then, in JSP, get the image data (in the data URI format) using
String imageData = request.getParameter("ImageData");
and process them using javax.xml.bind.DatatypeConverter as described in Convert DataURL image to image file in java

How to handle Enums from backend in frontend

I use at frontend AngularJS 1.4 and at Backend Java and I have a lot of options which can be selected in frontend, e.g. the country:
GERMANY
FRANCE
USA
RUSSIA
Enums are written in upper case and I will customize this in frontend (e.g. FRANCE will become to France).
My question now would be if there is a directive or a any other support doing this in frontend.
In view:
<select ng-model="selectedCountry" ng-options="country as country.name for country in countries | filter:filterUpperCamelCase"></select>
In controller:
$scope.countries= [
{name:"SPAIN"},
{name:"GERMANY"}
];
$scope.filterUpperCamelCase = function(element){
element.name = element.name.toLowerCase();
element.name = element.name.charAt(0).toUpperCase() + element.name.slice(1);
return element;
};
Check out this link
http://hello-angularjs.appspot.com/angularjs-create-custom-filter
It has a custom filter written which can help you out.
Here's code from link given above.
<!DOCTYPE html>
<html ng-app="HelloApp">
<head>
<title></title>
</head>
<body ng-controller="HelloCtrl">
<form>
<input type="text" ng-model="name"/>
</form>
<div>{\{name|titlecase}}</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
// Code defining custom module consisting of a filter
// The module needs to be included as dependency for using the filter, titlecase
//
angular.module('CustomFilterModule', [])
.filter( 'titlecase', function() {
return function( input ) {
return input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
});
// Angular App on this page
// Included CustomFilterModule as dependency
//
angular.module('HelloApp', [ 'CustomFilterModule'])
.controller('HelloCtrl', ['$scope', function($scope){
$scope.name = '';
}])
</script>
</body>
</html>

How to run a child window java script function in parent window after changing the url in the parent window?

I want to execute the java script function of a child window on parent window, Even after changing the URL in the parent window.
I tried like below:
**Parent.html:**
<html>
<head>
<title>Parent window document</title>
</head>
<body>
<script type="text/Javascript">
function openChildWindow()
{
var s_url = "child.html";
var s_name = "ChildWindowDocument";
var s_specs = "resizable=yes,scrollbars=yes,toolbar=0,status=0";
var childWnd = window.open(s_url, s_name, s_specs);
var div = childWnd.document.getElementById("child_wnd_doc_div_id");
div.innerHTML = "Hello from parent wnd dddsfds";
}
</script>
<input type="button" value="Open child window document" name="sss" onclick="openChildWindow()" />
<div>Click me: nothing will happen.</div>
<div id="aaa" class="yourclass">
<p>This is a paragraph with a <span>span</span> where the paragraph's container has the class. Click the span or the paragraph and see what happens.</p>
This sentence is directly in the div with the class rather than in child element.
</div>
<div>Nothing for this div.</div>
<a>dsfsd</a>
</body>
</html>
**child.html:**
<html>
<head>
<title>Parent window document</title>
<script>
opener.document.body.onclick = function(e) {
var sender = (e && e.target) || (window.parent.event && window.parent.event.srcElement);
document.getElementById("id").value=sender.tagName;
}
</script>
</head>
<body>
<div id="child_wnd_doc_div_id">child window</div>
ID: <input type="text" id="id"/><br/>
Name: <input type="text" id="id"/><br/>
Xpath: <input type="text" id="id"/><br/>
CSS: <input type="text" id="id"/><br/>
</body>
</html>
Clearly, my concept is: I want to execute the child window function after changing the url in the parent window.
The only way I see:
observe the unload-event of the opener. When it fires, try(after a short timeout) to reassign the onclick-function(and also the onunlad-function).
Of course this will only work when both documents are placed under the same domain.

on click show Iframe

I have a map that you can click on locations to get information for that area and I would like to show that information in a Iframe on the same page when clicked
My page has this for the link now
`<AREA SHAPE="CIRCLE" COORDS="555,142,6" HREF="http://www.Page.com" TITLE="" />`
Any suggestions
The beauty of AJAX is that you don't really need an IFRAME to do this.
You've got a server that will return to you information about a certain area. Each of the AREA tags simply needs an onclick attribute that calls a JavaScript function to retrieve that information and display it in a location you set aside on your page.
Here is a sample HTML page that will retrieve information from the server using AJAX
<html>
<head>
<script type="text/javascript">
function getAreaInfo(id)
{
var infoBox = document.getElementById("infoBox");
if (infoBox == null) return true;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status != 200) alert(xhr.status);
infoBox.innerHTML = xhr.responseText;
};
xhr.open("GET", "info.php?id=" + id, true);
xhr.send(null);
return false;
}
</script>
<style type="text/css">
#infoBox {
border:1px solid #777;
height: 400px;
width: 400px;
}
</style>
</head>
<body onload="">
<p>AJAX Test</p>
<p>Click a link...
Area One
Area Two
Area Three
</p>
<p>Here is where the information will go.</p>
<div id="infoBox"> </div>
</body>
</html>
And here is the info.php that returns the information back to the HTML page:
<?php
$id = $_GET["id"];
echo "You asked for information about area #{$id}. A real application would look something up in a database and format that information using XML or JSON.";
?>
Hope this helps!

Categories

Resources