Write Properties to URL - java

I am trying to the properties from java.util.Properties to a online file using its URL.
This is the code I have so far:
public static boolean savePropertiesToURL(Properties properties, String link, String fileName) {
boolean result = false;
if (properties != null && link != null && fileName != null) {
try {
URL url = new URL(link);
try {
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
try {
OutputStream outStream = connection.getOutputStream();
try {
properties.store(outStream, fileName);
} catch (IOException ex) {
System.err.println("Unable to store the properties: " + ex.getMessage());
} finally {
try {
outStream.flush();
result = true;
} catch (IOException ex) {
Logger.getLogger(PropertiesUtil.class.getName()).log(Level.SEVERE, null, ex);
System.err.println("Unable to flush outputstream: " + ex.getMessage());
}
outStream.close();
}
} catch (IOException ex) {
System.err.println("Unable to get outputstream: " + ex.getMessage());
}
} catch (IOException ex) {
System.err.println("Unable to open URL connexion: " + ex.getMessage());
}
} catch (MalformedURLException ex) {
System.err.println("The URL hasn't been created: " + ex.getMessage());
}
}
return result;
}
It goes thru all that and returns true. Even tho the file is not written.
There are loggers in every catch, but no catch is ever triggered.

Related

I am getting 500 as reply code when I try to delete a file from remote server using java FTPClient

When I try to delete a file using ftpclient I am getting reply code as 500. Can someone help me with the issue. As you can see in the commented section of the code I tried to move the file to other folder and I got the reply code as 500 as well.
public boolean sendFile(HttpResponse httpresponse, String accessionNumber)
throws Exception {
FTPClient ftpClient = null;
boolean fileUploadStatus = false;
InputStream inputStream = null;
try {
FTPSClient ftpClient = new FTPSClient(true);
String fileName = "SampletesterFileNine.pdf";
String remotePath = "/";
String tempFile = remotePath + fileName;
try {
ftpClient.connect(server, this.port);
} catch (Exception e) {
e.printstackTrace();
}
int reply = ftpClient.getReplyCode();
logger.info("Reply code connect :" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
boolean login = ftpClient.login(userName, password);
if (login) {
if (ftps) {
((FTPSClient) ftpClient).execPROT("P");
}
logger.info("Logged in to ftp server with host " + server);
} else {
logger.info("login failed");
}
} else {
logger.info("login failed with exception");
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
logger.info("Checking whether file exists or not!!");
inputStream = ftpClient.retrieveFileStream(tempFile);
if(inputStream != null) {
logger.info("File already exists");
isFileExist = true;
String toPath = "/failed/SampletesterFileNine.pdf";
/*boolean renamed = ftpClient.rename(tempFile, toPath);
logger.info("replycode is : " + ftpClient.getReplyCode());
if(renamed) {
logger.info("file moved to failed folder successfully");
} else {
logger.info("failed while moving file to failed folder");
} */
boolean renamed = ftpClient.deleteFile(tempFile);
logger.info("replycode is : " + ftpClient.getReplyCode());
if(renamed) {
logger.info("file moved to failed folder successfully");
} else {
logger.info("failed while moving file to failed folder");
}
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
} catch(Exception e) {
throw e;
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
} catch (Exception e) {
e.printstackTrace();
}
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (Exception e) {
e.printstackTrace();
}
}
return fileUploadStatus;
}

Resources not getting released in java

So, I have a function that reads file data, in this case image size. But after it's done it doesn't seem to properly release the files. I can't move those files afterwards. If I don't call this function everything works, but if I do I always get "file in use.. blah blah blah"
private void setMoveType() {
ImageInputStream in = null;
try {
in = ImageIO.createImageInputStream(new FileInputStream(file.toString()));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if(readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
try {
moveType = Helper.getMoveType(new Dimension(reader.getWidth(0), reader.getHeight(0)));
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
} catch(Exception e) {
System.err.println("ReaderException: " + e.getMessage());
} finally {
reader.dispose();
}
}
} catch(Exception e) {
System.err.println("MoveTypeSetException: " + e.getMessage());
}
} catch (IOException e) {
System.err.print("IOException: failure while creating image input stream");
System.err.println(" -> createImageInputStream Error for file: " + file.getFileName());
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
}
}
}
EDIT: The ImageInputStream doesn't close properly
EDIT2: a FileInputStream wasn't closed
This stream should also be closed:
new FileInputStream(file.toString())
Closing the stream when you are done should work (in.close()). The operating system prevents the file from being changed, deleted or moved while it is in use. Otherwise, the stream would get messed up. Closing the stream tells the operating system you are no longer using the file.

