In my application, we use java applet to write cookie on browser and use jquery to read this cookie. I tried do like tutorial but I always don't see the cookie set on my browser.
http://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html
And here is my code:
The first I create a class to handle the cookie
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.util.List;
public class CookieAccessor implements CookieStore {
public CookieStore store;
public CookieManager manager;
public CookieAccessor() {
try {
manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(manager);
store = manager.getCookieStore();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void add(URI uri, HttpCookie cookie) {
// TODO Auto-generated method stub
store.add(uri, cookie);
}
#Override
public List<HttpCookie> get(URI uri) {
// TODO Auto-generated method stub
return store.get(uri);
}
#Override
public List<HttpCookie> getCookies() {
// TODO Auto-generated method stub
return store.getCookies();
}
#Override
public List<URI> getURIs() {
// TODO Auto-generated method stub
return store.getURIs();
}
#Override
public boolean remove(URI uri, HttpCookie cookie) {
// TODO Auto-generated method stub
return store.remove(uri, cookie);
}
#Override
public boolean removeAll() {
// TODO Auto-generated method stub
return store.removeAll();
}
}
Then I call it in main applet (I use jquery to run this applet):
try {
cookie = new CookieAccessor();
HttpCookie cookiedata = new HttpCookie("UserName", "Jonh");
URL url = new URL(getCodeBase().toString());
cookie.add(url.toURI(), cookiedata);
} catch(Exception e) {
e.printStackTrace();
}
But I've checked the browser cookies and there's no UserName What is missing in this code?
Many thanks!
Related
I need to create a TrxPlugin to verify if my Claim Line has a valid Product.
This is what I am trying to do:
import java.util.List;
import com.kernelsol.common.engine.Row;
import com.kernelsol.common.plugins.TrxPlugin;
public class MyTrxPlugin extends TrxPlugin {
#Override
public List<String> fields() throws Exception {
// TODO Auto-generated method stub
return null;
}
#Override
public Row augment(Row row) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
Here there is pseudocode about how to handle BLOB and CLOB in olingo jpa. I added the needed imports to the pseudocode:
package me;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import javax.sql.rowset.serial.SerialException;
import org.apache.olingo.odata2.jpa.processor.api.OnJPAWriteContent;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
public class OnDBWriteContent implements OnJPAWriteContent {
#Override
public Blob getJPABlob(byte[] binaryData) throws ODataJPARuntimeException {
try {
return new JDBCBlob(binaryData);
} catch (SerialException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
} catch (SQLException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return null;
}
#Override
public Clob getJPAClob(char[] characterData) throws ODataJPARuntimeException {
try {
return new JDBCClob(new String(characterData));
} catch (SQLException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return null;
}
}
the only problem is I couldn't find any implementation for JDBCBlob and JDBCClob. Any suggestion about how can I implement them or use some classes?
If You are using MySQL it requires an additional ExceptionInterceptor along with the Blob Implementation. You can have a custom implementation of ExceptionInterceptor and use it to initialise the Blob field.
The code to achieve it would be as follows
import java.sql.Blob;
import java.sql.Clob;
import java.util.Properties;
import org.apache.olingo.odata2.jpa.processor.api.OnJPAWriteContent;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
import com.mysql.cj.exceptions.ExceptionInterceptor;
import com.mysql.cj.log.Log;
public class CustomOnJPAWriteContent implements OnJPAWriteContent {
#Override
public Blob getJPABlob(byte[] binaryData) throws ODataJPARuntimeException {
return new com.mysql.cj.jdbc.Blob(binaryData, exceptionInterceptor);
}
#Override
public Clob getJPAClob(char[] characterData) throws ODataJPARuntimeException {
return new com.mysql.cj.jdbc.Clob(new String(characterData), exceptionInterceptor);
}
ExceptionInterceptor exceptionInterceptor = new ExceptionInterceptor() {
#Override
public Exception interceptException(Exception sqlEx) {
// TODO Auto-generated method stub
return null;
}
#Override
public ExceptionInterceptor init(Properties props, Log log) {
// TODO Auto-generated method stub
return null;
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
};
}
I'm trying to get some information from Firebase Real-time database without success. I don't know what I'm doing wrong. I also tried the doc's example and they didn't work. Here's my code and my firebase db structue:
Topics.java:
public class Topics {
private String name;
public Topics() {
}
public Topics(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Main.java
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream serviceAccount;
FirebaseOptions options = null;
try {
serviceAccount = new FileInputStream(".//...");
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("...")
.build();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
FirebaseApp.initializeApp(options);
String topics = getDatafromFirebase();
System.out.println("Everything right!");
}
private static String getDatafromFirebase() {
CountDownLatch done = new CountDownLatch(1);
StringBuilder b = new StringBuilder();
DatabaseReference dbRef = FirebaseDatabase.getInstance()
.getReference();
dbRef.child("topics").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
if(snapshot.exists()) {
for(DataSnapshot s:snapshot.getChildren()) {
Topics t = s.getValue(Topics.class);
b.append(t.getName());
b.append(" ");
done.countDown();
}
}
else {
b.append("No existe ");
done.countDown();
}
}
#Override
public void onCancelled(DatabaseError error) {
// TODO Auto-generated method stub
b.append("Error: "+error.getDetails());
done.countDown();
}
});
try {
done.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b.toString();
}
I have wait for the CountDownLatch for 5+ minutes, which I think is enough time for it to trigger. Also, important note: I have successfully sent message through firebase cloud messaging, so I don't think that it is a problem with the credentials.
I ran your code against my database with the same db structure and I can for sure say that I am ableto get information from the database.
onDataChange breakpoint not triggering only happens if I remove the topics subtree entirely. ie. in your case an empty database.
I suspect either your database url or Private Key JSON.
Follow the below Instruction for a new private key
In the console, click the gear icon on the left, and the Service Accounts Tab
Refer
Take a note of databaseUrl and click on Generate New Private Key, save it.
Refer
Here is the working code for example
package fireb;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Fireb {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream serviceAccount;
FirebaseOptions options = null;
try {
serviceAccount = new FileInputStream("C:\\key\\testapp-f0fe2-firebase-adminsdk-4po4a-5ce6c60b81.json");
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://testapp-f0fe2.firebaseio.com")
.build();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
FirebaseApp.initializeApp(options);
String topics = getDatafromFirebase();
System.out.println(topics);
System.out.println("Everything right!");
}
private static String getDatafromFirebase() {
CountDownLatch done = new CountDownLatch(1);
StringBuilder b = new StringBuilder();
DatabaseReference dbRef = FirebaseDatabase.getInstance()
.getReference();
dbRef.child("topics").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
if(snapshot.exists()) {
for(DataSnapshot s:snapshot.getChildren()) {
Topics t = s.getValue(Topics.class);
b.append(t.getName());
b.append(" ");
}
done.countDown();
}
else {
b.append("No existe ");
done.countDown();
}
}
#Override
public void onCancelled(DatabaseError error) {
// TODO Auto-generated method stub
b.append("Error: "+error.getDetails());
done.countDown();
}
});
try {
done.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b.toString();
}
}
According to the documentation available here.
Before you can access the Firebase Realtime Database from a server using the Firebase Admin SDK, you must authenticate your server with Firebase. When you authenticate a server, rather than sign in with a user account's credentials as you would in a client app, you authenticate with a service account which identifies your server to Firebase.
If you are not running your code on server, you may authenticate as a client instead as described here.
Hope this helps.
I don't know how to acquire token without username and password using the adal4j library. I have this code:
public class GetToken implements AuthenticationCallback {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "resource";
String redirectUrl = "redirecturl";
String authority = "https://login.microsoftonline.com/common/";
ExecutorService executor = null;
ClientAssertion clientId = new ClientAssertion("my-client-id");
AuthenticationCallback callback;
// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext;
try {
authContext = new AuthenticationContext(authority, false,executor);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Future <AuthenticationResult> result = authContext.acquireToken(resource, clientId, callback);
}
#Override
public void onSuccess(AuthenticationResult result) {
// TODO Auto-generated method stub
}
#Override
public void onFailure(Throwable exc) {
// TODO Auto-generated method stub
}
}
And I don't know how to acquire token ....
Check this link: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-webapp-java#step-8-create-the-basicfilter-file-for-basicfilter-mvc
Look into the getAccessToke() method.This is what you're looking for:
ExecutorService executor = Executors.newFixedThreadPool(1);
Hope this helps!
You will get an IllegalArgumentException as the Executor service passed to AuthenticationContext is null.
I get an unknown host error when I try to start an RMI server
here. The error is unknown host. Actually, I'm just a beginner in RMI and sockets programming in JAVA. Can you please provide me with some tutorials
concerning my problem.
My interface code:
package ApplicationServer;
import java.io.File;
import java.rmi.RemoteException;
import java.sql.ResultSet;
public interface Méthodes {
public String authentification(String login, String mdp) throws RemoteException;
public ResultSet selection(String requete) throws RemoteException;
public int miseAjour(String requete) throws RemoteException;
public String envoyerFichier(File fichier) throws RemoteException;
}
In this class I have all the methods that I need in my program:
package ApplicationServer;
import java.io.File;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Traitements extends UnicastRemoteObject implements Méthodes {
private Connection cnx;
private Statement stm;
private ResultSet rst;
private int rs;
public void setCnx(Connection cnx) {
this.cnx = cnx;
}
public void setStm(Statement stm) {
this.stm = stm;
}
public void setRst(ResultSet rst) {
this.rst = rst;
}
public void setRs(int rs) {
this.rs = rs;
}
protected Traitements() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
#Override
public String authentification(String login, String mdp) throws RemoteException {
// TODO Auto-generated method stub
try {
setCnx(null);
setStm(null);
setRst(null);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rst=stm.executeQuery("select md5('"+mdp+"');");
while(rst.next()){
mdp=rst.getString(1);
}
stm.clearBatch();
stm=cnx.createStatement();
setRst(null);
String Query = "select * from utilisateurs where login like '"+login+"' and motdepasse like '"+mdp+"';";
rst=stm.executeQuery(Query);
int id = 0;
String nm = null;
String prm = null;
while(rst.next()){
id = rst.getInt("id");
nm = rst.getString("nom");
prm = rst.getString("prenom");
}
if(id>0 && nm!=null && prm!=null){
return id+" "+nm+" "+prm;
}
}catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public ResultSet selection(String requete) throws RemoteException {
try{
setCnx(null);
setStm(null);
setRst(null);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rst=stm.executeQuery(requete);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rst;
}
#Override
public int miseAjour(String requete) throws RemoteException {
try{
setCnx(null);
setStm(null);
setRs(0);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rs=stm.executeUpdate(requete);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
#Override
public String envoyerFichier(File fichier) throws RemoteException {
// TODO Auto-generated method stub
return null;
}
}
This is the main class that runs the server:
package ApplicationServer;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int port=12345;
String url="rmi://serveur:"+port+"/reference";
LocateRegistry.createRegistry(port);
Traitements srv = new Traitements();
Naming.rebind(url, srv);
JOptionPane.showMessageDialog(null, "Serveur Lance :");
} catch (RemoteException | MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are supposed to replace serveur with a real hostname in that code.
However it's far better to use localhost in the RMI URL when binding. The Registry has to be local to the host anyway so there's no point in using anything else.