Serving WebLogic LogFiles as Jersey Resource
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
@Path("/logs")
public class LogResource {
private final static Logger LOGGER = Logger.getLogger(LogResource.class.getName());
@GET
@Produces(MediaType.TEXT_HTML)
public Response list() {
StringBuilder sb = new StringBuilder("<html>\n<head>\n<title>LogViewerListing</title>\n</head>\n<body>\n<ul>\n");
String path = getLogDir();
if (path != null) {
File logFolder = new File(path);
if (logFolder.exists() && logFolder.canRead()) {
for (File f : logFolder.listFiles()) {
if (!f.getName().startsWith(".") && f.length() > 0L) {
sb.append("<li>").append("<a href=\"").append(addLogLink(f.getName())).append("\">").append(f.getName()).append("</a>").append("</li>\n");
}
}
}
}
sb.append("</ul>\n</body>\n</html>");
return Response.ok(sb.toString()).build();
}
@GET
@Path("/{logName}")
public Response show(@PathParam("logName") String logName) {
String path = getLogDir();
if (path != null && logName != null) {
String logFilePath = path + File.separator + logName;
File logFile = new File(logFilePath);
if (logFile.exists()) {
Response.ResponseBuilder builder = Response.ok(logFile)
.header("Content-Disposition", "attachment; filename=" + logFile.getName())
.header("X-File-Name", logFile.getName())
.header("X-File-Size", logFile.length())
.header("X-File-ContentType", MediaType.TEXT_PLAIN);
return builder.build();
}
}
return Response.status(Response.Status.NOT_FOUND).build();
}
private String addLogLink(String logName) {
UriBuilder builder = UriBuilder.fromPath("/logs/{logName}");
try {
return builder.build(URLEncoder.encode(logName, "UTF-8")).toString();
} catch (UnsupportedEncodingException ex) {
return "";
}
}
private static String getLogDir() {
String weblogicHome = System.getProperty("weblogic.home");
String weblogicName = System.getProperty("weblogic.Name");
String path = null;
String userDir = System.getProperty("user.dir");
if (weblogicHome != null && weblogicName != null) {
path = userDir + File.separator + "servers" + File.separator + weblogicName + File.separator + "logs";
} else {
LOGGER.log(Level.WARNING, "LogFile not availibe. Maybe you do not run on Weblogic? user.dir is {0}", System.getProperty("user.dir"));
}
return path;
}
}
Written by Philipp Haußleiter
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Logs
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#