Using a save button to save arraylist to .dat file on C:drive

I am having a hard time with saving my file to my C: drive using my save button. My action listener looks like this
saveButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
File savedFile = new File("C:\\data\\inventory.dat");
if (savedFile.exists() == false)
{
try
{
savedFile.createNewFile();
outputText.append("The file has been saved\n");
}
catch (IOException ex)
{
Logger.getLogger(JavaGUIFixed.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
if (savedFile.exists() == true)
{
try
{
savedFile.createNewFile();
outputText.append("The file already exists\n and has been overwritten\n");
}
catch (IOException ex)
{
Logger.getLogger(JavaGUIFixed.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
);
The problem I keep running into is
Dec 06, 2013 12:14:16 AM javaguifixed.JavaGUIFixed$8 actionPerformed
SEVERE: null
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1006)
Can anyone point me in the right direction? Why is this not saving? Essentially it should be creating the directory as well as the file if it doesn't exist and it should overwrite it if it does.
I did some playing around and got this to work. Below is my code
saveButton.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
File savedFile = new File("C:\\Users\\kerinr\\Documents\\data\\inventory.dat");
if (savedFile.exists() == false) {
try {
savedFile.createNewFile();
outputText.append("The file has been saved\n");
} catch (IOException ex) {
Logger.getLogger(JavaGUIFixed.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
if (savedFile.exists() == true) {
try {
savedFile.createNewFile();
outputText.append("The file already exists\n and has been overwritten\n");
} catch (IOException ex) {
Logger.getLogger(JavaGUIFixed.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("C:\\Users\\kerinr\\Documents\\data\\inventory.dat"), "utf-8"));
for (int i = 0; i < inventory.size(); i++) {
writer.write(inventory.get(i).itemName + " \r\n");
writer.write(inventory.get(i).inStock + " \r\n");
writer.write(inventory.get(i).itemNumber + " \r\n");
writer.write(inventory.get(i).unitPrice + " \r\n");
writer.write(inventory.get(i).restockingFee + " \r\n");
writer.write(inventory.get(i).inventoryValue + " \r\n");
}
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
});
One thing I have noticed though is that the folder "data" has to already be in place. If it is not then it will not save the file.

apache ftpclient retrievefile() downloading corrupted file

I am using org.apache.commons.net.ftp.FTPClient for downloading files from ftp server.
It downloads all the files from my ftp server except those files with names like test.xml test.txt west.xml etc., The files with these names are getting downloaded with no data inside the file. retrieveFile() method is returning boolean false for these files.
I tried to download the same file by renaming its name manually on ftp server. It worked well with other names.
Please let me know how to solve this problem.
EDIT- Adding sample code
public static boolean downloadFTPDir(String localDir, FTPClient ftpClient) {
OutputStream output = null;
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
/*
* Use passive mode as default because most of us are behind
* firewalls these days.
*/
ftpClient.enterLocalPassiveMode();
FTPFile[] fileList = ftpClient.listFiles();
for (FTPFile ftpFile : fileList) {
if(ftpFile.isDirectory()){
String tempDir = localDir + File.separatorChar+ftpFile.getName();
try {
File temp = new File(tempDir);
temp.mkdirs();
} catch (Exception e) {
System.out.println("Could not create local directory "+tempDir);
return false;
}
if(ftpClient.changeWorkingDirectory(ftpFile.getName())) {
downloadFTPDir(tempDir, ftpClient);
} else {
System.out.println("Could change directory to "+ftpFile.getName()+" on FTP server");
return false;
}
} else {
output = new FileOutputStream(localDir + File.separatorChar + ftpFile.getName());
if (!ftpClient.retrieveFile(ftpFile.getName(), output)) {
System.out.println("Unable to download file from FTP server : " + ftpFile.getName());
File tmp = null;
try {
output.close();
/*tmp = new File(localDir + File.separatorChar + ftpFile.getName());
tmp.delete();
logger.info("Deleted corrupt downloaded file : " + tmp.getAbsolutePath());*/
} catch (FTPConnectionClosedException e) {
System.out.println("Connection to FTP server is closed ");
return false;
} catch (Exception e1) {
System.out.println("Unable to delete corrupt file from local directory : " + tmp.getAbsolutePath());
return false;
}
}
output.close();
System.out.println("FTP file download successful : " + ftpFile.getName());
}
}
} catch (FTPConnectionClosedException e) {
e.printStackTrace();
return false;
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return false;
} catch (IOException e2) {
e2.printStackTrace();
return false;
} catch (Exception e3) {
try {
output.close();
} catch (Exception e4) {
e3.printStackTrace();
}
return false;
} finally{
try {
if(output!=null)
output.close();
} catch (Exception e5) {
e5.printStackTrace();
}
}
return true;
}
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("FTP IP", 21);
System.out.println("connecting");
if(FTPReply.isPositiveCompletion(ftpClient.getReply())) {
System.out.println("connected");
if(!ftpClient.login("FTP username", "FTP Password")) {
System.out.println("could not login");
ftpClient.disconnect();
return;
}
System.out.println("logged in");
String remotePath = "FTP directory Path";
StringTokenizer st = new StringTokenizer(remotePath, "/");
String dir = null;
boolean status = false;
while (st.hasMoreTokens()) {
dir = st.nextToken();
status = ftpClient.changeWorkingDirectory(dir);
if (!status) {
System.out.println("FTP client is not able to change the current directory to " + dir);
return ;
}
}
System.out.println("connected");
downloadFTPDir("local path", ftpClient);
} else {
ftpClient.disconnect();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Connection was forcibly closed error in servlet

I am getting an error in my java servlet. The servlet fills the fields of an existing pdf. The page pulls up an alert asking "Do you want to open or save this file?" So if I press "Open" or "Save" it works fine, and does the correct thing. But.... if I press "Cancel", nothing pops up, and I get this error:
com.evermind.server.http.HttpIOException: An existing connection was forcibly closed by the remote host
I am not sure why or where this error is coming about, but it says that the error is happening on this line:
stamp.close();
If more code snippets are needed, please let me know. I just didnt want to paste everything in here, because I dont exactly know where it is happening. Thanks in advance.
EDIT
Here is the majority of my relevant code:
try {
conn = ((DataSource) new InitialContext().lookup(dSource)).getConnection();
stmt = conn.prepareStatement("....");
rs = stmt.executeQuery();
if (rs.next()) {
....
}
stmt = conn.prepareStatement("....");
rs = stmt.executeQuery();
if (rs.next()) {
....
}
if (isTempVerification) {
final String tempFile = "TemporaryVerification.pdf";
try {
response.setHeader(contentDisposition, "attachment; filename=" + tempFile);
reader = new PdfReader(this.getServletContext().getResource("/pdf/" + tempFile));
stamp = new PdfStamper(reader, response.getOutputStream());
form = stamp.getAcroFields();
form.setField("date", current);
form.setField("reply_line", replyLine);
form.setField("first_middle_last", fmlName);
form.setField("term_year_1", termYear + ".");
form.setField("census_date", termCensus);
form.setField("term_year_2", termYear + ".");
//stamp.setFormFlattening(true);
stamp.close();
} catch (IOException e) {
errorFound = true;
e.printStackTrace(System.err);
} catch (DocumentException e) {
errorFound = true;
e.printStackTrace(System.err);
}
} else {
final String officialFile = "OfficialVerification.pdf";
try {
response.setHeader(contentDisposition, "attachment; filename=" + officialFile);
reader = new PdfReader(this.getServletContext().getResource("/pdf/" + officialFile));
stamp = new PdfStamper(reader, response.getOutputStream());
form = stamp.getAcroFields();
form.setField("date", current);
form.setField("reply_line", replyLine);
form.setField("first_middle_last", fmlName);
form.setField("status", studentStatus);
form.setField("hr", hoursTaken);
form.setField("term_year", termYear);
form.setField("start_end_date", termStart + " - " + termEnd);
//stamp.setFormFlattening(true);
stamp.close();
} catch (IOException e) {
errorFound = true;
e.printStackTrace(System.err);
} catch (DocumentException e) {
errorFound = true;
e.printStackTrace(System.err);
}
}
} catch (NamingException e) {
e.printStackTrace(System.err);
} catch (SQLException e){
e.printStackTrace(System.err);
} finally {if (stmt != null) try {stmt.close();
} catch (SQLException e){
e.printStackTrace(System.err);
} if (rs != null) try {rs.close();
} catch (SQLException e){
e.printStackTrace(System.err);}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace(System.err);
}
}
when u make the stamp.close() call, the output stream is also flushed. since you set the response headers before stamp.close(), the response headers are also written to the client. consequently, this causes the file download dialog to appear on the client. when the client clicks 'cancel', the http connection is terminated.
your servlets need to maintain the http connection throughout its execution as it will be writing output to the response output stream. if the http connection is terminated before the response has been committed, you will get the exception that you are seeing now.

Categories