I have a problem with portlet. When i write in portlet.xml standart line
<portlet-class>com.liferay.util.bridges.mvc.MVCPortlet</portlet-class>
my jsp pages works fine. But when im add my portlet-class
<portlet-class>test.uploadport</portlet-class>
java code in jsp page dont execute. Im not talking about view.jsp im talk about pages which called from view.jsp.
I think problem in doView() from portlet
uploadport.java
package test;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import javax.portlet.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.portlet.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.util.*;
public class uploadport extends GenericPortlet {
private String error;
public void doView(RenderRequest req, RenderResponse res)
throws IOException, PortletException
{
WindowState state = req.getWindowState();
res.setContentType("text/html");
PortletSession session = req.getPortletSession(true);
PortletContext context = getPortletContext();
PortletRequestDispatcher rd;
rd = context.getRequestDispatcher("/view.jsp");
rd.include(req, res);
}
public void processAction(ActionRequest req, ActionResponse res)
throws IOException, PortletException
{
System.out.println("VASAY - PIROZJOK");
PortletSession session = req.getPortletSession(true);
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
List<FileItem> list=null;
String mifpath= "1";
String path = " ";
String mif = " ";
String from = "\\\\";
String to ="/";
String error="";
try{
list = portletFileUpload.parseRequest(req);
Iterator<FileItem> it = list.iterator();
//response.setContentType("text/html");
while ( it.hasNext() )
{
FileItem item = (FileItem) it.next();
File disk = new File("C:/uploaded_files/"+item.getName());
path = disk.toString();
String code = new String(path.substring(path.lastIndexOf("."), path.length()).getBytes("ISO-8859-1"),"utf-8");
if (code.equalsIgnoreCase(".zip"))
{
System.out.println("PIROZJOK");
mifpath=path;
mif = mifpath.replaceAll(from, to);
item.write(disk);
error=unzip.unpack(mif, "C:/uploaded_files");
}
else
{
error = "Выбранный файл не является архивом zip";
}
}
}
catch ( Exception e ) {
log( "Upload Error" , e);
}
}
private void log(String string, Exception e)
{
// TODO Auto-generated method stub
}
}
Why its heppening?
This problem was particullary solved.
1. need to use MVC portlet not Generic Portlet
2. delete doView() from portlet
That all. But thare is anther problems.
1. MVC portlet not a best choise.
2. How to send parametrs to view.jsp from portlet without doView()?
Related
I need to modify the code that read a text file, in a dynamically to read text or html files.
Now the code use only
response.setContentType("text/plain");
because the file is saved in text format. But I would like to save in html format to manage all tag and have a better view, but If I modify in
response.setContentType("text/html");
all file saved as text have a wrong viewer
My code is:
package uk.co.mycode.fax.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import uk.co.mycode.fax.dao.mycodeFaxDAO;
import uk.co.mycode.fax.domain.Image;
import uk.co.morpheus.logging.Logger;
public class FaxImageRequest
extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); }
public void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getParameter("U");
if (url == null || url.length() < 1) {
url = request.getParameter("URL");
}
Logger.log(4, getClass().getName(), "<**** Entered FaxImageRequest (" + url + ") ****>");
try {
Cookie[] cookies = request.getCookies();
String userId = "";
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("IMPS3IAuserid")) {
userId = cookies[i].getValue();
break;
}
}
}
if (userId.length() < 1) {
userId = "NOT LOGGED ON";
}
mycodeFaxDAO dao = mycodeFaxDAO.getInstance();
Image image = dao.getImage(url);
Logger.log(4, getClass().getName(), "Image: " + image);
if (image != null) {
ServletOutputStream out = response.getOutputStream();
if (image.type.toLowerCase().startsWith("f")) {
response.setContentType("image/tiff");
} else {
//----------------------------------------------------------------------------
response.setContentType("text/plain");
//----------------------------------------------------------------------------
}
for (int i = 0; i < image.bytes.length; ) { out.write(image.bytes, i, (image.bytes.length - i > 4096) ? 4096 : (image.bytes.length - i)); i += 4096; }
dao.updateImageArchive(userId, request.getParameter("U"));
} else {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<HTML>");
pw.println("<BODY>");
pw.println("<B>No image found</B>");
pw.println("</BODY>");
pw.println("</HTML>");
pw.close();
}
} catch (Throwable th) {
Logger.log(1, getClass().getName(), "Error during image read or update:" + th.getMessage());
th.printStackTrace();
}
Logger.log(4, getClass().getName(), "<**** Finished FaxImageRequest ****>");
}
}
I tried to write this:
if (response.getContentType() == null) {
response.setContentType("text/html");
} else {
response.setContentType("text/plain");
}
but it is always null.
Thanks for the support.
The correct answer, if I may bring up your "hosting platform" - is that such settings are usually changed in the hosting platform. I have hosted three different web domains with GCS (Google Cloud Server) because it is (mostly) free.
In Google Cloud, when you save a file, generally it will recognize what type of file you have save (Content-Type) based on the file's extension - '.txt' or '.html'. The Content-Type setting can be changed in Google's bucket file explorer GUI using a mouse. It may also be changed manually at the command line using the GSUTIL command line program.
You may make calls to GSUTIL from Java by using Java's shell execution libraries (the Java Standard library routines for calling UNIX Shell commands). This is what I do...
... But you may even download Google's Java Jar files to access GCS and make Java based calls to GCS for doing things like changing the content type of a storage bucket file....
If you were using.MSFT Azure, or GoDaddy or something else this would be different.
This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Connect Java to a MySQL database
(14 answers)
Closed 3 years ago.
I followed a tutorial online and there were some mistakes here and there but I understood the ideas behind it and the mindset. I have a school project on developing a Web App and I decided to do it in Java EE (since I was comfortable with Java).
My source code consists of 5 packages (Beans, Connection, Filter, Servlets and Utilities).
The problem consists of the JDBC Filter, as told in the title. It checks that everywhere on the website, I'm still connected to the MySQL Database. However, whenever it goes on anything of a localhost:8080/*, an SQL Exception is enabled, complaining about the Driver. Except this error doesn't arrive when opening files directly in the path, instead of using URL Patterns.
So I decided to do some investigating. Checked the console and climbed up the errors. It complained about the ConnectionUtils class, specifically the getMySQLConnection method, which comes from the MySQLConnUtils class.
The problem is that when I try the method itself in the mainmethod, it works !
package Connection;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionUtils {
public static Connection getMyConnection() throws SQLException, ClassNotFoundException{
return MySQLConnUtils.getMySQLConnection();
}
public static void closeQuietly(Connection conn)
{
try{
conn.close();
}catch(Exception e){
}
}
public static void rollbackQuietly(Connection conn){
try{
conn.rollback();
}catch(Exception e){
}
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("Get connection...");
Connection conn = ConnectionUtils.getMyConnection();
System.out.println("Get connection " + conn);
System.out.println("Done!");
}
}
package Connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnUtils {
public static Connection getMySQLConnection() throws SQLException{
String userName = "username";
String password="pwd";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("CLASS NOT FOUND");
}
String connectionURL = "jdbc:mysql://localhost:3306/flytogo";
Connection conn = DriverManager.getConnection(connectionURL,userName,password);
return conn;
}
}
Here's the filter proving that the url-pattern it applies to is "/*" :
package Filter;
import java.io.IOException;
import java.sql.Connection;
import java.util.Collection;
import java.util.Map;
import Connection.ConnectionUtils;
import Utils.MyUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
#WebFilter(filterName = "jdbcFilter", urlPatterns = { "/*" })
public class JDBCFilter implements Filter {
public JDBCFilter() {
}
#Override
public void init(FilterConfig fConfig) throws ServletException {
}
#Override
public void destroy() {
}
// Check the target of the request is a servlet?
private boolean needJDBC(HttpServletRequest request) {
System.out.println("JDBC Filter");
//
// Servlet Url-pattern: /spath/*
//
// => /spath
String servletPath = request.getServletPath();
// => /abc/mnp
String pathInfo = request.getPathInfo();
String urlPattern = servletPath;
if (pathInfo != null) {
// => /spath/*
urlPattern = servletPath + "/*";
}
// Key: servletName.
// Value: ServletRegistration
Map<String, ? extends ServletRegistration> servletRegistrations = request.getServletContext()
.getServletRegistrations();
// Collection of all servlet in your Webapp.
Collection<? extends ServletRegistration> values = servletRegistrations.values();
for (ServletRegistration sr : values) {
Collection<String> mappings = sr.getMappings();
if (mappings.contains(urlPattern)) {
return true;
}
}
return false;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
// Only open connections for the special requests.
// (For example, the path to the servlet, JSP, ..)
//
// Avoid open connection for commons request.
// (For example: image, css, javascript,... )
//
if (this.needJDBC(req)) {
System.out.println("Open Connection for: " + req.getServletPath());
Connection conn = null;
try {
// Create a Connection.
conn = ConnectionUtils.getMyConnection();
// Set outo commit to false.
conn.setAutoCommit(false);
// Store Connection object in attribute of request.
MyUtils.storeConnection(request, conn);
// Allow request to go forward
// (Go to the next filter or target)
chain.doFilter(request, response);
// Invoke the commit() method to complete the transaction with the DB.
conn.commit();
} catch (Exception e) {
e.printStackTrace();
ConnectionUtils.rollbackQuietly(conn);
throw new ServletException();
} finally {
ConnectionUtils.closeQuietly(conn);
}
}
// With commons requests (images, css, html, ..)
// No need to open the connection.
else {
// Allow request to go forward
// (Go to the next filter or target)
chain.doFilter(request, response);
}
}
}
Anyways, thanks in advance to anyone who would know what could be the source of mistakes or error.
Here is my current servlet code. This is where I will get the image from the database.
newServlet.java
package LAWS_SERVLETS;
import LAWS_DAOS.LReceiptsDAO;
import LAWS_ENTITIES.Lawyer_Receipt;
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;
/**
*
* #author Meryl
*/
#WebServlet(name = "newServlet", urlPatterns = {"/newServlet"})
public class newServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
LReceiptsDAO lrDAO = new LReceiptsDAO();
int imageId = Integer.parseInt(request.getParameter("id"));
// Check if ID is supplied to the request.
if (imageId == 0) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
byte[] image = lrDAO.getReceiptFile(imageId);
// Check if image is actually retrieved from database.
if (image == null) {
// Do your thing if the image does not exist in database.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Init servlet response.
response.reset();
response.setContentType(image.getContentType());
response.setContentLength(image.getContent().length);
// Write image content to response.
response.getOutputStream().write(image.getContent());
}
}
LReceiptsDAO
public byte[] getReceiptFile(int id){
byte[] l = null;
try {
DBConnectionFactory myFactory = DBConnectionFactory.getInstance();
Connection conn = myFactory.getConnection();
PreparedStatement pstmt = conn.prepareStatement("SELECT receipt_filepath FROM lawyer_receipts"
+ "where lawyerreceipt_id = ? ");
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
l = rs.getBytes("receipt_filepath");
}
conn.close();
return l;
} catch (SQLException ex) {
Logger.getLogger(LReceiptsDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
I got the servlet code from this link but it seems that I get an error when I set the init servlet response part.
I'm very sorry for asking this question. It's my first time trying to get image blobs from the database and getting it via a DAO and a servlet and so far, I only saw codes that included the java codes in a jsp.
I appreciate the help. Thank you!
try replace
response.setContentType(image.getContentType());
response.setContentLength(image.getContent().length);
response.getOutputStream().write(image.getContent());
to
response.setContentType("image/*");
response.setContentLength(image.length);
response.getOutputStream().write(image);
The reason the getContentType() and getContent() methods aren't found is because they don't exist. The type of the variable image is byte[] - an array of primitive bytes - and arrays don't have those methods. That code shouldn't actually compile.
The link where you got that code has the type of image variable as com.example.model.Image (a class which has been defined in that example and has those methods) not byte[].
Incidentally, the code in your example is selecting a field called receipt_filepath which suggests that the field stores the path to the image on disk, not a blob. If so, you should resolve that path and read the file from disk (as is done in the example you linked to).
If it is a blob, then you really should be storing the content type of the image in the database, too. In that case, you can do something like this:
PreparedStatement pstmt = conn.prepareStatement("SELECT image_blob_field_name, image_content_type_field_name FROM lawyer_receipts"
+ "where lawyerreceipt_id = ? ");
...
byte[] image = rs.getBytes(1);
String contentType = rs.getString(2);
...
Then later:
response.setContentType(contentType);
response.setContentLength(image.length);
response.getOutputStream().write(image);
I'm trying to make a servlet on Jetty that overrides a file extension but that still needs to read the file being accessed.
I've been trying with resources but I could achieve nothing yet. I've tryed this code so far and, as you'll see, the resources are there but I somehow can't access them:
package valarionch.lab0.webapp.todo;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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;
#SuppressWarnings("serial")
#WebServlet(urlPatterns = { "*.ToDo" })
public class ToDoHandler extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
String s = req.getParameter("s");
boolean small = (s != null && s.equals("1"));
PrintWriter out = resp.getWriter();
if (!small) {
out.println("<html><head><title>ToDo list</title></head>"
+ "<body>");
}
for (String res : getServletContext().getResourcePaths("/")) {
System.out.println("Resource: " + res);
System.out.println("ResourceURL: " + getServletContext().getResource(res));
System.out.println("ResourceStream: " + getServletContext().getResourceAsStream(res));
}
InputStream input = getServletContext().getResourceAsStream(req.getRequestURI());
System.out.println(input);
ToDoFormatter.parse(input, out, req.getParameter("q"));
if (!small) {
out.println("</body></html>");
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
this code prints this:
Resource: /META-INF/
ResourceURL: null
ResourceStream: null
Resource: /WEB-INF/
ResourceURL: null
ResourceStream: null
Resource: /index.html
ResourceURL: null
ResourceStream: null
Resource: /ToDoList.ToDo
ResourceURL: null
ResourceStream: null
null
I tryed with the next code too but also didn't worked:
getClass().getClassLoader().getResource(".").toString()+"../.."+req.getRequestURI()
so getClass().getClassLoader().getResource(".").toString() goes to WEB-INF/classess and +"../.."+req.getRequestURI() picks the actual file.
Am I missing something about how resources work? Is there another way to read the file?
You can use getServletContext().getRealPath() for such task. Let's imagine that you have the file myText.txt in the webapps folder:
#SuppressWarnings("serial")
#WebServlet(urlPatterns = { "*.ToDo" })
public class UseGetRealPath extends HttpServlet {
public void doGet( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException {
String todoFile = getServletContext().getRealPath("/myText.txt");
FileReader fr = new FileReader( todoFile );
for( int c = fr.read(); c != -1; c = fr.read() ) {
System.out.print( (char) c );
}
fr.close();
res.getWriter().println( "check the console!" );
}
}
The code will open the file and dump its content in the console.
I searched on net, found similar issues. As I'm newbie to LDAP, had to reach out for help.
Right now code brings all the groups for a user. When user1 logins, it brings Group A.
New Requirement is:
If Group A is member of Group B, we need to retrieve Group B as well along with Group A.
I'm trying to achieve this by tweaking query. I read about some matching rules OID 1.2.840.113556.1.4.1941 & LDAP_MATCHING_RULE_IN_CHAIN. But couldn't figure out how to implement in my code.
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
public abstract class SAPSecurityFilter implements Filter {
protected abstract SAPPrincipal buildGroups(SAPPrincipal principal, NamingEnumeration<SearchResult> results) throws NamingException;
private static final String SECURE_ENTERPRISE_DIRECTORY = "ldaps://ldap.abc.com:636/o=abc.com";
private static final String PRINCIPAL_NAME = "SAPPrincipal";
private static final String ENTERPRISE_DIRECTORY = "ldap://ldap.abc.com:389/o=abc.com";
private static final String USER_KEY = "HTTP_SM_USER";
private static final String BASE = "ou=Groups";
private static final String GROUP_QUERY = "(member=uid=%s,ou=People,o=abc.com)";
private final CacheManager cacheManager;
private List<String> excludeUrlPatterns = new ArrayList<String>();
public SAPSecurityFilter() {
// Setup Cache for principals
// cache Manager
URL url = getClass().getResource("/data-cache.xml");
cacheManager = new CacheManager(url);
}
public void destroy() {
// TODO Auto-generated method stub
}
/**
* doFilter
* <p/>
* Read the request headers for the HTTP_SM_USER value
* This value is the users email address.
* Using the email address lookup the users values in Enterprise directory
* Populate the principal and place it in request scope.
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//SAPt the request into HttpServletRequest
String path = ((HttpServletRequest) request).getPathInfo();
if (patternExcluded(path) || "OPTIONS".equalsIgnoreSAPe(((HttpServletRequest) request).getMethod())) {
chain.doFilter(request, response);
} else {
String smUser = ((HttpServletRequest) request).getRemoteUser();
HttpSession session = ((HttpServletRequest) request).getSession();
if (smUser == null) throw new ServletException("USER TOKEN MISSING");
// use the smUser to get the data needed to build a principal
LdapContext ctx = null;
// build SAP principal //
SAPPrincipal principal = new SAPPrincipal();
principal.setName(smUser);
//Cache cache = cacheManager.getCache("principalCache");
//Element element = cache.get(smUser);
// Cache miss for user
if (session.getAttribute(PRINCIPAL_NAME) == null) {
try {
ctx = getLdapContext(smUser);
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrs = {"cn"};
constraints.setReturningAttributes(attrs);
String filter = String.format(GROUP_QUERY, smUser);
NamingEnumeration<SearchResult> results = ctx.search(BASE, filter, constraints);
principal = buildGroups(principal, results);
//cache.put(new Element(smUser, principal));
session.setAttribute(PRINCIPAL_NAME, principal);
} catch (NamingException ne) {
throw new ServletException(ne);
} finally {
try {
if (ctx != null) ctx.close();
} catch (NamingException ne) {
// swallow on purpose
}
}
// Cache Hit for user
} else {
principal = (SAPPrincipal) session.getAttribute(PRINCIPAL_NAME);
}
// add principal to securityContext and SAPContext//
SAPContext.setPrincipal(principal);
chain.doFilter(new SecurityRequestWrapper(principal, (HttpServletRequest) request), response);
}
}
Your filter needs to be something like:
(member:1.2.840.113556.1.4.1941:=(CN=UserName,CN=Users,DC=YOURDOMAIN,DC=NET))
form:http://ldapwiki.willeke.com/wiki/Active%20Directory%20User%20Related%20Searches
-jim