Unable to write log file using Log4j on Google App Engine - java

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.

Related

Web servlet error by using html code in get method

I am new to web programming. I am using this simple code in my get method
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html><head><title>Guest Book</title></head><body>" );
out.println(" </body></html> ");
I am getting the below error while clicking on run on server
enter image description here
Note: When i removed the html code, the servlet is working fine.Is it my Html code problem or any tomcat sevrver issue.
The servlet is in my package cs3220homework and servlet name is #WebServlet("/MainFolder").
I tried everywhere to look for the issue and i was not able to find it.If its duplicate please let me know.
Thanks for your reply
Harminder
Its working fine. App is named Test and Servlet class is also named Test. This is the url http://localhost:8080/Test/Test
package foo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html><head><title>Guest Book</title></head><body>" );
out.println(" </body></html> ");
}
}

RemoteApi calls from servlet not loading in local app engine app

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()

Verify header before request receive in tomcat

I need verify header before receive the request. I found that tomcat valve can help in it. I follow these steps but valve is not called:
make a maven project and do this code in it.
package cz.ValveTest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
public class ProcessingValve extends ValveBase {
private static final Logger logger = Logger.getLogger(ProcessingValve.class.getName());
#Override
public void invoke(Request request, Response response) throws IOException,
ServletException {
HttpServletRequest httpServletRequest = request.getRequest();
Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
logger.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
logger.log(Level.INFO, "Header --> {0} Value --> {1}", new Object[]{header, httpServletRequest.getHeader(header)});
}
getNext().invoke(request, response);
}
}
make jar and put jar inside tomcat/lib folder
add this line in server.xml
<valve className="cz.ValveTest.ProcessingValve"/>
restart tomcat.
Now I hit my web service with header:
Expect : 100-continue
but using this configuration and code valve is not called on http hit.If any one knew why tomcat valve is not called please help.
The tags in server.xml are case sensitive.
So try this :
<Valve className="cz.ValveTest.ProcessingValve"/>

mongodb on server (jboss and glassfish) doesn't work

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.

How to run a java web application?

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>");
}
}
}

Categories