I have created a Textarea in my app. And I have one method in my server i.e, in
GreetingServiceImpl class
The sample code of my method in GreetingServiceImpl class is:
public String greetServer(String input) throws IllegalArgumentException {
System.out.println("input===>>" + input);
String serverInfo = getServletContext().getServerInfo();
System.out.println("serverinfo===>>" + serverInfo);
String userAgent = getThreadLocalRequest().getHeader("User-Agent");
System.out.println("User agent===" + userAgent);
input = escapeHtml(input);
System.out.println("2....input===>>" + input);
userAgent = escapeHtml(userAgent);
return "Hello, " + input + "!<br><br>I am running " + serverInfo
+ ".<br><br>It looks like you are using:<br>" + userAgent;
}
Now in my client I will call this method, after calling this method I want to setText to my textarea. The text should come from the server.
i.e, I have 4 sysout statements in this method.
System.out.println("input===>>" + input);
System.out.println("serverinfo===>>" + serverInfo);
System.out.println("User agent===" + userAgent);
System.out.println("2....input===>>" + input);
When these statements prints into eclipse console , at the same time I want to print this in order(one by one according to their execution)in my UI i.e, into my textarea. I have no Idea how to achieve this. Please tel me is this possible to do, if so how I can achieve?
PS: I'm looking for a logger type functionality which can update my textarea when ever any server side mathods executed.
It's possible to push data from server to client using Atmosphere which supports WebSockets and GWT.
Why don't you use RPC calls? It is straightforward and easy.
You just create an Example.java and ExampleAsync class at client, and the implementation at server. You can then call the implementation with an AsyncCallback.
For example:
callback = new AsyncCallback() {
public void onSuccess(Void result) {
// Make what ever you want! For example, set the textarea
}
On the other hand, if you want server to notify and update client, you can use Server-Push
You can also use gwt-comet , which also streams messages over http.
Related
I have one config.js file:
sOptions = {
enabled: true,
vtest: assign,
stest: remove
}
I want to get value of 'vtest' using Java. I tried below code
ScriptEngine ee = new ScriptEngineManager().getEngineByName("nashorn");
ee.eval(new FileReader("config.js"));
System.out.println("ee: "+ee);
I am not seeing anything is write in log file.
First thing you need valid javascript. When I ran your original js I got exception messsages.
In the fix below I quoted both of your 'assign' and 'remove' values. Also, you need to print out the value that you want.
import javax.script.*;
public class NashornTest{
public static void main(String[] args) throws Exception{
String js = "sOptions = {\n" +
" enabled: true,\n" +
" vtest: 'assign',\n" +
" stest: 'remove'\n" +
"}";
ScriptEngine ee = new ScriptEngineManager().getEngineByName("nashorn");
ee.eval(js);
System.out.println("ee:" + ee);
System.out.println("sOptions: "+ee.get("sOptions"));
}
}
Which shows.
ee:jdk.nashorn.api.scripting.NashornScriptEngine#b3ca52e
sOptions: [object Object]
The next step is to get what you want from the data. Also, if you're just using JSON, you might want to use a JSON library instead of javascript.
Apparently, in the move from Spring Boot 1 to Spring Boot 2 (Spring 5), the encoding behavior of URL parameters for RestTemplates changed. It seems unusually difficult to get a general query parameter on rest templates passed so that characters that have special meanings such as "+" get properly escaped. It seems that, since "+" is a valid character, it doesn't get escaped, even though its meaning gets altered (see here). This seems bizarre, counter-intuitive, and against every other convention on every other platform. More importantly, I can't figure out how to easily get around it. If I encode the string first, it gets double-encoded, because the "%"s get re-encoded. Anyway, this seems like it should be something very simple that the framework does, but I'm not figuring it out.
Here is my code that worked in Spring Boot 1:
String url = "https://base/url/here";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
for (Map.Entry<String, String> entry : query.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
HttpEntity<TheResponse> resp = myRestTemplate.exchange(builder.toUriString(), ...);
However, now it won't encode the "+" character, so the other end is interpreting it as a space. What is the correct way to build this URL in Java Spring Boot 2?
Note - I also tried this, but it actually DOUBLE-encodes everything:
try {
for (Map.Entry<String, String> entry : query.entrySet()) {
builder.queryParam(entry.getKey(), URLEncoder.encode(entry.getValue(),"UTF-8" ));
}
} catch(Exception e) {
System.out.println("Encoding error");
}
In the first one, if I put in "q" => "abc+1#efx.com", then, exactly in the URL, I get "abc+1#efx.com" (i.e., not encoded at all). However, in the second one, if I put in "abc+1#efx.com", then I get "abc%252B1%2540efx.com", which is DOUBLE-encoded.
I could hand-write an encoding method, but this seems (a) like overkill, and (b) doing encoding yourself is where security problems and weird bugs tend to creep in. But it seems insane to me that you can't just add a query parameter in Spring Boot 2. That seems like a basic task. What am I missing?
Found what I believe to be a decent solution. It turns out that a large part of the problem is actually the "exchange" function, which takes a string for a URL, but then re-encodes that URL for reasons I cannot fathom. However, the exchange function can be sent a java.net.URI instead. In this case, it does not try to interpolate anything, as it is already a URI. I then use java.net.URLEncoder.encode() to encode the pieces. I still have no idea why this isn't standard in Spring, but this should work.
private String mapToQueryString(Map<String, String> query) {
List<String> entries = new LinkedList<String>();
for (Map.Entry<String, String> entry : query.entrySet()) {
try {
entries.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch(Exception e) {
log.error("Unable to encode string for URL: " + entry.getKey() + " / " + entry.getValue(), e);
}
}
return String.join("&", entries);
}
/* Later in the code */
String endpoint = "https://baseurl.example.com/blah";
String finalUrl = query.isEmpty() ? endpoint : endpoint + "?" + mapToQueryString(query);
URI uri;
try {
uri = new URI(finalUrl);
} catch(URISyntaxException e) {
log.error("Bad URL // " + finalUrl, e);
return null;
}
}
/* ... */
HttpEntity<TheResponse> resp = myRestTemplate.exchange(uri, ...)
I am trying to get the index status for a very large index using the Java API. In the background, I am updating the same index with large amounts of data
I have tried
IndicesStatsResponse indicesStatsResponse = client.admin().indices()
.prepareStats(index_name).all().execute().actionGet();
but this does not return the correct size because it is a very large index. However using the REST call, I got the correct answer.
GET /index_name/_stats
Perhaps I need to use some kind of listener mechanism, so I tried
IndicesStatsRequest req = new IndicesStatsRequest();
req.all();
client.admin().indices().stats(req, new ActionListener<IndicesStatsResponse>()
{
#Override
public void onResponse(IndicesStatsResponse response)
{
long s = response.getIndex(indexName).getTotal().getStore().getSizeInBytes();
System.out.println(indexName + " " + s);
}
..
});
but this threw org.elasticsearch.common.util.concurrent.EsRejectedExecutionException
I also tried
IndicesStatsRequest req = new IndicesStatsRequest();
req.all();
ActionFuture<IndicesStatsResponse> statsResponseFeature = client.admin().indices().stats(req.clear().flush(true).refresh(true));
IndicesStatsResponse statsResponse = statsResponseFeature.get(1, TimeUnit.MINUTES);
But this did not retrieve any useful information.
Strangely enough, when I run it in debug mode in Eclipse, it works perfectly. So maybe there is some flush mechanism I am missing.
What is the way out?
I am using the code below , as part of my push notifications implementation:
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = "3582-M4687r9k9k836r980kO2395i32i66y11a34";
String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + ";deviceside=false;ConnectionType=mds-public";
System.out.println("\n\n\n !!msg registerBPAS URL is: "+ registerUrl + "\n\n");
where :
private static String formRegisterRequest(String bpasUrl, String appId, String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
What i get printed is this :
!!msg registerBPAS URL is: http://pushapi.eval.blackberry.com/mss/PD_subReg?serviceid=3582-M4687r9[0.0] k9k836r980kO2395i32i66y11a34&osversion=5.0.0.669&model=9520;deviceside=false;ConnectionType=mds-publ[0.0] ic
I cant understand why though. Why there are spaces " " in the URL and why is there a "[0.0]"
From the code above i cant explain this behavior.
What i would expect to be printed is this:
!!msg registerBPAS URL is: http://pushapi.eval.blackberry.com/mss/PD_subReg?serviceid=3582-M4687r9k9k836r980kO2395i32i66y11a34&osversion=5.0.0.669&model=9520;deviceside=false;ConnectionType=mds-public
*I dont have BIS enabled if this is any help , but i dont think it matters as i am forming the URL locally.
All you're seeing is an extra [0.0] in your log in a couple places.
This is normal ... your URL is fine.
Calling
System.out.println("");
does not give you exclusive, or atomic, access to stdout. In other words, while the log is printing out the String you passed to println(), you can also get these tokens printed to the log, and other messages from the BlackBerry OS, and they may/will be placed right in the middle of your log output.
It's annoying, but there's nothing wrong with your code.
If you want another option, look at the BlackBerry EventLogger API, which writes to a log that you can pull off the device, and search through for your messages, without the annoying [0.0].
I need to create an automated process (preferably using Java) that will:
Open browser with specific url.
Login, using the username and password specified.
Follow one of the links on the page.
Refresh the browser.
Log out.
This is basically done to gather some statistics for analysis. Every time a user follows the link a bunch of data is generated for this particular user and saved in database. The thing I need to do is, using around 10 fake users, ping the page every 5-15 min.
Can you tink about simple way of doing that? There has to be an alternative to endless login-refresh-logout manual process...
Try Selenium.
It's not Java, but Javascript. You could do something like:
window.location = "<url>"
document.getElementById("username").value = "<email>";
document.getElementById("password").value = "<password>";
document.getElementById("login_box_button").click();
...
etc
With this kind of structure you can easily cover 1-3. Throw in some for loops for page refreshes and you're done.
Use HtmlUnit if you want
FAST
SIMPLE
java based web interaction/crawling.
For example: here is some simple code showing a bunch of output and an example of accessing all IMG elements of the loaded page.
public class HtmlUnitTest {
public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
final WebClient webClient = new WebClient();
final HtmlPage page = webClient.getPage("http://www.google.com");
System.out.println(page.getTitleText());
for (HtmlElement node : page.getHtmlElementDescendants()) {
if (node.getTagName().toUpperCase().equals("IMG")) {
System.out.println("NAME: " + node.getTagName());
System.out.println("WIDTH:" + node.getAttribute("width"));
System.out.println("HEIGHT:" + node.getAttribute("height"));
System.out.println("TEXT: " + node.asText());
System.out.println("XMl: " + node.asXml());
}
}
}
}
Example #2 Accessing named input fields and entering data/clicking:
final HtmlPage page = webClient.getPage("http://www.google.com");
HtmlElement inputField = page.getElementByName("q");
inputField.type("Example input");
HtmlElement btnG = page.getElementByName("btnG");
Page secondPage = btnG.click();
if (secondPage instanceof HtmlPage) {
System.out.println(page.getTitleText());
System.out.println(((HtmlPage)secondPage).getTitleText());
}
NB: You can use page.refresh() on any Page object.
You could use Jakarta JMeter