Servlet/JSP: "Access Denied" error when trying to add an image [duplicate] - eclipse

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 1 year ago.
I'm having a problem with adding the image in jsp/Servlet. I get the following error:
C:\Users\palex\eclipse-workspace\AgendaJSP_Path\img (Access Denied)
I have windows 10; I did not understand if it is an operating system problem or other.
I put the structure of the project
and the code where I add an image:
package pack_person;
import java.io.File;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class addpersonimage
*/
#WebServlet("/addpersonimage")
#MultipartConfig(fileSizeThreshold=1024*1024*2,
maxFileSize=1024*1024*10,
maxRequestSize=1024*1024*50)
public class addpersonimage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public addpersonimage() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name=request.getParameter("name");
Part part=request.getPart("file");
String namefile=extractFileName(part);
String path="C:\\Users\\palex\\eclipse-workspace\\AgendaJSP_Path\\img" + File.separator + namefile;
File fileSaveDir= new File(path);
part.write(path + File.separator);
String message=null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/persons","root","pssw");
PreparedStatement pst = con.prepareStatement("insert into persons values (?,?,?)");
pst.setString(1, name);
pst.setString(2, namefile);
pst.setString(3, path);
int row = pst.executeUpdate();
if(row>0) {
message= "Successfully";
}
} catch (Exception e) {
out.println(e);
}
request.setAttribute("Message", message);
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("namefile")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}

So you're trying to write file to the path
C:\Users\palex\eclipse-workspace\AgendaJSP_Path\img
and you get "access denied"
What are file access rights assigned to this path?
Does the user account the server is running as have write privilege
to this path?
What server are you running the servlet in?
Some servers, example Tomcat Apache, are sandboxed and can only
write to paths allowed by the sandbox. Again for Tomcat you need
to write your file to one of these paths or add your path to
tomcat9.service which on Ubuntu is in /usr/lib/systemd/system
(where 9 is the current version number of tomcat)
So check path permissions and check server sandbox.

Read the servlet specification. This is a good thing. It's there to prevent hackers from using your website to infiltrate you computer.
The specification also has the information you need to know where you can store your images, and how you can override that default.

Related

How do I get all the list of assets present in the AEM DAM

