How to append more than two folders to user.home java - javafx

guys! I'm trying to append folder to user.home property. It working nice, while I'm using just one additional folder. But when I try to make another two additions (so it looks like user.home+folder1+folder2+folder3) it trows ---
java.lang.IllegalArgumentException: Folder parameter must be a valid folder---
. My though that there is some restriction, but can't find out where.
String fullRoute = null;
File homeDir = new File("MLog");
if (!SiteCo.getEditor().getText().isEmpty() &&
!InciDate.getEditor().getText().isEmpty()) {
homeDir.mkdirs();
fullRoute = System.getProperty("user.home") + File.separator +
//SaveVarTo.getLastVisitedDirectory() +
SaveVarTo.AddPath(SiteCo.getValue().toString()) +
File.separator + SaveVarTo.AddPath(InciDate.getValue().toString());
}
else {homeDir.mkdirs();
// File.separator+homeDir.toString() - without it
fullRoute =
System.getProperty("user.home")+File.separator+homeDir.toString();}
System.out.println(fullRoute);
fileChooser.setInitialDirectory(new File(fullRoute));
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("XML Files", "*.xml"));
//sample of method
public class Variables{
public String AddPath(String name) {
if (!name.isEmpty()) {
//File nou = new File(getLastVisitedDirectory() +"\\" + name);
File nou = new File(name);
if (!nou.exists()) {
nou.mkdirs();
} else {
System.out.println("Folder already exists");
}
}
else{name = null;}
return name;
}}

String fullRoute = null;
File homeDir = new File(System.getProperty("user.home"));
if (SiteCo.getValue() !=null && InciDate.getValue() !=null) {
System.out.println(SaveVarTo.getMainFolder());
fullRoute = homeDir + File.separator + SaveVarTo.getMainFolder() +
File.separator + SiteCo.getValue().toString() +
File.separator + InciDate.getValue().toString();
} else {
fullRoute = homeDir.toString();
}
System.out.println(fullRoute);
File fhd = new File(fullRoute);
if (!fhd.exists())
fhd.mkdirs();
fileChooser.setInitialDirectory(fhd);
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("XML Files", "*.xml"));

Related

Can't move file , because is used by another process

I have many files in one directory, My app, must move some files to another directory. When I did this, first time works fine, but after that I have a exception like:
System.IO.IOException: process cannot access the file because another process is using the file.
I close windows explorer, or any program, avoiding the use of the file, but the problem persists.
I move files in this way:
private void ExtractosRemover()
{
string dirOrigen = '\\' + #"\" + servidor + #"\" + "EEQ_" + User.Identity.Name.ToString() + #"\";
string dirDestin = '\\' + #"\" + servidor + #"\" + "FacturasMatch_" + User.Identity.Name.ToString() + #"\";
try
{
foreach (GridViewRow grd_Row in this.gvwExtractosMatch.Rows)
{
File.Move(System.IO.Path.Combine(dirOrigen, clean(grd_Row.Cells[7].Text) + ".xml"), dirDestin);
}
}
catch (FileNotFoundException)
{
}
catch (IOException ioex)
{
lbl_UbiDevMensaje.Text = string.Empty;
lbl_UbiDevMensaje.Text = ioex.ToString();
}
}
For the names of the files, I read a gridview, and I add the extensions.
I don't know what is happening,
Please, I hope somebody can help me.
Thanks in advance.
best regards
Solved,
Using server map
private void ExtractosRemover()
{
string dirOrigen = "~/" + "EEQ_" + User.Identity.Name.ToString() + "/";
string dirDestin = "~/" + "FacturasMatch_" + User.Identity.Name.ToString() + "/";
foreach (GridViewRow grd_Row in this.gvwExtractosMatch.Rows)
{
try
{
File.Move( //Mover xml
Server.MapPath(dirOrigen + clean(grd_Row.Cells[7].Text) + ".xml"),
Server.MapPath(dirDestin + clean(grd_Row.Cells[7].Text) + ".xml")
);
File.Move( //Mover pdf
Server.MapPath(dirOrigen + "RIDE_" + clean(grd_Row.Cells[7].Text) + ".pdf"),
Server.MapPath(dirDestin + "RIDE_" + clean(grd_Row.Cells[7].Text) + ".pdf")
);
}
catch (FileNotFoundException)
{ }
}
}

