Inserting values into database using JSP - ajax

<%
if (MultipartFormDataRequest.isMultipartFormData(request))
{
// Uses MultipartFormDataRequest to parse the HTTP request.
MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
String todo = null;
if (mrequest != null) todo = mrequest.getParameter("todo");
if ( (todo != null) && (todo.equalsIgnoreCase("upload")) )
{
Hashtable files = mrequest.getFiles();
if ( (files != null) && (!files.isEmpty()) )
{
UploadFile file = (UploadFile) files.get("uploadfile");
if (file != null)
out.println("");
//out.println(report1);
String sever = mrequest.getParameter("sever");
String ease = mrequest.getParameter("ease");
String logo = "C:/uploads/"+file.getFileName(); // Uses the bean now to store specified by jsp:setProperty at the top.
String dana = mrequest.getParameter("danalysis");
String loc = mrequest.getParameter("loc");
String state = mrequest.getParameter("state");
String Sr = mrequest.getParameter("Sr");
String Doc_ID = mrequest.getParameter("doc");
String impact = mrequest.getParameter("impact");
String desc = mrequest.getParameter("desc");
String ref = mrequest.getParameter("ref");
String recom = mrequest.getParameter("recom");
try
{
String connectionURL = "jdbc:mysql://localhost:3306/mssg";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection(connectionURL, "root","");
out.println("OK!\n");
PreparedStatement ps1=con.prepareStatement("insert into report values(?,?,?,?,?,?,?,?,?,?,?,?)");
ps1.setString(1,Doc_ID);
ps1.setString(2,Sr);
ps1.setString(3,sever);
ps1.setString(4,ease);
ps1.setString(5,state);
ps1.setString(6,loc);
ps1.setString(7,desc);
ps1.setString(8,impact);
ps1.setString(9,dana);
ps1.setString(10,logo);
ps1.setString(11,recom);
ps1.setString(12,ref);
int count=ps1.executeUpdate();
if(count > 0)
{
out.println("successfully inserted");
//response.sendRedirect("/index.jsp");
}
else
{
out.println("error occured");
}
}
catch (Exception e)
{
System.out.println("error in program:-"+e);
}
upBean.store(mrequest, "uploadfile");
}
else
{
out.println("<li>No uploaded files");
}
}
}
%>
In the above code I get all the values also file is uploading but not able to insert these values into database. I think I made a very small mistake, please tell me what is the problem in the above code. This code is working until connection but after prepare statement it's not working.

This is beacuse you have used try and catch block.
In the jsp page life cycle, the jsp page is translated in the servlets. so the code for the database connectivity will be automatically placed in the try catch block.
Just remove the try catch block.

Related

Nifi Processor gets triggered twice for single Input flow file

I am currently new on Apache Nifi and still exploring it.
I made a custom processor where I will fetch data from server with pagination.
I pass the input file which will contains the attribute "url".
Finally transfer the response in output flow file, as I fetch data with pagination, so I made a new output flow file for each page and transferred it to Successful relationship.
Below is the code part:
#Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
FlowFile incomingFlowFile = session.get();
String api = null;
if (incomingFlowFile == null) {
logger.info("empty input flow file");
session.commit();
return;
} else {
api=incomingFlowFile.getAttribute("url");
}
session.remove(incomingFlowFile);
if(api == null) {
logger.warn("API url is null");
session.commit();
return;
}
int page = Integer.parseInt(context.getProperty(PAGE).getValue());
while(page < 3) {
try {
String url = api + "&curpg=" + page;
logger.info("input url is: {}", url);
HttpResponse response = httpGetApiCall(url, 10000);
if(response == null || response.getEntity() == null) {
logger.warn("response null");
session.commit();
return;
}
String resp = EntityUtils.toString(response.getEntity());
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(resp).array());
FlowFile outFlowFile = session.create();
outFlowFile = session.importFrom(is, outFlowFile);
session.transfer(outFlowFile, SUCCESSFUL);
} catch (IOException e) {
logger.warn("IOException :{}", e.getMessage());
return;
}
++page;
}
session.commit();
}
I am facing issue that for a single Input flow file, this processor get triggered twice and so it generates 4 flow files for a single input flow file.
I am not able to figure out this where I have done wrong.
Please help in this issue.
Thanks in advance.
======================================================================
processor group 1(Nifi_Parvin)
processor group 2 (News_Point_custom)