We have assets api to fetch the list, but for that we need to provide AEM user credentials.
Do we have any interface, to fetch all the assets list from the dam just the way get all the pages using page manager.
For this, you can use JCR's QueryManager API and your specific query in conjunction.
Below is a sample servlet which lists all the Assets below path - /content/dam/we-retail/en/features
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;
import javax.servlet.Servlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Component(immediate = true, service = Servlet.class, property = { "sling.servlet.methods=" + HttpConstants.METHOD_GET,
"sling.servlet.paths=" + "/bin/learning/assetlister" })
public class AssetListerServlet extends SlingSafeMethodsServlet {
// Generated serialVersionUID
private static final long serialVersionUID = 7762806638577908286L;
// Default logger
private final Logger log = LoggerFactory.getLogger(this.getClass());
// Instance of ResourceResolver
private ResourceResolver resourceResolver;
// JCR Session instance
private Session session;
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
try {
// Getting the ResourceResolver from the current request
resourceResolver = request.getResourceResolver();
// Getting the session instance by adapting ResourceResolver
session = resourceResolver.adaptTo(Session.class);
QueryManager queryManager = session.getWorkspace().getQueryManager();
String queryString = "SELECT * FROM [dam:Asset] AS asset WHERE ISDESCENDANTNODE(asset ,'/content/dam/we-retail/en/features')";
Query query = queryManager.createQuery(queryString, "JCR-SQL2");
QueryResult queryResult = query.execute();
response.getWriter().println("--------------Result-------------");
RowIterator rowIterator = queryResult.getRows();
while (rowIterator.hasNext()) {
Row row = rowIterator.nextRow();
response.getWriter().println(row.toString());
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
}
Similary using your specific requirement, you can use this logic in a component, service etc. I hope this helps.
If you are looking for a python solution, here is a python tool that I created to connect to AEM DAM and perform most DAM operations, including listing of all DAM assets or assets under a given path

doPost Method of AEM SlingServlet can't be called - sling resolver defaulting to GET

I am working with AEM version 6.2 and I need to create a servlet that connects to a backend system and call a restful service. This has to done using the doPost method and not the doGet for security reasons. I have been able to register the Sling based servlet within AEM however, I have not been able to call POST a request to the servlet. I have registered the using the #SlingServlet annotation using resourceTypes and Paths but still the doPost is not being called only doGet. I know the default call is to doGet from the server but I have specified the method as POST.
package com.dash.dev.servlets.core.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.jcr.api.SlingRepository;
#SlingServlet(name="A Servlet2",
resourceTypes = "/apps/DashServletApp/components/structure/page",
paths = "/bin/case/enrol2",
methods = "POST",
metatype=true)
public class AServletByPath extends SlingSafeMethodsServlet {
private static final long serialVersionUID = 7175649210039853979L;
#Reference
private SlingRepository repository;
public void bindRepository(SlingRepository repository){
this.repository = repository;
}
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
HttpSession session = request.getSession();
String sessionID = session.getId();
System.out.println(sessionID);
PrintWriter out = response.getWriter();
out.println(sessionID + "POST Method called");
out.flush();
out.close();
}
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
HttpSession session = request.getSession();
String sessionID = session.getId();
System.out.println(sessionID);
PrintWriter out = response.getWriter();
out.println(sessionID + "POST Method called");
out.flush();
out.close();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
finally
{
//Important: Close the connect
httpClient.getConnectionManager().shutdown();
}
}
}
I have read the Sling documnetation and took particular note of:
The request methods supported by the servlet. The property value must either be a single String, an array of Strings or a Vector of Strings. This property is only considered for the registration with sling.servlet.resourceTypes. If this property is missing, the value defaults to GET and HEAD, regardless of which methods are actually implemented/handled by the servlet.
and when I look at the sling console I see only GET and HEAD registered. What do I need to do to be able to make the doPost available???
thank you!
As the naeme suggests the SlingSafeMethodsServlet is supposed to be used only for "Safe" requests, which are GET, HEAD, OPTIONS etc. By default this servlet doesn't support POST, PUT and DELETE.
Quoting the docs
This base class is intended for applications where data is only read.
As such, this servlet by itself does not support the POST, PUT and
DELETE methods. Extensions of this class should either overwrite any
of the doXXX methods of this class or add support for other read-only
methods only.
Applications wishing to support data modification should
rather use or extend the SlingAllMethodsServlet which also contains
support for the POST, PUT and DELETE methods. This latter class should
also be overwritten to add support for HTTP methods modifying data.
You can extend the SlingAllMethodsServlet to cater to your POST requests.

How to resolve java.net.SocketException Permission Denied error?

I have already included the Internet Permissions in the andoird manifest page, still the error seems to persist. I am also recieveing an unknown host excption in the similar code. Kindly guide me through! Ty! :)
package name.id;
import android.app.Activity;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import org.ksoap2.*;
import org.ksoap2.serialization.*;
import org.ksoap2.transport.*;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FirstPage extends Activity implements android.view.View.OnClickListener
{
/** Called when the activity is first created. */
TextView tv;
Button bu;
EditText et;
private static final String SOAP_ACTION="http://lthed.com/GetFullNamefromUserID";
private static final String METHOD_NAME="GetFullNamefromUserID";
private static final String NAMESPACE="http://lthed.com";
private static final String URL="http://vpwdvws09/services/DirectoryService.asmx";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText) findViewById(R.id.editText1);
tv=(TextView) findViewById(R.id.textView2);
bu=(Button) findViewById(R.id.button1);
bu.setOnClickListener((android.view.View.OnClickListener) this);
tv.setText("");
}
public void onClick(View v)
{
// creating the soap request and all its paramaters
SoapObject request= new SoapObject(NAMESPACE, METHOD_NAME);
//request.addProperty("ID","89385815");// hardcoding some random value
//we can also take in a value in a var and pass it there
//set soap envelope,set to dotnet and set output
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet=true;
soapEnvelope.setOutputSoapObject(request);
HttpTransportSE obj = new HttpTransportSE(URL);
//to make call to server
try
{
obj.call(SOAP_ACTION,soapEnvelope);// in out parameter
SoapPrimitive resultString=(SoapPrimitive)soapEnvelope.getResponse();
//soapObject or soapString
tv.setText("Status : " + resultString);
}
catch(Exception e)
{
tv.setText("Error : " + e.toString());
//e.printStackTrace();
}
}
}
Have you added Internet permission to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
The error was being thrown because of an error in the URL. The URL needed my IP address to function properly rather than the URL i was providing because that the webservice was not able to understand.
Depending on what KSOAP2 version you are using error may vary.
Its recommend that use KSOAP2 v3+ lib.
Simply use following code to override...
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
and also use...