java.util.zip.ZipEntry and apache compress ZipEntry corrupt some image files

I have been using Spring's multipart uploader controllers to upload and store entries from zipped files, but I am finding that the occaisional PNG file being corrupted, where instead of begginning with something like "PNG..." in its byte[], it starts with "fþ»ÀÃgÞÉ" or similar. This seems to happen to the same files on each run. I tried all of this using java.util.ZipEntry and then I tried Apache Compress and found that Apache compress corrupted different files to the Java 7 utility, but always the same files on subsequent runs.
The code (firstly java.util.zip.ZipEntry):
protected void processZipFile(String path, MultipartFile file, String signature) throws IOException {
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
File tempFile = new File(System.getProperty("user.dir") + "/" + file.getName() + df.format(new Date()));
file.transferTo(tempFile);
ZipFile zipFile = null;
try {
zipFile = new ZipFile(tempFile);
LOG.debug("Processing archive with name={}, size={}.", file.getName(), file.getSize());
final Enumeration<? extends ZipEntry> entries = zipFile.entries();
while ( entries.hasMoreElements() )
{
ZipEntry entry = entries.nextElement();
LOG.debug("Processing file={} is directory?={}.", entry.getName(), entry.isDirectory());
// we don't bother processing directories, and we don't process any resource fork info
// from Mac OS X (which does not seem to be transparent to ZipFile).
if (!(entry.isDirectory() || entry.getName().contains("__MACOSX") || entry.getName().contains(".DS_Store"))) {
// if the entry is a file, extract it
Content contentToSave = null;
if(entry.getName().contains("gif") || entry.getName().contains("png") || entry.getName().contains("jpeg")) {
byte[] bytes = readInputStream( zipFile.getInputStream( entry ), entry.getSize() );
LOG.debug("{} is of inflated-length={} from compressed-length={}",
entry.getName(), bytes.length, entry.getCompressedSize());
if(entry.getName().contains("gif")) {
contentToSave = Content.makeImage(path + entry.getName(), Content.GIF, signature, bytes);
} else if (entry.getName().contains("png")) {
contentToSave = Content.makeImage(path + entry.getName(), Content.PNG, signature, bytes);
} else if (entry.getName().contains("jpeg")) {
contentToSave = Content.makeImage(path + entry.getName(), Content.JPEG, signature, bytes);
}
} else {
InputStream is = zipFile.getInputStream(entry);
if (entry.getName().contains("json")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.JSON, signature, convertStreamToString(is));
} else if (entry.getName().contains("js")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.JS, signature, convertStreamToString(is));
} else if (entry.getName().contains("css")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.CSS, signature, convertStreamToString(is));
} else if (entry.getName().contains("xml")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.XML, signature, convertStreamToString(is));
} else if (entry.getName().contains("html")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.HTML, signature, convertStreamToString(is));
}
}
contentService.putOrReplace(contentToSave);
LOG.info("Persisted file: {} from uploaded version.", contentToSave.getName());
}
}
} catch (ZipException e) {
// If I can't create a ZipFile, then this is not a zip file at all and it cannot be processed
// by this method. Its pretty dumb that there's no way to determine whether the contents are zipped through
// the ZipFile API, but that's just one of its many problems.
e.printStackTrace();
LOG.error("{} is not a zipped file, or it is empty", file.getName());
} finally {
zipFile = null;
}
tempFile.delete();
}
And now the same thing for org.apache.commons.compress.archivers.zip.ZipFile:
protected void processZipFile(String path, MultipartFile file, String signature) throws IOException {
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
File tempFile = new File(System.getProperty("user.dir") + "/" + file.getName() + df.format(new Date()));
file.transferTo(tempFile);
ZipFile zipFile = null;
try {
zipFile = new ZipFile(tempFile);
LOG.debug("Processing archive with name={}, size={}.", file.getName(), file.getSize());
final Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
while ( entries.hasMoreElements() ) {
ZipArchiveEntry entry = entries.nextElement();
LOG.debug("Processing file={} is directory?={}.", entry.getName(), entry.isDirectory());
// we don't bother processing directories, and we don't process any resource fork info
// from Mac OS X (which does not seem to be transparent to ZipFile).
if (!(entry.isDirectory() || entry.getName().contains("__MACOSX") || entry.getName().contains(".DS_Store"))) {
// if the entry is a file, extract it
Content contentToSave = null;
if(entry.getName().contains("gif") || entry.getName().contains("png") || entry.getName().contains("jpeg")) {
byte[] bytes = readInputStream( zipFile.getInputStream( entry ), entry.getSize() );
LOG.debug("{} is of inflated-length={} from compressed-length={}",
entry.getName(), bytes.length, entry.getCompressedSize());
if(entry.getName().contains("gif")) {
contentToSave = Content.makeImage(path + entry.getName(), Content.GIF, signature, bytes);
} else if (entry.getName().contains("png")) {
contentToSave = Content.makeImage(path + entry.getName(), Content.PNG, signature, bytes);
} else if (entry.getName().contains("jpeg")) {
contentToSave = Content.makeImage(path + entry.getName(), Content.JPEG, signature, bytes);
}
} else {
InputStream is = zipFile.getInputStream(entry);
if (entry.getName().contains("json")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.JSON, signature, convertStreamToString(is));
} else if (entry.getName().contains("js")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.JS, signature, convertStreamToString(is));
} else if (entry.getName().contains("css")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.CSS, signature, convertStreamToString(is));
} else if (entry.getName().contains("xml")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.XML, signature, convertStreamToString(is));
} else if (entry.getName().contains("html")) {
contentToSave = Content.makeFile(path + entry.getName(), Content.HTML, signature, convertStreamToString(is));
}
}
contentService.putOrReplace(contentToSave);
LOG.info("Persisted file: {} from uploaded version.", contentToSave.getName());
}
}
} catch (ZipException e) {
e.printStackTrace();
LOG.error("{} is not a zipped file, or it is empty", file.getName());
} catch (IOException e) {
e.printStackTrace();
LOG.error("{} is not a file, or it is empty", file.getName());
} finally {
zipFile = null;
}
tempFile.delete();
}
The two called methods are:
private static byte[] readInputStream( final InputStream is, final long length ) throws IOException {
final byte[] buf = new byte[ (int) length ];
int read = 0;
int cntRead;
while ( ( cntRead = is.read( buf, 0, buf.length ) ) >=0 )
{
read += cntRead;
}
return buf;
}
and:
public String convertStreamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder(2048);
char[] read = new char[128];
try (InputStreamReader ir = new InputStreamReader(is, StandardCharsets.UTF_8)) {
for (int i; -1 != (i = ir.read(read)); sb.append(read, 0, i));
}
// need to remove the ? at teh beginning of some files. This comes from the UTF8 BOM
// that is added to some files saved as UTF8
String out = sb.toString();
String utf8Bom = new String(new char[]{'\ufeff'});
if(out.contains(utf8Bom)) {
out = out.replace(utf8Bom,"");
}
return out;
}
The second one is, of course, not likely part of the problem.
I have googled around and it looks like issues similar to this have been found, but its always been some outside issue. Does anyone know why this might be the case?
I have re-edited some images and found that if I change the image to black and white, or change the hue of the whole image, the problem goes away, but if I add a border or change a single colour the problem remains. It looks like a particular arrangement of bytes in some files tickles a bug in whatever underlying API that both Java's own and Apache's compressed file readers use, but that's just speculation.
EDIT: additional usage shows that the corruption happens in gifs over 10K in size, so perhaps this has something to do with the bug? I have tried arbitrarily doubling the size of the buffer in the call to ReadInputStream(), but it did nothing except overflow the blob size in MySQL in particularly large images (49K became 98K, which was too big).
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'encoded_content' at row 1
My finding is that this issue arise when the 'packed size' is larger that the actual size, this can happen with png files for example which are already 'zipped' them selves.

