I am using Volley library for fetching the json data. I have also modified the Manifest adding the necessary Internet permission . But when I run the app it crashes.
Main activity.java
package com.example.sans.myapplication1;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView listView;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listView=(ListView)findViewById(R.id.list);
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, "http://api.themoviedb.org/3/movie/popular?api_key=fa468af9e769ba5fbc027e9e933130ed",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Movie> movieList= new ArrayList<Movie>();
try{
JSONArray jsonArray=response.getJSONArray("results");
for (int i=0;i< jsonArray.length();i++){
JSONObject jsonObject= jsonArray.getJSONObject(i);
String title= jsonObject.getString("title");
movieList.add(new Movie(title));
MovieAdapter adapter= new MovieAdapter(getApplicationContext(),movieList);
listView.setAdapter(adapter);
}
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error getting data", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
$ MovieAdapter.java
package com.example.sans.myapplication1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by sans on 13/7/16.
*/
public class MovieAdapter extends ArrayAdapter<Movie> {
public MovieAdapter(Context context, List<Movie> objects) {
super(context,0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Movie movie=getItem(position);
if(convertView==null){
convertView= LayoutInflater.from(getContext()).inflate(R.layout.list_row, parent);
}
TextView title=(TextView)convertView.findViewById(R.id.title);
title.setText(movie.getTitle());
return convertView;
}
}
$ Movie.java
package com.example.sans.myapplication1;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by sans on 13/7/16.
*/
public class Movie {
private String title;
public Movie(String title){
this.title=title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
$ list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/listPreferredItemHeight"
android:id="#+id/title"/>
</LinearLayout>
$ content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.sans.myapplication1.MainActivity"
tools:showIn="#layout/activity_main">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list" />
</RelativeLayout>
Log error
FATAL EXCEPTION: main
Process: com.example.sans.myapplication1, PID: 4252
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.sans.myapplication1.MovieAdapter.getView(MovieAdapter.java:29)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
at android.widget.ListView.onMeasure(ListView.java:1188)
at android.view.View.measure(View.java:18788)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18788)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-13 17:37:39.746 1532-1903/? W/ActivityManager: Force finishing activity com.example.sans.myapplication1/.MainActivity
In MovieAdapter.java class change convertView!=null to convertView==null
& in list_row.xml file
instead of android:minHeight="?attr/listPreferredItemHeight"
change it to android:minHeight="?android:attr/listPreferredItemHeight"
Related
the spring boot REST app with MySQL
I am trying to add record to DB and expect the record added and postman got it as output instead of the output "status":404,"error":"Not Found","path":"/api/employees" following is the classes
package com.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.service.EmployeeService;
import com.model.Employee;
#RestController
#RequestMapping("/api")
public class EmployeeController {
private EmployeeService employeeservice;
public EmployeeController(EmployeeService employeeservice) {
super();
this.employeeservice = employeeservice;
}
//build create Employee REST API
#PostMapping("/employees")
public ResponseEntity<Employee> saveEmployee(#RequestBody Employee employee)
{
return new ResponseEntity<Employee>(employeeservice.saveEmployee(employee), HttpStatus.CREATED);
}
}
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories(
basePackages = {"com.model"})
#SpringBootApplication(scanBasePackages = {"service.impl"})
public class RestapimysqlApplication {
public static void main(String[] args) {
SpringApplication.run(RestapimysqlApplication.class, args);
}
}
It doesn't look like you're scanning the package that contains your REST controller (i.e. com.controller), seems like you're only scanning the service.impl package on your RestapimysqlApplication class.
You should probably add the com.controller to the list of packages being scanned by Spring here:
#EnableJpaRepositories(basePackages = {"com.repository"})
#SpringBootApplication(scanBasePackages = {"service.impl", "com"})
#EntityScan({"com.model"})
public class RestapimysqlApplication {
...
}
Tried every solution from >https://stackoverflow.com/questions/10069050/download-file-inside-webview
but every time it just opens the text file instead of downloading it. The text file is just temporary; when I try it with an apk it just crashes.
Incae you were wondering here is the HTML text
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="head">
<h1>FisheStore</h1>
</div>
<a href="drawable/text.txt" download>Install</a>
</body>
</html>
And here is whats in MainActivity.Java
package com.example.project;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("file:///android_asset/index.html");
webView.setDownloadListener(new DownloadListener()
{
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition,
mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}});
}
}
I have a service project written in Java11. It is using junit tests to cover full code coverage.
I have written scheduler method to updateFiles (invoked by Files.walkFileTree) in FileReceivingStateMarkerService class. I want to test static call Files.walkFileTree from test class written for FileReceivingStateMarkerService. I need to use PowerMockRunner to test static call as it cannot be tested by simple MockitoJunitRunner.
On running test, I am getting NPE in setUp method at line - mockStatic(Files.class);
Can you please help me to resolve issue on how to configure powermock with Java11 and initialize static class?
I configured powermock in service project (in Java11) as below
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0-RC.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0-RC.1</version>
<scope>test</scope>
</dependency>
FileReceivingStateMarkerService class
class FileReceivingStateMarkerService {
private static final Logger LOG = LoggerFactory.getLogger(FileReceivingStateMarkerService.class);
private final FileProcessingActivityRepositoryService fileProcessingActivityRepositoryService;
private final FilePollActivityRepository filePollActivityRepository;
private final FileProcessingRequestRepositoryService fileProcessingRequestRepositoryService;
#Autowired
FileReceivingStateMarkerService(FileProcessingActivityRepositoryService fileProcessingActivityRepositoryService, FilePollActivityRepository filePollActivityRepository,
FileProcessingRequestRepositoryService fileProcessingRequestRepositoryService) {
this.fileProcessingActivityRepositoryService = fileProcessingActivityRepositoryService;
this.filePollActivityRepository = filePollActivityRepository;
this.fileProcessingRequestRepositoryService = fileProcessingRequestRepositoryService;
}
#Scheduled(fixedDelayString="#{${fileprocess.filemonitor.interval.minutes}*60*1000}")
void updateFiles() {
List<FileProcessingRequest> requests = fileProcessingRequestRepositoryService.getFileProcessingRequests();
LOG.debug("Running file receiving state");
requests.forEach(request -> {
LOG.debug("Looking at location {}", request.getFileLocation());
final var fileVisitor = new FileReceivingStateMarkerFileVisitor(filePollActivityRepository
, fileProcessingActivityRepositoryService
, request);
try {
Files.walkFileTree(Path.of(request.getFileLocation()), Collections.emptySet(), 1, fileVisitor);
} catch(Exception e) {
LOG.debug(e.getMessage());
}
});
}
}
Test class for FileReceivingStateMarkerService
package com.experianhealth.rfp.scheduler;
import com.experianhealth.rfp.core.DocumentType;
import com.experianhealth.rfp.core.FileProcessingRequest;
import com.experianhealth.rfp.dao.FilePollActivityRepository;
import com.experianhealth.rfp.service.FileProcessingActivityRepositoryService;
import com.experianhealth.rfp.service.FileProcessingRequestRepositoryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
#RunWith(PowerMockRunner.class)
#PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
#PrepareForTest(FileReceivingStateMarkerService.class)
public class FileReceivingStateMarkerServicePowerTest {
#Mock
private FileProcessingActivityRepositoryService fileProcessingActivityRepositoryService;
#Mock
private FilePollActivityRepository filePollActivityRepository;
#Mock
private FileProcessingRequestRepositoryService fileProcessingRequestRepositoryService;
#Before
public void setUp() throws Exception {
mockStatic(Files.class);
}
#Test
public void updateFiles() throws Exception {
String rootDir = "C:\\files_processor";
List<FileProcessingRequest> requests = new ArrayList<>();
FileProcessingRequest request = new FileProcessingRequest();
request.setClientId("123");
request.setTradingPartnerId("123");
request.setDocumentId(DocumentType.Payer);
request.setFileLocation(rootDir);
requests.add(request);
final var fileVisitor = new FileReceivingStateMarkerFileVisitor(filePollActivityRepository
, fileProcessingActivityRepositoryService
, request);
try {
PowerMockito.when(Files.walkFileTree(Path.of(request.getFileLocation() ), Collections.emptySet(), 1, fileVisitor))
.thenReturn(any());
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
I've been trying to figure the code out for quite a while now, however have had no success. Everytime the App crashes by throwing some random exception.
I learnt this code off a tutorial on youtube and despite that, the code doesn't work for me.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.Buffer;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
Button b1;
TextView t1;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.bthhit);
t1=(TextView)findViewById(R.id.tvJSONitem);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
});
}
public class JSONTask extends AsyncTask<String,String,String>{
HttpsURLConnection connection = null;
BufferedReader reader = null;
#Override
protected String doInBackground(String... params) {
try {
URL url=new URL(params[0]);
connection= (HttpsURLConnection)url.openConnection();
connection.connect();
InputStream stream= connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuffer buffer= new StringBuffer();
while((line=reader.readLine())!=null){
buffer.append(line);
}
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection!=null) {
connection.disconnect();
}
try {
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
t1.setText(result);
}
}
}
Logcat shows this:
01-05 00:46:09.018 5573-5580/? E/art: Failed sending reply to debugger: Broken pipe
01-05 00:46:17.852 5573-5706/com.example.test.jsonparser E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.test.jsonparser, PID: 5573
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
at com.example.test.jsonparser.MainActivity$JSONTask.doInBackground(MainActivity.java:58)
at com.example.test.jsonparser.MainActivity$JSONTask.doInBackground(MainActivity.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
01-05 00:46:19.104 5573-5587/com.example.test.jsonparser E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab792110
Please note that your URL protocol is HTTP and not HTTPS. Try either using a java.net.HttpURLConnection object or a "https://..." URL.
If some specific methods like .getResponseCode() or,... are not needed in your app, then you can use the generic URLConnection class as well, which will refrain from introducing this kind of exceptions, since it is the parent class for both HttpURLConnection and Https... classes somehow.
I am trying to upload a file into mysql database using struts1.But unable to doso,I am getting the error:FileNotFoundException.Here is my code...
1.JSP Page:
<%# taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<body>
<html:form action="upload" enctype="multipart/form-data">
Select a File :<html:file property="file"/>
<html:submit/>
</html:form>
</body>
</html:html>
2.My Action Form
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm{
private FormFile file;
public FormFile getFile(){
return this.file;
}
public void setFile(FormFile file){
this.file=file;
}
}
3.Action Class
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.sql.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{
UploadForm file=(UploadForm)form;
System.out.print("Executed");
FormFile formFile=file.getFile();
System.out.print("Executed1");
String fileName=formFile.getFileName();
System.out.print(fileName);
File file1=new File(formFile.getFileName());
System.out.print(">>>>");
FileInputStream fin=new FileInputStream(file1);
System.out.print("*****");
Integer fileSize=formFile.getFileSize();
int insert=0;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded.");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
System.out.println("Connection Opened.");
PreparedStatement pst=con.prepareStatement("insert into upload values(?)");
pst.setBinaryStream(1,fin,fileSize);
insert=pst.executeUpdate();
System.out.print("File Uploaded.");
}
catch(Exception e){System.out.println(e);}
if(insert!=0){
return mapping.findForward("success");
}
else{
return mapping.findForward("error");
}
}
}
I am getting error at this line in my Action Class:FileInputStream fin=new FileInputStream(file1);
Please help me to resolve this problem.