I'am trying this example https://cloud.google.com/appengine/docs/java/tools/remoteapi
Everything works fine if I run script as java application, but when I do it as servlet it always loads forever and doesn't throw any errors. Also works fine on localhost. Also I noticed it happens when query is made, when I comment it out (datastore.put), servlet loads instantly.
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.remoteapi.RemoteApiInstaller;
import com.google.appengine.tools.remoteapi.RemoteApiOptions;
#SuppressWarnings("serial")
public class Gae_java_Servlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
RemoteApiOptions options = new RemoteApiOptions()
.server("java-dot-project.appspot.com", 443)
.useApplicationDefaultCredential();
RemoteApiInstaller installer = new RemoteApiInstaller();
installer.install(options);
try {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
System.out.println("Key of new entity is " +
datastore.put(new Entity("Hello Remote API!")));
} finally {
installer.uninstall();
}
}
}
I figured it out, needed to use RemoteApiOptions().useServiceAccountCredential("service email", "p12key") instead of useApplicationDefaultCredential()
Related
Am using firebase admin sdk and JavaEE on intellij built on gradle and glassfish server.
am trying to push a value to realtime database, but sadly am unable to do so. I've been searching online for weeks now and gotten nothing. I also followed some solutions in stackoverflow answers like : Firebase Java Admin SDK don't work but nothing works for me.
I've read a lot of reasons why such a problem would occur with firebase admin sdk but i have no solutions.
here's my code:
package sample;
package sample;
import com.google.api.core.ApiFuture;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.UserRecord;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import sample.model.FireBaseAuth;
import sample.model.FireBaseUtils;
import sample.model.Owner;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
#WebServlet("/success")
public class SuccessServlet extends HttpServlet {
public void init() throws ServletException {
super.init();
FireBaseUtils.initilizeFirebase();
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String email = request.getParameter("email");
String password = request.getParameter("pass");
//System.out.println(name);
try{
//a hashmap for the number of shopsOwned
HashMap<String, String> shopsOwned = new HashMap<>();
shopsOwned.put("shopName" , "shopName");
//get the database instance and the database reference
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Business");
DatabaseReference ownersRef = ref.child("Owners"); //further get the reference to the owners node
//create a new owner with the values of the new user, using the Owner class
Owner newOwner = new Owner("userRecord2.getUid()", "userRecord2.getDisplayName()",
"userRecord2.getPhoneNumber()", "userRecord2.getEmail()", shopsOwned);
//create a hashmap of the users, in this case, just one user
Map<String, Owner> users = new HashMap<>();
users.put("userRecord2getPhoneNumber", newOwner); //add the new owner to the hashmap
System.out.println("this is the user :" + newOwner.getFull_name());
//push the new owner hashmap to the database reference
ApiFuture<Void> future = ownersRef.push().setValueAsync(users);
//Object o = future.get(8, TimeUnit.SECONDS);
System.out.println(future.isDone());
//System.out.println(future.isDone());
request.getRequestDispatcher("success.jsp").forward(request, response);
}catch(Exception e){e.printStackTrace();}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
}
any ideas will be appreciated.
Edit : I dont get any errors whatsoever, the webapp runs normally but the realtime db at firebase isn't updated
You need to wait until the future is complete, before the request thread is returned. Otherwise there's no guarantee that the update is completed, and any errors are silently discarded. So try something like the following:
ApiFuture<Void> future = ownersRef.push().setValueAsync(users);
future.get();
request.getRequestDispatcher("success.jsp").forward(request, response);
Writing to Firestore (like interaction with most cloud APIs) happens asynchronously, and on a different thread. When you call future.isDone(), the operation isn't done yet.
You'll want to add a callback that gets called when the operation has completed:
ApiFuture<Void> future = ownersRef.push().setValueAsync(users);
future.addCallback(future, new ApiFutureCallback<String>() {
#Override
public void onSuccess(String result) {
System.out.println("Operation completed with result: " + result);
System.out.println(future.isDone());
request.getRequestDispatcher("success.jsp").forward(request, response);
}
#Override
public void onFailure(Throwable t) {
System.err.println("Operation failed with error: " + t);
}
Also see:
Firebase: Asynchronous Operations with Admin Java SDK
I am using Eclipse Kepler, Java, Jboss 7.1 and Mongodb.
When I am trying to send request from the Servlet to the class that works with the Mongodb I get an exception:
java.lang.ClassNotFoundException: org.bson.conversions.Bson
I am including the org.bson to the prohect by importing jar file named mongo-java-driver-3.0.3.jar.
The code is really basic and simple:
import java.net.UnknownHostException;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.*;
public class UserConnection {
private MongoClient client;
private MongoDatabase md;
private MongoCollection<Document>userCollection;
public void initUserConnection(){
client=new MongoClient();
md=client.getDatabase("eatFreeLottery");
userCollection=md.getCollection("users");
}
public void addClient(){
Document d=new Document();
d.append("name", "Sam");
this.initUserConnection();
userCollection.insertOne(d);
}
Servlet:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserConnection uc=new UserConnection();
uc.addClient();
}
Main class:
public class Test {
public static void main(String[] args) {
UserConnection uc=new UserConnection();
uc.addClient();
}
}
Both the servlet and the class work fine as long as they don't need to work together.
At first I thought that the problem was with my glassFish server so I switched to Jboss, but that got me nowhere.
Thanks!
OK.
Just copy paste the Jar file (mongo-java-driver-3.0.3.jar) under the web-inf/lib of the project and it works.
I have a folder that has only .java files. There are no .html, .jsp, .jsf etc. files only .java. I was told that this is a web application, but I have no idea on how to run it.
Here is a sample code from one of the .java files:
public List<String> generateHtml(String name, String css) {
List<String> html = new ArrayList<>();
html.add("<!DOCTYPE HTML><html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"" + css
+ "\"/></head><body>");
html.add("<div class='screen page_size " + name + "'>");
for (HtmlElement element : orderedElements) {
element.generateHtml(html);
}
html.add("</div>");
html.add("</body></html>");
return html;
}
I tried making a web project in eclipse and importing the files and running it, but no luck. It gives me a lot of errors with something to do with jetty. After installing jetty it still didnt work. Maybe I am installing it wrong. Anyone has any idea?
If you want to create a runnable war with jetty, have a look a the Embedded Jetty examples
You can call the generateHtml method from the servlet below.
package org.eclipse.jetty.embedded;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
public class MinimalServlets
{
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(HelloServlet.class, "/*");
server.start();
server.join();
}
#SuppressWarnings("serial")
public static class HelloServlet extends HttpServlet
{
#Override
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
//From here you can call the generateHtml method
response.getWriter().println("<h1>Hello from HelloServlet</h1>");
}
}
}
I am trying log4j. I got output for printing in console. But when I try using FileAppender it shows error. I am using google app engine.
This is my code.
package com.log4jtest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.*;
import org.apache.log4j.Appender;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
#SuppressWarnings("serial")
public class Log4jTestServlet extends HttpServlet
{
int count=0;
private static Logger log=Logger.getLogger(Log4jTestServlet.class);
public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException
{
resp.setContentType("text/plain");
/*BasicConfigurator.configure();*/
Appender app=new FileAppender(new SimpleLayout(),"hello.log");
log.setLevel(Level.TRACE);
BasicConfigurator.configure(app);
PrintWriter out=resp.getWriter();
//private static Logger log=Logger.getLogger(Log4jTestServlet.class);
String username="faisal";
String password="mohamed";
//int count=0;
count++;
out.println(count);
log.trace("TRACE");
log.debug("DEBUG");
log.info("INFO");
log.warn("WARN");
log.error("ERROR");
log.fatal("FATAl");
System.out.println("end line of the program");
resp.getWriter().println("Hello, world");
}
}
And this is my error..
Http error 500
java.io.FileOutputStream is a restricted class. Please see the Google App Engine developer's guide for more details.
now what I have to do
See answer to this: Does Google App Engine allow creation of files and folders on the server?
You cannot write files on GAE. Use console or Log API.
Is there a good way to get the logged in user count in a Java web application that is running in a cluster?
I wrote a simple HttpSessionListener with a static field, but I suppose this doesn't work in cluster. I can see there is a Spring Security solution, but I read in some forums that this is still not ok in cluster.
The product in which I have to implement this user count is trying to be application server independent, currently we support Tomcat, Weblogic and JBoss. At the moment I need a solution for Weblogic 10.3 clusters.
You can maintain the counter in database which will work in cluster env.
A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.
package com.hubberspot.javaee.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
#WebListener
public class OnlineUsersCounter implements HttpSessionListener {
private static int numberOfUsersOnline;
public OnlineUsersCounter() {
numberOfUsersOnline = 0;
}
public static int getNumberOfUsersOnline() {
return numberOfUsersOnline;
}
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Session created by Id : " + event.getSession().getId());
synchronized (this) {
numberOfUsersOnline++;
}
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("Session destroyed by Id : " + event.getSession().getId());
synchronized (this) {
numberOfUsersOnline--;
}
}
}
Running the below servlet on three different browsers will provide output as : (see fig below)
package com.hubberspot.javaee;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hubberspot.javaee.listener.OnlineUsersCounter;
// #WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// #WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.
#WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
, initParams = { #WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// sessionCreated method gets executed
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);
try {
out.println("<html>");
out.println("<body>");
out.println("<h2>Number of Users Online : "
+ OnlineUsersCounter.getNumberOfUsersOnline()
+ "</h2>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
Output of the program :
Eclipse Browser ->
Firefox Browser ->
Internet Explorer Browser ->
Console Output ->
For more: http://www.hubberspot.com/2013/09/how-to-determine-active-users-sessions.html