How to create zip file in asp.net

I need to create zip file from the folder, path:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild\HOST
within that host folder there are 7 txt files.
I want to create zip file HOST.zip in the folder above:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild
I've used Ionic ZIP for this in our own projects.
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
}
public class Ziper
{
public static string MapPathReverse(string fullServerPath)
{
return #"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath, String.Empty);
}
public static void Zip(HttpResponse Response, HttpServerUtility Server, string[] pathes)
{
Response.Clear();
Response.BufferOutput = false; // false = stream immediately
System.Web.HttpContext c = System.Web.HttpContext.Current;
//String ReadmeText = String.Format("README.TXT\n\nHello!\n\n" +
// "This is text for a readme.");
string archiveName = String.Format("archive-{0}.zip",
DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + archiveName);
var path = Server.MapPath(#"../Images/TempFile/TempFile" + DateTime.Now.Ticks);
if (Directory.Exists(path) == false)
Directory.CreateDirectory(path);
var pathzipfile = Server.MapPath(#"../Images/TempFile/zip_" + DateTime.Now.Ticks + ".zip");
for (int i = 0; i < pathes.Length; i++)
{
if (File.Exists(pathes[i]))
{
string dst = Path.Combine(path, Path.GetFileName(pathes[i]));
File.Copy(pathes[i], dst);
}
}
if (File.Exists(pathzipfile))
File.Delete(pathzipfile);
ZipFile.CreateFromDirectory(path, pathzipfile);
{
byte[] bytes = File.ReadAllBytes(pathzipfile);
Response.OutputStream.Write(bytes, 0, bytes.Length);
}
Response.Close();
File.Delete(pathzipfile);
Directory.Delete(path, true);
}
public Ziper()
{
}
}

Failed to upload image saved on server

I am saving an image file at server. The file is successfully saved at the server but when I try to assign the URL of that file to the image control, the image is failed to load but when I assign that url directly in to HTML code, the file is loaded successfully. Please guide me Where I am making a mistake. Below are the code for my file upload and fetch URL.
Code For File Upload
private string ImageUpload()
{
try
{
string FileName = UpldCompanyLogo.FileName;
if (UpldCompanyLogo.HasFile)
{
string SaveFilePath = Server.MapPath("~\\Upload\\")+FileName;
if (!Directory.Exists(Server.MapPath("~\\Upload\\")))
Directory.CreateDirectory(Server.MapPath("~\\Upload\\"));
if (File.Exists(SaveFilePath))
{
File.Delete(SaveFilePath);
}
if(File.Exists(ViewState["ImageURL"].ToString()))
{
File.Delete(ViewState["ImageURL"].ToString());
}
UpldCompanyLogo.PostedFile.SaveAs(SaveFilePath);
}
return FileName;
}
catch (Exception ex)
{
if (ex.HelpLink == null)
ex.HelpLink = "Controls_Company103>>" + ex.Message;
else
ex.HelpLink = "Controls_Company103>>" + ex.HelpLink;
lblMessage.Text = ex.HelpLink;
lblMessage.CssClass = "ERROR";
return null;
}
}
This is the code to get the image URL
if (dtCompany != null)
{
if (dtCompany.Rows.Count > 0)
{
txtCompanyName.Text = dtCompany.Rows[0]["CompanyName"].ToString();
txtAddress.Text = dtCompany.Rows[0]["Address"].ToString();
txtPhoneNo.Text = dtCompany.Rows[0]["PhoneNumber"].ToString();
txtFaxNo.Text = dtCompany.Rows[0]["FaxNumber"].ToString();
string path = Server.MapPath("~\\Upload\\");
imgLogo.ImageUrl = path + dtCompany.Rows[0]["CompanyLogo"].ToString();
}
}
If I copy and past the retrieved path in the browser, the image is found there at the server.
You may try this:
if (dtCompany != null)
{
if (dtCompany.Rows.Count > 0)
{
txtCompanyName.Text = dtCompany.Rows[0]["CompanyName"].ToString();
txtAddress.Text = dtCompany.Rows[0]["Address"].ToString();
txtPhoneNo.Text = dtCompany.Rows[0]["PhoneNumber"].ToString();
txtFaxNo.Text = dtCompany.Rows[0]["FaxNumber"].ToString();
imgLogo.ImageUrl = Page.ResolveUrl("~\\Upload\\") + dtCompany.Rows[0]["CompanyLogo"].ToString();
}
}

Dynamically change colour of KML polygon in Google Maps API v3

I'm using Google Maps v3 API to load a KML layer and want to be able to change the colour of the KML from its default blue without having to edit the KML file itself. Is this possible using JavaScript or some other means?
Unfortunately can't post a link, but it's pretty standard stuff.
var map = new google.maps.Map(document.getElementById("mymap"), { some options });
var regionLayer = new google.maps.KmlLayer("http://.../some.kml");
regionLayer.setMap(map);
From my understanding of the documentation, 'no', but it's not especially clear. I'm trying to do a similar thing (but update the colour of mouseover/mouseout).
The KML file is loaded by the Google servers, parsed and sent along to your javascript object to be applied to the map, so, by the time your javascript KMLLayer sees it, it's all sorted out.
You may be able to do something with Styles and styleUrl. This is supposed to allow you to set a number of different styles that can then be applied at runtime, however, I haven't got it working.
I have done this by creating a web service which reads in a KML file to a string, inserts a style section to the beginning of the KML string, and also a styleURL to each uniquely named placemark. It's fairly simple to amend the markup using a .net web service and write it back out to the server you have hosting the web service.
For example this uses a class which contains placemark IDs and a colour flag:
public string KMLStyler(string URL, string URLName, Data[] MyData)
{
try
{
ReadFile(URL);
string NewKML = ReadFile(URL);
string RedStyle = "<Style id=\"red\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F0000FF</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string BlackStyle = "<Style id=\"black\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F7F7F7F</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string GreenStyle = "<Style id=\"green\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F00FF00</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string BlueStyle = "<Style id=\"blue\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F7F7F7F</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
//add styles to top
int EndID = 0;
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, RedStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, BlackStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, GreenStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, BlueStyle);
//add each style to each placemark
foreach (Data MyDataSingle in MyData)
{
int NamePos = NewKML.IndexOf(MyDataSingle.Name);
if (NamePos == -1) throw new Exception("Did not find '" + MyDataSingle.Name + "' within File");
NamePos += MyDataSingle.Name.Length + 7;
int MultiGeometryStartPos = NewKML.IndexOf("<MultiGeometry>", NamePos);
int MultiGeometryEndPos = NewKML.IndexOf("</MultiGeometry>", NamePos);
int PolygonStartPos = NewKML.IndexOf("<Polygon>", NamePos);
int InsertPos = 0;
if (MultiGeometryStartPos < PolygonStartPos)
{
if (MultiGeometryStartPos != -1)
{
InsertPos = MultiGeometryStartPos;
}
else
{
InsertPos = PolygonStartPos;
}
}
else
{
InsertPos = PolygonStartPos;
}
if (MyDataSingle.Red)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#red</styleUrl>");
}
if (MyDataSingle.Black)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#black</styleUrl>");
}
if (MyDataSingle.Green)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#green</styleUrl>");
}
if (MyDataSingle.Blue)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#blue</styleUrl>");
}
}
string NewFileName = WriteFile(NewKML, URLName);
return NewFileName;
}
catch (Exception ex)
{
return ex.ToString();
}
}
public string WriteFile(string KMLData, string URLName)
{
string FileName = "http:\\blah.co.uk\blah.kml";
StreamWriter writer = new StreamWriter("C:/inetpub/blah.kml");
writer.Write(KMLData);
writer.Flush();
writer.Close();
return FileName;
}
public string ReadFile(string URL)
{
string File = "";
StreamReader reader = new StreamReader(WebRequest.Create(URL).GetResponse().GetResponseStream());
string line;
while ((line = reader.ReadLine()) != null)
{
File += line;
}
return File;
}

Resources