Reading xls file in gwt

I am looking to read xls file using the gwt RPC and when I am using the code which excecuted fine in normal file it is unable to load the file and giving me null pointer exception.
Following is the code
{
{
import com.arosys.readExcel.ReadXLSX;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.Preview.client.GWTReadXL;
import java.io.InputStream;
import com.arosys.customexception.FileNotFoundException;
import com.arosys.logger.LoggerFactory;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author Amandeep
*/
public class GWTReadXLImpl extends RemoteServiceServlet implements GWTReadXL
{
private String fileName;
private String[] Header=null;
private String[] RowData=null;
private int sheetindex;
private String sheetname;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private static Logger logger=null;
public void loadXlsxFile() throws Exception
{
logger.info("inside loadxlsxfile:::"+fileName);
InputStream resourceAsStream =ClassLoader.getSystemClassLoader().getSystemResourceAsStream("c:\\test2.xlsx");
logger.info("resourceAsStream-"+resourceAsStream);
if(resourceAsStream==null)
throw new FileNotFoundException("unable to locate give file");
else
{
try
{
workbook = new XSSFWorkbook(resourceAsStream);
sheet = workbook.getSheetAt(sheetindex);
}
catch (Exception ex)
{
logger.error(ex.getMessage());
}
}
}// end loadxlsxFile
public String getNumberOfColumns() throws Exception
{
int NO_OF_Column=0; XSSFCell cell = null;
loadXlsxFile();
Iterator rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator cellIter = firstRow.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
return NO_OF_Column+"";
}
}
}
I am calling it in client program by this code:
final AsyncCallback<String> callback1 = new AsyncCallback<String>() {
public void onSuccess(String result) {
RootPanel.get().add(new Label("In success"));
if(result==null)
{
RootPanel.get().add(new Label("result is null"));
}
RootPanel.get().add(new Label("result is"+result));
}
public void onFailure(Throwable caught) {
RootPanel.get().add(new Label("In Failure"+caught));
}
};
try{
getService().getNumberOfColumns(callback1);
}catch(Exception e){}
}
Pls tell me how can I resolve this issue as the code runs fine when run through the normal java file.
Why are using using the system classloader, rather than the normal one?
But, If you still want to use then look at this..
As you are using like a web application. In that case, you need to use the ClassLoader which is obtained as follows:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
This one has access to the all classpath paths tied to the webapplication in question and you're not anymore dependent on which parent classloader (a webapp has more than one!) has loaded your class.
Then, on this classloader, you need to just call getResourceAsStream() to get a classpath resource as stream, not the getSystemResourceAsStream() which is dependent on how the webapplication is started. You don't want to be dependent on that as well since you have no control over it at external hosting:
InputStream input = classLoader.getResourceAsStream("filename.extension");
The location of file should in your CLASSPATH.

Unable to find the org.drools.builder.KnowledgeType drrols class

While am trying to execute the Helloword process example from the section 2.3 in
https://hudson.jboss.org/hudson/job/drools/lastSuccessfulBuild/artifact/trunk/target/docs/drools-flow/html_single/index.html#d4e24 site am unable to find the below mentioned class.
org.drools.builder.KnowledgeType
Could anyone please tell from which package can i get this class?
Thanks!
That part of the documentation seems a little outdated. You should use ResourceType. I've updated the docs with the following code fragment instead (should also appear on the link you're using once the build succeeds):
package com.sample;
import org.drools.KnowledgeBase;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;
/**
* This is a sample file to launch a process.
*/
public class ProcessTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
// start a new process instance
ksession.startProcess("com.sample.ruleflow");
logger.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
private static KnowledgeBase readKnowledgeBase() throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("ruleflow.rf"), ResourceType.DRF);
return kbuilder.newKnowledgeBase();
}
}