Saving new File to any directory Groovy

I keep getting file or directory does not exist. I am running within a Groovy script that creates a Spring Application Context. I am easily reading in a different file using the same type of pathing. However, the file I am reading is in the class path of Spring. This script might be run by any number of people with different file systems, so I can't hard code a path. I need a relative path.
This is above in the class but important info.
private static String saveFilesToLocation = "/retrieve/";
Here is the code.
CSVReader reader = new CSVReader(new InputStreamReader(balanceFile), SEPARATOR)
String[] nextLine
int counter = 0;
while ((nextLine = reader.readNext()) != null) {
counter++
if (nextLine != null && (nextLine[0] != 'FileLocation') ) {
counter++;
try {
//Remove 0, only if client number start with "0".
String fileLocation = nextLine[0];
byte[] fileBytes = documentFileService.getFile(fileLocation);
if (fileBytes != null) {
String fileName = fileLocation.substring(fileLocation.indexOf("/") + 1, fileLocation.length());
File file = new File(saveFilesToLocation+fileLocation);
file.withOutputStream {
it.write fileBytes
}
println "$counter) Wrote file ${fileLocation} to ${saveFilesToLocation+fileLocation}"
} else {
println "$counter) UNABLE TO RETRIEVE FILE: $fileLocation";
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
The paths in Strings have what I would expect in them, no extra characters.
UPDATE:
Thanks loteq Your answer would work too, and has better grooviness than our final result that worked. Since it is a sort of one off, we don't have the time to change to the nicer version you have.
Here is the code that worked for us, it is identical to above except the saveFilesToLocation is set to a directory that already exists now. The one before didn't exist and we would have needed to call mkdir like loteq
suggested.
private static String saveFilesToLocation = "/tmp/retrieve/";
CSVReader reader = new CSVReader(new InputStreamReader(balanceFile), SEPARATOR)
String[] nextLine
int counter = 0;
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null && (nextLine[0] != 'FileLocation') ) {
counter++;
try {
//Remove 0, only if client number start with "0".
String fileLocation = nextLine[0];
byte[] fileBytes = documentFileService.getFile(fileLocation);
if (fileBytes != null) {
String fileName = fileLocation.substring(fileLocation.indexOf("/") + 1, fileLocation.length());
File file = new File(saveFilesToLocation+fileName);
file.withOutputStream {
it.write fileBytes
}
println "$counter) Wrote file ${fileLocation} to ${saveFilesToLocation+fileLocation}"
} else {
println "$counter) UNABLE TO RETRIEVE FILE: $fileLocation";
}
} catch (Exception e) {
e.printStackTrace()
}
} else {
counter++;
}
}
There seems to be something add in your code, but I can't be certain that it's a bug.
You compute a fileName and don't really use it to create the target file. Instead you just append the original path to the prefix saveFilesToLocation:
String fileName = fileLocation.substring(fileLocation.indexOf("/") + 1, fileLocation.length());
File file = new File(saveFilesToLocation+fileLocation);
This seems strange.
Then, if fileLocation contains directories that need to be created, then you need to mkdirs() them, otherwise you will get an error.
I will give you 2 snippets, one atht assumes that youir code above is buggy, te other that does what you do in a safer way, in idiomatic groovy.
First lets work with actual File objects instead if Strings:
private static File saveFilesToLocationDir = saveFilesToLocation as File
Version that supposes a bug in the above code:
private static String saveFilesToLocation = "/retrieve/";
private static File saveFilesToLocationDir = saveFilesToLocation as File
CSVReader reader = new CSVReader(new InputStreamReader(balanceFile), SEPARATOR)
String[] nextLine
int counter = 0;
while ((nextLine = reader.readNext()) != null) {
counter++
if (nextLine != null && (nextLine[0] != 'FileLocation')) {
counter++;
try {
//Remove 0, only if client number start with "0".
String fileLocation = nextLine[0];
byte[] fileBytes = documentFileService.getFile(fileLocation);
if (fileBytes != null) {
int firstSlash = fileLocation.indexOf("/") + 1
String fileName = fileLocation[firstSlash..-1]
File destination = new File(saveFilesToLocationDir, fileName)
destination.parentFile.mkdirs()
destination.withOutputStream { it << fileBytes }
println "$counter) Wrote file ${fileLocation} to ${destination.absolutePath}"
} else {
println "$counter) UNABLE TO RETRIEVE FILE: $fileLocation";
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
Version that does not use the created fileName (like you):
private static String saveFilesToLocation = "/retrieve/";
private static File saveFilesToLocationDir = saveFilesToLocation as File
CSVReader reader = new CSVReader(new InputStreamReader(balanceFile), SEPARATOR)
String[] nextLine
int counter = 0;
while ((nextLine = reader.readNext()) != null) {
counter++
if (nextLine != null && (nextLine[0] != 'FileLocation')) {
counter++;
try {
//Remove 0, only if client number start with "0".
String fileLocation = nextLine[0];
byte[] fileBytes = documentFileService.getFile(fileLocation);
if (fileBytes != null) {
int firstSlash = fileLocation.indexOf("/") + 1
String fileName = fileLocation[firstSlash..-1]
File destination = new File(saveFilesToLocationDir, fileLocation)
destination.parentFile.mkdirs()
destination.withOutputStream { it << fileBytes }
println "$counter) Wrote file ${fileLocation} to ${destination.absolutePath}"
} else {
println "$counter) UNABLE TO RETRIEVE FILE: $fileLocation";
}
} catch (Exception e) {
e.printStackTrace()
}
}
}

Android getContentResolver insert not returning full URI

I have an activity that is being swapped out when I raise an intent for another activity. onPause calls saveState() to save work so far:
private void saveState() {
...
...
if (myUri == null) {
// Inserting a new record
*** myUri = getContentResolver().insert(ContentProvider.CONTENT_URI, values);
} else {
// Update an existing record
getContentResolver().update(myUri, values, null, null);
}
}
Before calling getContentResolver(), ContentProvider.CONTENT_URI = 'content://nz.co.bkd.extraTime.contentprovider/times'.
After the call, myUri = 'times/#' where #=row ID. My question is; where is the 'content:...' prefix to the returned uri?
During the call, ContentResolver.java is called and returns CreatedRow uri
ContentResolver.java
....
....
public final Uri insert(Uri url, ContentValues values)
{
IContentProvider provider = acquireProvider(url);
if (provider == null) {
throw new IllegalArgumentException("Unknown URL " + url);
}
try {
long startTime = SystemClock.uptimeMillis();
*** Uri createdRow = provider.insert(url, values);
long durationMillis = SystemClock.uptimeMillis() - startTime;
maybeLogUpdateToEventLog(durationMillis, url, "insert", null /* where */);
return createdRow;
} catch (RemoteException e) {
// Arbitrary and not worth documenting, as Activity
// Manager will kill this process shortly anyway.
return null;
} finally {
releaseProvider(provider);
}
}
At this point, createdRow = 'times/#'.
The record does actually get saved in the Sqlite database.
Do I have to add the uri prefix in my code or should the full uri be returned?

BlackBerry - Downloaded images are corrupted on wifi with HttpConnection

In my app I need to download several images from a server. I use this code to get a byte array :
HttpConnection connection = null;
InputStream inputStream = null;
byte[] data = null;
try
{
//connection = (HttpConnection)Connector.open(url);
connection = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK)
{
inputStream = connection.openInputStream();
data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
}
connection.close();
return data;
}
catch(IOException e)
{
return null;
}
The url are formed with the suffix ";deviceSide=false;ConnectionType=MDS - public" (without spaces) and it is working perfectly well.
The problem is that with phones that do not have a sim card, we can't connect to the internet via the MDS server. So we changed to use the connection factory and let BB choose whatever he wants :
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
final HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
httpConn.setRequestMethod(HttpConnection.GET);
final int iResponseCode = httpConn.getResponseCode();
if(iResponseCode == HttpConnection.HTTP_OK)
{
InputStream inputStream = null;
try{
inputStream = httpConn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
return data;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
return null;
The connection works because it select the good prefix (interface=wifi in our case), but this create another problem.
Some images are not well downloaded, some of them (not the sames at each try) are corrupted, but only when the phone use a wifi connection to get these images.
How can I avoid this problem ? What method to get a connection do I have to use ? Is it possible to check if the user have a sim card in orderto use MDS - public ?
Here is an example of a corrupted image :
error image http://nsa30.casimages.com/img/2012/06/28/120628033716123822.png
try this:
public static String buildURL(String url) {
String connParams = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connParams = ";interface=wifi"; //Connected to a WiFi access point.
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
//
if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
connParams = ";deviceside=false;ConnectionType=mds-public";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage and a WAP 2.0 service book record
ServiceRecord record = getWAP2ServiceRecord();
//
if (record != null) {
connParams = ";deviceside=true;ConnectionUID=" + record.getUid();
} else {
connParams = ";deviceside=true";
}
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// Have an MDS service book and network coverage
connParams = ";deviceside=false";
}
}
Log.d("connection param"+url+connParams);
//
return url+connParams;
}
private static ServiceRecord getWAP2ServiceRecord() {
String cid;
String uid;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
//
for (int i = records.length -1; i >= 0; i--) {
cid = records[i].getCid().toLowerCase();
uid = records[i].getUid().toLowerCase();
//
if (cid.indexOf("wptcp") != -1
&& records[i].getUid().toLowerCase().indexOf("wap2") !=-1
&& uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
//
return null;
}
What happens when you append interface=wifi? Can you run the network diagnostic tool attached to below kb article and run all tests with SIM removed
http://supportforums.blackberry.com/t5/Java-Development/What-Is-Network-API-alternative-for-legacy-OS/ta-p/614822
Please also note that when download large files over BES/MDS there are limits imposed by MDS. Please ensure you review the below kb article
http://supportforums.blackberry.com/t5/Java-Development/Download-large-files-using-the-BlackBerry-Mobile-Data-System/ta-p/44585
You can check to see if coverage is sufficient for BIS_B (MDS public) but that won't help you if you are trying to support SIM-less users. I wonder if the problem is in an incomparability between the connection on Wi-Fi and IOUtilities.streamToBytes(). Try coding as recommended in the API documents.

MVC 3 The process cannot access the file because it is being used by another process

I upload a file in my MVC 3 project.
[HttpPost]
public ActionResult MyUpload(HttpPostedFileBase file)
{
string filePath = string.Empty;
string path = "C:\\";
string filePath = string.Empty;
try
{
if (file != null && file.ContentLength > 0)
{
filePath = path + file.FileName;
file.SaveAs(filePath);
file.InputStream.Dispose();
GC.Collect();
// other operations, where can occur an exception
// (because the uploaded file can have a bad content etc.)
}
}
catch (Exception e)
{
if (file.InputStream != null)
file.InputStream.Dispose();
GC.Collect();
if (!string.IsNullOrEmpty(filePath))
{
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath); //here is the error
}
}
}
in that code, if an exception occured after I saved the file I can't delete it (also I cann't upload it again) because I get the error
The process cannot access the file
'[filePath]' because it is being used by another process.
What's wrong with that code ?
edit
I had to change the file.InputStream.Dispose(); to
file.InputStream.Close();
file.InputStream.Dispose();
file.InputStream = null;
And, now it's working fine.
Instead of checking if the file.InputStream is not null inside the catch block, you should dispose it inside the finally block, like this:
if (file != null && file.ContentLength > 0)
{
try
{
filePath = path + file.FileName;
file.SaveAs(filePath);
// other operations, where can occur an exception
// (because the uploaded file can have a bad content etc.)
}
catch (Exception e)
{
if (!string.IsNullOrEmpty(filePath))
{
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath); //here is the error
}
}
finally
{
file.InputStream.Close();
file.InputStream.Dispose();
GC.Collect();
}
}
By the way, the InputStream property is a read-only property. You can't set it to null.

Resources