i have a domain with fields like URL, lastModified etc. Now i want to view the information i get from this code into the list page. How can i do tht
def url = new URL("http://www.google.com")
HttpURLConnection connection = (HttpURLConnection)url.openConnection()
// long contentLength = Long.parseLong(connection.getHeaderField("Content-Length"));
connection.setRequestMethod("GET")
connection.connect()
connection.getURL()
println("Date: " + new Date(connection.getDate()))
println("LastModified Date:" + new Date(connection.getLastModified()))
if (connection.responseCode == 200 || connection.responseCode == 201){
def returnMessage = connection.content
//print out the full response
println "${returnMessage}";
System.out.println(connection.getURL());
} else {
println "Error Connecting to " + url
println "Couldn't connect to url"
}
From your controller, you can use the render method,
render returnMessage
(see http://grails.org/doc/2.0.x/ref/Controllers/render.html)
or pass it in a model to a gsp page and then print it from gsp,
return [returnMsg: returnMessage]
....(in .gsp)
${returnMsg}
(see http://grails.org/doc/2.0.x/guide/theWebLayer.html#GSPBasics)
Related
When doing calls to Exact-on-line API to get authenticated we run into the problem that getting the first refresh-token fails. We're not sure why. This is what we get back from Exact:
Http code: 400
JSON Data:
{
error='invalid_request',
description='Handle could not be extracted',
uri='null',
state='null',
scope='null',
redirectUri='null',
responseStatus=400,
parameters={}
}
We use this Java code based on library org.apache.oltu.oauth2.client (1.0.2):
OAuthClientRequest oAuthRequest = OAuthClientRequest //
.tokenLocation(BASE_URL + "/api/oauth2/token") //
.setGrantType(GrantType.AUTHORIZATION_CODE) //
.setClientId(clientId) //
.setClientSecret(clientSecret) //
.setRedirectURI(REDIRECT_URI) //
.setCode(code) //
.buildBodyMessage();
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse oauthResponse = client.accessToken(oAuthRequest, OAuth.HttpMethod.POST);
We did do the first step (getting the 'code' as used in setCode(...)) using a localhost-redirect as displayed in https://support.exactonline.com/community/s/knowledge-base#All-All-DNO-Content-gettingstarted There we copy the code from the address-bar of our browser and store it in a place the next computer-step can read it again.
This is due to the fact that the code was copied from your browsers address-bar. There you will find a URL-encoded version of the code (visible in the '%21' often) which when passed into the setCode verbatim will fail the subsequent calls.
Suggestion: URL-decode the value or setup a small temporary localhost-HTTP-server using Undertow or the like to catch the code that was send to you localhost-URL:
Undertow server = Undertow.builder() //
.addHttpListener(7891, "localhost") //
.setHandler(new HttpHandler() {
#Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
String code = exchange.getQueryParameters().get("code").getFirst();
LOG.info("Recieved code: {}.", code);
LOG.info("Store code");
storeCode(code);
LOG.info("Code stored");
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send( //
"Thanks for getting me the code: " + code + "\n" //
+ "Will store it for you and get the first refreshToken..." //
+ "Please have a look at " + OAUTH_STATE_INI
+ " for the new code & refreshToken in a minute" //
);
done.add("done");
}
}).build();
server.start();
NB: Do make sure the redirect URL is correct in your Exact-app-settings
In an Java agent I generate a mail. When I send this only with text then the mail is sent to the recipient. I also want to attach an xml file to the mail. If I attach it my notes server crashes.
I think my code is wrong, this is the part where I want to add the attachment to the mail:
mime = mimeRoot.createChildEntity();
MIMEHeader hdr = mime.createHeader("Content-Disposition");
hdr.setHeaderValAndParams("attachment; filename=" + OrderFilePath);
Stream stream = session.createStream();
System.out.println("Open stream");
//AT THIS IF IT WILL CRASH THE SERVER
if (stream.open(OrderFilePath, "binary")){
System.out.println("in eerste if");
if (stream.getBytes() != 0) {
System.out.println("getbytes !0 ");
mime.setContentFromBytes(stream, "application/octet-stream",MIMEEntity.ENC_IDENTITY_BINARY);
}
else System.out.println
(OrderFilePath + "has no content or is not working");
}
I have some working LotusScript code that does almost the same, with the exception of two lines:
hdr.setHeaderValAndParams("attachment; filename=\\"" + OrderFilePath + "\\"");
and
mime.setContentFromBytes(stream, "application/octet-stream; name=\\"" + OrderFilePath + "\\"",MIMEEntity.ENC_IDENTITY_BINARY);
My LS code, so yo can see for yourself:
ForAll att In attachments
disposition= "attachment"
If att.isInLine Then disposition= "inline"
Set sect = body.createChildEntity()
Call sect.CreateHeader("Content-Disposition").SetHeaderValAndParams(disposition + {; filename="} & att.attName & {";"} )
Call sect.CreateHeader("Content-ID").SetHeaderVal( |<| & ListTag(att) & |>| )
Set stream = session.CreateStream
If stream.Open(att.attFile) Then
Call sect.SetContentFromBytes(stream, strContentType & {; name="} & att.attName & {"}, ENC_IDENTITY_BINARY)
Call stream.Close
End If
End Forall
attachments is a list of Attachment objects that contain only the name and the filepath of an attachment; it isn't a full Notes attachment embedded object thing.
I have a Java application that uses the Google Cloud Print API (https://github.com/jittagornp/GoogleCloudPrint) to print pdf's. In most cases it works like a charm but every now and then (approx 1 out of 100) it gives an error back which looks like this "Det går inte att göra ändringar i ett avslutat jobb".
Roughly translated to english it reads: "Can't make changes to a finished job"
The kicker is that the pages prints perfectly every time, with or without the error.
Code looks like this for every call to GCP:
public static SubmitJobResponse submitPrintJob(String filename, String type){
String jsonTicket;
String printerId;
SubmitJobResponse response = null;
String jobtitle;
jobtitle = filename.substring(filename.lastIndexOf('/') + 1);
// Login to GCP
GoogleCloudPrint cloudPrint = gcpLogin();
jsonTicket = "{'version':'1.0','print':{'vendor_ticket_item':[],'color':{'type':1},'copies':{'copies':4}}}";
printerId = session("printerlabel");
try {
// Get file as byte array
Path path = Paths.get(filename);
byte[] content = Files.readAllBytes(path);
Gson gson = new Gson();
Ticket ticket = gson.fromJson(jsonTicket, Ticket.class);
String json = gson.toJson(ticket);
//create job
SubmitJob submitJob = new SubmitJob();
submitJob.setContent(content);
submitJob.setContentType("application/pdf");
submitJob.setPrinterId(printerId);
submitJob.setTicket(ticket);
submitJob.setTitle(jobtitle);
//send job
response = cloudPrint.submitJob(submitJob);
Logger.debug("PrinterID => {}", printerId);
Logger.debug("submit job response => {}", response.isSuccess() + "," + response.getMessage());
if(response.isSuccess()) {
Logger.debug("submit job id => {}", response.getJob().getId());
}
cloudPrint.disconnect();
} catch (Exception ex) {
Logger.warn(null, ex);
}
return response;
}
The API uses a call to "/submit?output=json&printerid=" at GCP so why does it say that I'm trying to change a finished job - I'm not submitting a job id - only printer id.
How do I get rid of these false errors?
I am currently trying to create a cookie in JavaScript. The idea is that when the user clicks the extension icon whilst watching a YouTube video it gets the tab name and saves it as a cookie. This is so that I can then access the cookie from my Java program.
I am using chrome and I can't see the cookie in the list when I have pressed it even though the alert successfully displays so I am wondering if anyone can see an issue with my code.
Also if anyone has a better idea of how to get the tab name to my Java program I would be happy to hear your ideas.
Thanks everyone, here's my code:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
createCookie(cookieName, cookieValue);
});
}
function createCookie(name, value)
{
var expires = new Date().getTime() + (1000 * 3600);
var domain = ";domain=.youtube.com";
document.cookie = name + "=" + value + ";expires=" + expires + domain + ";path=/";
alert(name + " = " + value + ". Date = " + expires);
}
EDIT: I have changed my code to use the chrome API's provided by Google, great success!
If anyone has the same problem I have used the Google API's for chrome concerning cookies.
My new code is the following:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
}
Note: In the manifest file you will need permissions for tabs, cookies and the website domain. Furthermore I have not stated when the cookie expires thus it expires when the session is closed.
Using DJ Native Swing it is possible to show a web page within a java application. When you do this it is also possible to communicate from the browser to the java runtime environment using the "command" protocol. The documentation has a code snippet which demonstrates it's usage:
function sendCommand( command ){
var s = 'command://' + encodeURIComponent( command );
for( var i = 1; i < arguments.length; s+= '&' + encodeURIComponent( arguments[i++] ) );
window.location = s;
}
As it looks here it seems to be a regular GET request to an url using the command protocol instead of http. Although when I create and image, script tag or just and ajax get request there is no response and the breakpoint in the java runtime isn't triggered.
I don't want to set the window.location because I don't want to navigate away from the page I am currently at. Using the link to navigate to a command url does work though but it also navigates away from the current page. The page uses OpenLayers and dojo. (I have also tried dojo.io.script)
After some work I have found a neat way to communicate with the java runtime which doesn't trigger a refresh of the page every time there is communication. It is inspired on the way JSONP works to get around the cross domain restriction in most browsers these days. Because an iFrame will also trigger a command:// url it possible to do a JSONP like action using this technique. The code on the client side (browser):
dojo.provide( "nmpo.io.java" );
dojo.require( "dojo.io.script" );
nmpo.io.java = dojo.delegate( dojo.io.script, {
attach: function(/*String*/id, /*String*/url, /*Document?*/frameDocument){
// summary:
// creates a new tag pointing to the specified URL and
// adds it to the document.
// description:
// Attaches the script element to the DOM. Use this method if you
// just want to attach a script to the DOM and do not care when or
// if it loads.
var frame = dojo.create( "iframe", {
id: id,
frameborder: 0,
framespacing: 0
}, dojo.body( ) );
dojo.style( frame, { display: "none" } );
dojo.attr( frame, { src: url } );
return frame;
},
_makeScriptDeferred: function(/*Object*/args){
//summary:
// sets up a Deferred object for an IO request.
var dfd = dojo._ioSetArgs(args, this._deferredCancel, this._deferredOk, this._deferredError);
var ioArgs = dfd.ioArgs;
ioArgs.id = dojo._scopeName + "IoScript" + (this._counter++);
ioArgs.canDelete = false;
//Special setup for jsonp case
ioArgs.jsonp = args.callbackParamName || args.jsonp;
if(ioArgs.jsonp){
//Add the jsonp parameter.
ioArgs.query = ioArgs.query || "";
if(ioArgs.query.length > 0){
ioArgs.query += "&";
}
ioArgs.query += ioArgs.jsonp
+ "="
+ (args.frameDoc ? "parent." : "")
+ "nmpo.io.java.jsonp_" + ioArgs.id + "._jsonpCallback";
ioArgs.frameDoc = args.frameDoc;
//Setup the Deferred to have the jsonp callback.
ioArgs.canDelete = true;
dfd._jsonpCallback = this._jsonpCallback;
this["jsonp_" + ioArgs.id] = dfd;
}
return dfd; // dojo.Deferred
}
});
When a request is sent to the java runtime a callback argument will be supplied and a webBrowser.executeJavascript( callbackName + "(" + json + ");" ); action can be executed to trigger the callback in the browser.
Usage example client:
dojo.require( "nmpo.io.java" );
nmpo.io.java.get({
// For some reason the first paramater (the one after the '?') is never in the
// paramater array in the java runtime. As a work around we stick in a dummy.
url: "command://sum?_",
callbackParamName: "callback",
content: {
numbers: [ 1, 2, 3, 4, 5 ].join( "," )
},
load: function( result ){
console.log( "A result was returned, the sum was [ " + result.result + " ]" );
}
});
Usage example java:
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
#Override
public void commandReceived(WebBrowserCommandEvent e) {
// Check if you have the right command here, left out for the example
// Parse the paramaters into a Hashtable or something, also left out for the example
int sum = 0;
for( String number : arguments.get( "numbers" ).split( "," ) ){
sum += Integer.parseInt( number );
}
// Execute the javascript callback like would happen with a regular JSONP call.
webBrowser.executeJavascript( arguments.get( "callback" ) + "({ result: " + sum + " });" );
}
});
Also with IE in the frame I can highly recommend using firebug lite, the dev tools for IE are not available.