while working on interceptor with SpringMVC I'm getting NPE. I am using log4j.properties and here is the following code of interceptor
ThreadLocal<StopWatch> stopWatchLocal = new ThreadLocal<>();
Logger logger = Logger.getLogger(this.getClass());
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
Exception exception) throws Exception {
StopWatch stopWatch = stopWatchLocal.get();
stopWatch.stop();//Line 24
logger.info("Total time taken for processing: " + stopWatch.getTotalTimeMillis() + " ms");
stopWatchLocal.set(null);
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
ModelAndView modelAndView) throws Exception {
logger.info("Request processing ended on " + getCurrentTime());
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
StopWatch stopWatch = new StopWatch(object.toString());
stopWatch.start(object.toString());
stopWatchLocal.set(stopWatch);
logger.info("Accessing URL path: " + getURLPath(request));
logger.info("Request processing started on: " + getCurrentTime());
return true;
}
private String getCurrentTime() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy 'at' hh:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return formatter.format(calendar.getTime());
}
private String getURLPath(HttpServletRequest request) {
String currentPath = request.getRequestURI();
String queryString = request.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
return currentPath + queryString;
}
this is the log
j
ava.lang.NullPointerException
at com.webstore.interceptor.PerformanceMontiorInterceptor.afterCompletion(PerformanceMontiorInterceptor.java:24)
at org.springframework.web.servlet.HandlerExecutionChain.triggerAfterCompletion(HandlerExecutionChain.java:167)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1023)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
interceptor in dispatcherServlet
<mvc:interceptors>
<bean class="com.package.InterceptorClass"></bean>
</mvc:interceptors>
Am I doing something wrong ?
Please Help, is my configuration is broken because I'm not able to get the answer why I am getting NPE
Related
I am trying to make a post request which is supposed to return a json, but for some reason it returns 500 something went wrong.
'''
public void templatRequestPayment(String token, String url, String key, String body)
throws RestClientException, URISyntaxException, IOException {
URI uri = new URI(url);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", token);
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("key", key);
HttpEntity<String> entity = new HttpEntity<String>(body, headers);
RestTemplate template = new RestTemplate(getConverter());
try {
ResponseEntity<JsonNode> res = template.exchange(uri, HttpMethod.POST, entity,
JsonNode.class);
String tok = res.getBody().toString();
System.out.println(tok);
} catch (HttpStatusCodeException e) {
ResponseEntity<String> st =
ResponseEntity.status(e.getStatusCode()).headers(e.getResponseHeaders())
.body(e.getResponseBodyAsString());
System.out.println(st.getHeaders() + "-- /n" + st.getBody());
}
}
protected List<HttpMessageConverter< ?>> getConverter() {
List<HttpMessageConverter< ?>> converters = Lists.newArrayList();
converters.add(new MappingJackson2HttpMessageConverter());
return converters;
}
'''
I need to create and download the CSV file, and for this I am using OpenCSV with Spring MVC, the data need to be written is holding by my class name CsvDataDto.
public class CsvDataDto {
private String fileName;
List<String> header=new ArrayList<>();;
private String heading;
List<List<Object>> data=new ArrayList<>();
//getters and setters
}
The main data contains file header (eg: userid,fname,lastname,rollno) and actual data (eg. 1,101,john,doe,1001).
File header is hold by List<String> header
and The file data is hold by List<List<Object>> data
and here is the controller method which set all the required data
#RequestMapping(value = "/export_data")
public void downloadDataInCsv(
#RequestParam("type") String type,
#RequestParam("tID") String tableId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (type.equals("csv")) {
CsvDataDto dataDTO = new CsvDataDto();
dataDTO.setFileName("Table_Data");
dataDTO.getHeader().add("User Id");
dataDTO.getHeader().add("First Name");
dataDTO.getHeader().add("Last Name");
dataDTO.getHeader().add("Roll No");
dataDTO.getHeader().add("Email ID");
dataDTO.getHeader().add("Gender");
List<UserInfo> list = userInfoDao.findById(tableId);
for (UserInfo infoList : list) {
List<Object> newList = new ArrayList<>();
newList.add(infoList.getUserId());
newList.add(infoList.getFirstName());
newList.add(infoList.getLastName());
newList.add(infoList.getRollNo());
newList.add(infoList.getEmail());
newList.add(infoList.getGender());
dataDTO.getData().add(newList);
}
ExportCsvUtil.downloadCsv(request, response, dataDTO);
}
Now the downloadCsv() implementation
public static void downloadCsv(HttpServletRequest request, HttpServletResponse response, CsvDataDto csvDataDto) throws IOException {
List<String[]> records = new ArrayList<>();
String csvFileName = csvDataDto.getFileName();
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=" + csvDataDto.getFileName() + ".csv");
response.setContentType("text/csv");
response.setHeader(headerKey, headerValue);
CSVWriter writer = new CSVWriter(new FileWriter(csvFileName));
String[] headerArr = new String[csvDataDto.getHeader().size()];
headerArr = csvDataDto.getHeader().toArray(headerArr);
records.add(headerArr);
for (List<Object> objList : csvDataDto.getData()) {
System.out.println("object list:" + objList);
String[] fileData = new String[objList.size()];
fileData = objList.toArray(fileData);
records.add(fileData);
}
writer.writeAll(records);
writer.close();
System.out.println(writer);
}
}
I am stuck here,as I explore tons of examples where the instructors simple pass the data in writeNext() method.
writer.writeNext(csvDataDto);
But I know that it will not work as i expected.File is successfully downloaded but blank, no data is write over it.
I want to implement the logic in such a way, so I get the CSV like below
userid, fname,lastname,rollno,gender (List<String> header)
1 , john, doe ,1001, M (List<List<Object>> data)
2 , Rose, Mary ,1002, F
3 , Jack, Jill ,1003, M
What is the best way to achieve the same by using writeNext().
#RequestMapping(value = "/export_data")
public void downloadDataInCsv(
#RequestParam("type") String type,
#RequestParam("tID") String tableId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (type.equals("csv")) {
List<UserInfo> list = userInfoDao.findById(tableId);
ExportCsvUtil.downloadCsv(request, response, list);
}
}
private void downloadCsv(HttpServletRequest request, HttpServletResponse response, List<UserInfo> list) throws IOException {
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=Table_Data.csv");
response.setContentType("text/csv");
response.setHeader(headerKey, headerValue);
try (final CSVWriter writer = new CSVWriter(response.getWriter(), ",")) {
writer.writeNext(new String[]{"User Id", "First Name", "Last Name", "Roll No", "Email ID", "Gender"});
for (UserInfo entry: list) {
// cast/convert to String where needed
writer.writeNext(new String[]{entry.getUserId()+"", entry.getFirstName(), entry.getLastName(),entry.getRollNo(),entry.getEmail(),entry.getGender()});
}
writer.close();
}
}
I have an android app which is making api requests to my server running Spring MVC. The RestController works fine when I make a request from the browser but it responds with 404 when I am making requests from android. Not sure why
Here is code snippet from Android app making requests
public class AsyncFetch extends AsyncTask<Pair<String, String>, String, String> {
public ProgressDialog pdLoading;
private HttpURLConnection conn;
private String urlStr;
private String requestMethod = "GET";
public AsyncFetch(String endpoint, Context ctx)
{
pdLoading = new ProgressDialog(ctx);
Properties reader = PropertiesReader.getInstance().getProperties(ctx, "app.properties");
String host = reader.getProperty("host", "10.0.2.2");
String port = reader.getProperty("port", "8080");
String protocol = reader.getProperty("protocol", "http");
String context = reader.getProperty("context", "");
this.urlStr = protocol+"://"+host+":"+port+context+endpoint;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Pair<String, String>... params) {
URL url;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made`enter code here`
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
Spring MVC Controller
#RestController
public class ApiController {
#RequestMapping(value = "homefeed", method=RequestMethod.GET)
public String homefeed(#RequestParam(value="userId", required = false) Integer id, #RequestParam(value="search", required = false) String search, #RequestParam(value="page", required = false, defaultValue = "0") Integer page) { ... }
}
localhost:8080/api/homefeed -- works
127.0.0.1:8080/api/homefeed -- works
My Public IP:8080/api/homefeed -- does not works
10.0.2.2:8080/api/homefeed -- android emulator to localhost -- does not work
10.0.2.2:8080/Some resource other than the api endpoint -- works
Any help is highly appreciable, have wasted quiet some time in debugging.
I am getting the following error on Tomcat.
The code is given below
message Servlet execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher
DBChart.doGet(DBChart.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.ClassNotFoundException: net.sf.ezmorph.Morpher
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
DBChart.doGet(DBChart.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Below is my Java file
//imported all the required packages here
class DBChart extends HttpServlet
{
Connection c = null;
Statement st = null;
ResultSet rs = null;
String query = null;
JSONObject obj = null;
JSONObject resobj = null;
PreparedStatement pst = null;
DatabaseMetaData dbmd = null;
String dbURL = "jdbc:sqlserver://localhost:1433; databaseName = EMPLOYEE";
String user = "username";
String password = "mypassword";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
List<JSONObject> Details = new LinkedList<JSONObject>();
PrintWriter out = response.getWriter();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
c = DriverManager.getConnection(dbURL, user, password);
query = " select DeptName, NumberOfEmployess from Departments";
pst = c.prepareStatement(query);
rs = pst.executeQuery();
while (rs.next())
{
String dept = rs.getString(1);
int empnumber = rs.getInt(2);
obj = new JSONObject();
obj.put("DepartmentName", dept);
obj.put("EmployeesinNumbers", empnumber);
Details.add(obj);
}
resobj.put("RelativeDetails", Details);
out.write(resobj.toString());
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
}
I made sure that I have mentioned the correct name in XMl file and using the url as follows:
http://localhost:8080/DBCHART/db
Your class needs to be public:
public class DBChart extends HttpServlet
Scenario - upload binary data in the body of a post, handle a response body containing JSON.
How to do the following using Volley?
curl -X POST -H "X-Application-Id: 3KxPB" -H "X-REST-API-Key: jkuI9" -H "Content-Type: audio/3gp" --data-binary '#test.3gp' https://host/1/files/audio
IMO - there is a gap in Volley handling binary POST body types that apache httpclient handles in subclasses of abstracthttpentity. If buffered binary data generated on the phone by camera, microphone, or other binary output sensors needs a mechanism to be wrapped and written to the body of a POST how to do it in volley?
I've looked at PoolingByteArrayOutputStream and would like to do something like fill the buffer and get the PBAOutStrm ,writing to PBAOutStrm from the buffer and then flipping OutStrm to InputStream and then wrap it in the body of a POST request as something like a ByteArrayEntity. I cant see how to do that in volley.
To send binary data you can do something like what I did in this answer How to send a “multipart/form-data” POST in Android with Volley .
I was able to solve this using a Volley GsonRequest:
public class MainActivity extends AppCompatActivity {
String url = "https://arcane-anchorage-34204.herokuapp.com/handleCode";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject jsonBody = null;
try {
jsonBody = new JSONObject ("{\"code\":\"NZ4UBUB\"}");
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error e = " + e, Toast.LENGTH_SHORT).show();
}
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
RequestQueue queue = Volley.newRequestQueue(this);
GsonRequest<Routine[]> gsonRequest = new GsonRequest<Routine[]>(Request.Method.POST, url, Routine[].class, headers, new Response.Listener<Routine[]>() {
#Override
public void onResponse(Routine[] routineData) {
TextView serverData = (TextView)findViewById(R.id.serverData);
String complete = "";
String repeat = "";
String hold = "";
String perform = "";
String txtData = "";
for (int i = 0; i < routineData.length; i++) {
complete = (routineData[i].instructions.complete != null) ? "Complete: " + routineData[i].instructions.complete : "";
repeat = (routineData[i].instructions.repeat != null) ? "Repeat: " + routineData[i].instructions.repeat : "";
hold = (routineData[i].instructions.hold != null) ? "Hold: " + routineData[i].instructions.hold : "";
perform = (routineData[i].instructions.perform != null) ? "Perform: " + routineData[i].instructions.perform : "";
txtData += "DESCRIPTION: " + routineData[i].description[0] + ": " + routineData[i].description[1] + ", " + complete + ", " + repeat + ", " + hold + ", " + perform + " ";
}
serverData.setText("Response: " + txtData);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
TextView serverData = (TextView)findViewById(R.id.serverData);
serverData.setText("Response: " + volleyError.toString());
}
}, jsonBody);
queue.add(gsonRequest);
}
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<T> listener;
private JSONObject parameters = null;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener, JSONObject parameters) {
this(method, url, clazz, headers, listener, errorListener);
this.parameters = parameters;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return parameters.toString().getBytes(getParamsEncoding());
} catch (UnsupportedEncodingException e) {
}
return null;
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data, HttpHeaderParser.parseCharset(response.headers));
Log.i("RESPONSE", json);
return Response.success(
gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
}