retrieve openID-url using openid4java - java

Consider the following code excerpt:
String openIDProviderURL = "https://www.google.com/accounts/o8/id";
try {
URI loc = getUI().getPage().getLocation();
List discoveries = manager.discover(openIDProviderURL);
DiscoveryInformation discovered = manager.associate(discoveries);
getUI().getSession().setAttribute("openid-disc", discovered);
AuthRequest authReq = manager.authenticate(discovered, "http://"+loc.getHost()+":"+loc.getPort()+loc.getPath());
FetchRequest fetch = FetchRequest.createFetchRequest();
authReq.addExtension(fetch);
System.out.println("DEST URL: "+authReq.getDestinationUrl(true));
getUI().getPage().setLocation(authReq.getDestinationUrl(true));
} catch (DiscoveryException ex) {
Logger.getLogger(NavigatorUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessageException ex) {
Logger.getLogger(NavigatorUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (ConsumerException ex) {
Logger.getLogger(NavigatorUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Authentication with Google works, however, can anyone tell me how to extract the actual openID-identifier-URL from the objects I'm using here? When the authentication succeeds, it lets me now by writing "INFO: Verification succeeded for: https://www.google.com/accounts/o8/id?blablabla", but so far, I haven't found a way to access this very URL in the program. Could someone help me out please?
PS: I have been going through older posts dealing with openID4java. However, they all deal with failed authentication and the likes, which for me isn't the problem. If this very question has been asked before, I apologise.

Related

Play framework - Set default language on server side

In my Play application I have an independent job which runs on server side in background. That job uses messages from messages.pl, but the problem is the server's default language is English so my messages cannot be reached. How can I change global default language for my application?
I have already tried Lang.apply("pl") in my Global class, but it doesn't work. I have also tested Controller.changeLang("pl") at user request, but since my job doesn't depends on any request it doesn't work as well.
Of course my application.conf file contains application.langs="pl".
EDIT
I forgot to mension, I'm using Play Framework 2.3.9.
Here is the code where I'm using messages (last line of each catch block). This function is called from the job (Akka scheduler):
public String processText(String text, String LPMN) {
lastError = "";
try {
String idt = nlpTextUpload(text);
return process(idt, LPMN);
} catch (NullPointerException ex) {
Logger.getLogger(SerelServiceRs.class.getName()).log(Level.WARNING, "Text to process is empty", ex);
play.Logger.warn("Text to process is empty", ex);
lastError = lastError.concat(Messages.get("error.process.emptyText")).concat("\n");
} catch (IOException ex) {
Logger.getLogger(SerelService.class.getName()).log(Level.SEVERE, "Problems in processing LPMN", ex);
play.Logger.error("Problems in processing LPMN", ex);
lastError = lastError.concat(Messages.get("error.process.lpmnProblem")).concat("\n");
} catch (InterruptedException ex) {
Logger.getLogger(SerelService.class.getName()).log(Level.SEVERE, null, ex);
play.Logger.error("Processing interrupt", ex);
lastError = lastError.concat(Messages.get("error.process.interrupt")).concat("\n");
}
return "";
}
And here is text from messages.pl:
error.process.emptyText=[BŁĄD]: Tekst do przetworzenia jest pusty
error.process.fileNotFound=[BŁĄD]: Plik nie został prawidłowo wczytany
error.process.lpmnProblem=[BŁĄD]: Błąd podczas wywoływania Web Serwisu
error.process.interrupt=[BŁĄD]: Przetwarzanie zostało przerwane

Accessing web API protected by Azure AD using a web app client

Can someone please explain me how to access the protected web api using a web app client?
I am trying something mentioned here in the following link. But I am always getting
The provided access grant is invalid or malformed.
https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx
Here is the code i am using for java
AuthenticationResult result = null;
try {
final Future<AuthenticationResult> resultFuture = context.acquireTokenByAuthorizationCode(
code, new URI(redirectUri), new ClientCredential(clientId, clientSecret), RESOURCE_GRAPH_API, null);
result = resultFuture.get();
} catch (InterruptedException | ExecutionException e) {
LOG.info("Failed to obtain access token: " + e.getMessage());
} catch (URISyntaxException e) {
}

Java how to find out if a URL is http or https?

I am writing a web crawler tool in Java. When I type the website name, how can I make it so that it connects to that site in http or https without me defining the protocol?
try {
Jsoup.connect("google.com").get();
} catch (IOException ex) {
Logger.getLogger(LinkGUI.class.getName()).log(Level.SEVERE, null, ex);
}
But I get the error:
java.lang.IllegalArgumentException: Malformed URL: google.com
What can I do? Are there any classes or libraries that do this?
What I'm trying to do is I have a list of 165 Courses, each with 65 - 71 html pages with links all throughout them. I am writing a Java program to test if the link is broken or not.
You can write your own simple method to try both protocols, like:
static boolean usesHttps(final String urlWithoutProtocol) throws IOException {
try {
Jsoup.connect("http://" + urlWithoutProtocol).get();
return false;
} catch (final IOException e) {
Jsoup.connect("https://" + urlWithoutProtocol).get();
return true;
}
}
Then, your original code can be:
try {
boolean shouldUseHttps = usesHttps("google.com");
} catch (final IOException ex) {
Logger.getLogger(LinkGUI.class.getName()).log(Level.SEVERE, null, ex);
}
Note: you should only use the usesHttps() method once per URL, to figure out which protocol to use. After you know that, you should connect using Jsoup.connect() directly. This will be more efficient.

Jersey: what does "couldn't find grammar element" mean?

After upgrading Jersey from version 1.15 to 1.17 it started to log the following messages:
Apr 2, 2013 5:13:06 PM com.sun.jersey.server.wadl.generators.AbstractWadlGeneratorGrammarGenerator attachTypes
INFO: Couldn't find grammar element for class java.lang.String
An example of a service that produces such a message:
#GET
#Path("/bla/{a}")
#Produces("application/json")
public String doStuff(#PathParam("a") String a) {
return a;
}
My first impression would be to consider this an error message, purely based on the way the message is phrased ("couldn't find"). However, it's logged at a level of INFO, and it doesn't seem to have any effects in practice since all services continue to work.
So my question is whether these log messages indicate a (potential) problem with the way we are configuring or using Jersey. Since it didn't happen with the previous version I already checked the release notes, but didn't find anything related.
I had the same "info" message as well. I didn't manage to fix it (yet) for basic java types (Boolean, String...) but for my own custom classes if I add the #XmlRootElement annotation and a default no-param constructor the message dissapears.
Digging into jersey source code I noticed the class "WadlGeneratorJAXBGrammarGenerator" the following code :
Object parameterClassInstance = null;
try {
Constructor<?> defaultConstructor = type.getDeclaredConstructor();
defaultConstructor.setAccessible(true);
parameterClassInstance = defaultConstructor.newInstance();
} catch (InstantiationException ex) {
LOGGER.log(Level.FINE, null, ex);
} catch (IllegalAccessException ex) {
LOGGER.log(Level.FINE, null, ex);
} catch (IllegalArgumentException ex) {
LOGGER.log(Level.FINE, null, ex);
} catch (InvocationTargetException ex) {
LOGGER.log(Level.FINE, null, ex);
} catch (SecurityException ex) {
LOGGER.log(Level.FINE, null, ex);
} catch (NoSuchMethodException ex) {
//getting here for Boolean/String and some other primitive data type
LOGGER.log(Level.FINE, null, ex);
}
if (parameterClassInstance==null) {
return null;
}
So basically there is no default constructor for String, Boolean and few others then it throws a NoSuchMethodException therefore it return nulls and log the info message.
So still no idea why it happens but in my case the solution was to disable the wadl generation since I was not using it.
Just add the following param to your web.xml
<init-param>
<param-name>com.sun.jersey.config.feature.DisableWADL</param-name>
<param-value>true</param-value>
</init-param>

Trasferring files and data with Jersey

I'm trying to develop some rest services with Jersey to upload and download files (something like a file manager). If my services produce/consume only File class as "application/octet-stream", like in the code below, they work.
#GET
#Produces("application/octet-stream")
public File getFile(String id) {
try {
File file = new File(System.getProperty("user.home"), id);
return file;
} catch (FileNotFoundException ex) {
Logger.getLogger(GenericResource.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GenericResource.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
But if I try to transfer a custom object that contains a File field and some other data (FileEnvelope in the sample) I obtain an error.
#GET
#Produces("application/octet-stream")
public FileEnvelope getXml(String id) {
try {
File file = new File(System.getProperty("user.home"), id);
FileEnvelope fileEnvelope = new FileEnvelope(file, "text");
return fileEnvelope;
} catch (FileNotFoundException ex) {
Logger.getLogger(GenericResource.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GenericResource.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
The error is
Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.mycompany.restdemo.FileEnvelope, and Java type class com.mycompany.restdemo.FileEnvelope, and MIME media type application/octet-stream was not found
Where I'm wrong? Is this the right way to manage this case? My client could not be a "Jersey client".
Jersey has no idea how to serialize your domain object into an octet-stream unless you tell it how. In this case if you want to include extra information beyond the file data you should consider how the client should be expected to read it. You could:
Embed the information directly in the octet stream by creating your own MessageBodyWriter. The client would need to know where to look for this information in the resulting file.
Include the information as part of the HTTP response header using ResponseBuilder. The client would just need to know which response headers to check for the information.
You can send different types of data in one message using multipart/* media types. For example this article shows how: http://aruld.info/handling-multiparts-in-restful-applications-using-jersey/

Categories

Resources