I am using the below code to upload image. The problem is that after uploading the image i cant change the file permission. my file permission set by default is rw-r--r-- (0644). Is it possible to change the file permission or set it as 0777 by default? It works fine in my local system. But not able to change the permission in my linux server.
<%
try
{
int filesize=0;
String fieldname="",fieldvalue="",filename="",content="",bookid="",bkdescription="";
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
fieldname = item.getFieldName();
fieldvalue = item.getString();
if(fieldname.equals("homeid")){
bookid=fieldvalue;
}
if(fieldname.equals("bkdescription")){
bkdescription=fieldvalue;
}
} else {
try{
fieldname = item.getFieldName();
filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
filesize=(int)item.getSize();
filename="literal_"+bookid+".jpg";
if(filesize>0){
byte[] b=new byte[filesize];
int c=0;
File f=new File(getServletConfig().getServletContext().getRealPath("/")+"/imagesX");
String filePah=getServletConfig().getServletContext().getRealPath("/")+"/imagesX";
if(f.isDirectory())
{
String fl[]=f.list();
for(int i=0;i<fl.length;i++)
{
File fd=new File(getServletConfig().getServletContext().getRealPath("/")+"/imagesX/"+fl[i]);
if(fd.getName().equals(filename))
fd.delete();
}
}
if(!f.exists())
{
new File(filePah).mkdir();
f.mkdir()
}
java.io.FileOutputStream fout=new java.io.FileOutputStream(getServletConfig().getServletContext().getRealPath("/")+"/imagesX/"+filename);
while((c = filecontent.read(b)) != -1 )
{
fout.write(b, 0, c);
}
fout.close();
filecontent.close();
}
}catch (Exception e) {
System.out.println("Exception in creation of file :"+e);
}
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
}
catch(Exception exp)
{
out.println(exp);
}
%>
You cannot change the file permission from inside java code.
Your system's default umask is set to 0644 for new file. It wouldn't be good idea to change the default umask.
What you need is to do is set the permission of your directory to 0777 and then redefine your directory's ACL to recursive, so all new file created inside will inherit the same permission.
Heres a link which shows how to go about -
https://superuser.com/questions/151911/how-to-make-new-file-permission-inherit-from-the-parent-directory
An alternative solution is to change the permissions externally with a system command, chmod.
Example:
public static void runCmd (String[] cmd) {
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader r = new BufferedReader(
new InputStreamReader (
p.getInputStream()
)
);
} catch(Exception e) {
}
}
runCmd(new String[] {
"/bin/chmod",
"755",
"/path/to/your/script"
});
P.S. were you also trying to call Java from a stored proc in an Oracle database?
Related
I am trying to download multiple files from gridView by selecting checkbox( on SharePoint site), Actually it will fetch the file using SharePoint ID from list in the SharePoint site and write it my documents folder and then zip it.
all the functionalities working in development server, I am able to download as zip file in the my documents folder in the system.
Note: The same code deployed to QA environment, I tried to download it, but I am getting the 403 forbidden error. I could not able to download it.
Could someone please help me on this issue.
protected void btnDownload_Click(object sender,EventArgs e)
{
int counter=0;
bool dataSel=false;
for(int i=0;i<gridviewestimates.rows.count; i++)
{
checkbox chkselect=
(checkboc)gridviewestimates.rows[i].findcontrol("chkselect");
try
{
if(chkselect.checked)
{
counter++;
Label lblspitemid=
(label)gridviewestimates.rows[i].findcontrol("lblspitemid");
addfiletodictionary("Estimate
Documents",convert.ToInt32(lblSPItemId.Text));
dataSel=true;
}
}
catch(Exception ex) {throw ex;}
}
if(counter <=0)
{
page.clientscript.registerstartupscript(GetType(),"msgbox","alert('Please
select the checkbox to download files');",true);
}
if(dataSel)
{
callzipmethod();
}
}
private void callzipmethod()
{
string path=path.combine(environment.getfolderpath
(environment.specialfolder.mydocument),"KKM Estimate Documents");
try
{
string sourcePath=path;
string
docPath=environment.getfolderpath(environment.specialfolder.mydocuments);
string
destinationPath=docPath+"\\"+"KKM_Estimates_"+datetime.now.tostring
("MM_dd_yyyy HH.mm tt")+".zip";
string[] filenames=Directory.GetFiles(sourcePath);
using(ZipOutputStream outputstream=new ZipOutputStream(File.Create
(destionationPath)))
{
outputstream.setlevel(9);
byte[] buffer=new byte[40000];
foreach(string file in filenames)
{
ZipEntry entry=new ZipEntry(Path.GetFileName(file));
entry.DateTime=DateTime.Now;
outputstream.PutNextEntry(entry);
using(FileStream fs=File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes=fs.Read(buffer,0,buffer.Length);
outputstream.Write(buffer,0,sourceBytes);
}while(sourceBytes > 0);
}
}
outputstream.Finish();
outputstream.Close();
Page.clientscript.registerstartupscript(GetType()."msgbox","alert
('KKM_Estiates_
"+DateTime.Now.ToString("MM_dd_yyyy HH.mm tt")+ ".zip downloaded
inside MyDocuments folder');",true);
}
}
catch(Exception ex)
{
throw ex;
}
string[] files=Directory.GetFiles(path);
foreach(string file in files)
{
var name=new FileInfo(file).Name;
File.Delete(file);
}
if(Directory.Exists(path))
{
Directory.Delete(path);
}
}
private void AddFileToDictionary(string libraryName,int documentId)
{
SPSite site=new SPSite(SPContext.Current.Web.Url);
SPWeb web=site.OpenWeb();
SPList docLib=web.Lists[libraryName];
SPListItem item=docLib.GetItemById(documentId);
SPFile docFile=item.File;
byte[] b=docFile.OpenBinary();
string date=DateTime.Now.ToString("MM_dd_yyyy HH.mm tt");
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "KKM Estimate Documents"));
string path=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "KKM Estimate Documents");
string fullPath=path+"\\"+docFile.Name;
FileStream stream=new FileStream(fullPath,FileMode.Create);
stream.Write(b,0,b.length);
stream.Close();
}
I our app (Xamarin C#) we download files from a server. At the end of a succeful download we get the URI to the newly-downloaded file and from the URI we get the file path:
Android.Net.Uri uri = downloadManager.GetUriForDownloadedFile(entry.Value);
path = u.EncodedPath;
In Android 4.4.2 and in Android 5 the uri and path look like this:
uri="file:///storage/emulated/0/Download/2.zip"
path = u.EncodedPath ="/storage/emulated/0/Download/2.zip"
We then use path to process the file.
The problem is that in Android 6 (on a real Nexus phone) we get a completely different uri and path:
uri="content://downloads/my_downloads/2802"
path="/my_downloads/2802"
This breaks my code by throwing a FileNotFound exception. Note that the downloaded file exists and is in the Downloads folder.
How can I use the URI I get from Android 6 to get the proper file path so I can to the file and process it?
Thank you,
donescamillo#gmail.com
I didn't get your actual requirement but it looks like you want to process file content. If so it can be done by reading the file content by using file descriptor of downloaded file. Code snippet as
ParcelFileDescriptor parcelFd = null;
try {
parcelFd = mDownloadManager.openDownloadedFile(downloadId);
FileInputStream fileInputStream = new FileInputStream(parcelFd.getFileDescriptor());
} catch (FileNotFoundException e) {
Log.w(TAG, "Error in opening file: " + e.getMessage(), e);
} finally {
if(parcelFd != null) {
try {
parcelFd.close();
} catch (IOException e) {
}
}
}
But I am also looking to move or delete that file after processing.
May you an build your URI with the download folder :
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toURI();
It's work. #2016.6.24
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals( action)) {
DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor c = downloadManager.query(query);
if(c != null) {
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String downloadFileUrl = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
startInstall(context, Uri.parse(downloadFileUrl));
}
}
c.close();
}
}
}
private boolean startInstall(Context context, Uri uri) {
if(!new File( uri.getPath()).exists()) {
System.out.println( " local file has been deleted! ");
return false;
}
Intent intent = new Intent();
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction( Intent.ACTION_VIEW);
intent.setDataAndType( uri, "application/vnd.android.package-archive");
context.startActivity( intent);
return true;
}
I'm trying to get and edit the code of all the html-files in the project
i found a way to loop over all ProjectItems
IEnumerator Projects = _applicationObject.Solution.Projects.GetEnumerator();
while (Projects.MoveNext())
{
IEnumerator Items = ((Project)Projects.Current).ProjectItems.GetEnumerator();
Queue<ProjectItem> ProjectItems = new Queue<ProjectItem>();
while (Items.MoveNext())
{
ProjectItem SubItem = (ProjectItem)Items.Current;
try
{
if (SubItem.Document != null) DocumentIndex.Add(SubItem.Document);
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
ProjectItems.Enqueue(SubItem);
}
//follow the tree down
while (ProjectItems.Count != 0)
{
ProjectItem ProjectItem = ProjectItems.Dequeue();
if (ProjectItem.ProjectItems != null)
{
foreach (ProjectItem SubItem in ProjectItem.ProjectItems)
{
ProjectItems.Enqueue(SubItem);
try
{
try
{
SubItem.Open(SubItem.Kind);
DocumentIndex.Add(SubItem.Document);
}catch(Exception Ex){
Console.WriteLine(Ex.Message);
}
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
}
}
}
}
now i can't get to the code of the files that are not open in an editor window.
how do i get and edit the code of "not opened" projectItems?
how do i detect if a file is a code file? (eg: .cs, .html, .htm, .asp, ....
You must open the ProjectItem that you want to read or edit
DTE dte = (DTE)Package.GetGlobalService(typeof(DTE));
var project = dte.Solution.Projects.Item(1);
var projectItems = project.ProjectItems;
var anyItem = projectItems.Item(0);
Window anyItemWindow = anyItem.open()
var selection = anyItem.Document.Selection as TextSelection;
selection.SelectAll();
Console.WriteLine(selection.Text) // All code
anyItem.Document.Close() //Close Document
if you don't open the ProjectItem anyItem.Doument is null.
Note: selection.Insert("") can be used to change the code
How to query Folder Size in remote computer through WMI and C#.
I need to find the each User's folder size in C:\Users in remote System through WMI.
I tried Win32_Directory , CMI_DataFile but not able to find the desired answer.
Please help!!
To get the size of a folder using the WMI, you must iterate over the files using the CIM_DataFile class and then get the size of each file from the FileSize property.
Try this sample (this code is not recursive, I leave such task for you).
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
// Directory is a type of file that logically groups data files 'contained' in it,
// and provides path information for the grouped files.
static void Main(string[] args)
{
try
{
string ComputerName = "localhost";
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string Drive= "c:";
//look how the \ char is escaped.
string Path="\\\\FolderName\\\\";
UInt64 FolderSize = 0;
ObjectQuery Query = new ObjectQuery(string.Format("SELECT * FROM CIM_DataFile Where Drive='{0}' AND Path='{1}' ", Drive, Path));
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0}", (string)WmiObject["FileName"]);// String
FolderSize +=(UInt64)WmiObject["FileSize"];
}
Console.WriteLine("{0,-35} {1,-40}", "Folder Size", FolderSize.ToString("N"));
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}
I want to make the application where I can get all the images no matter whether it is in phone or in external memory. I want to import all that images in my application. How can it be possible? I came to know that it is possible through file connection. But not getting exact idea.
Get all the file system roots using FileSystemRegistry.listRoots()
Open connection to each root in turn using FileConnection fconn = (FileConnection)Connector.open(root)
List the folder using fconn.list().
For each entry in the list, if it ends with an image extension (file.getName().endsWith(".png") etc), then it's an image.
If the entry is a folder (file.isDirectory() returns true) then use fconn.setFileConnection(folder) to traverse into that directory/
Do the same recursively for all folders in all roots.
Here is a code snippet I once used for my application. It more or less does the same in funkybros steps.
protected void showFiles() {
if (path == null) {
Enumeration e = FileSystemRegistry.listRoots();
path = DATAHEAD; //DATAHEAD = file:///
setTitle(path);
while (e.hasMoreElements()) {
String root = (String) e.nextElement();
append(root, null);
}
myForm.getDisplay().setCurrent(this);
} else {
//this if-else just sets the title of the Listing Form
if (selectedItem != null) {
setTitle(path + selectedItem);
}
else {
setTitle(path);
}
try {
// works when users opens a directory, creates a connection to that directory
if (selectedItem != null) {
fileConncetion = (FileConnection) Connector.open(path + selectedItem, Connector.READ);
} else // works when presses 'Back' to go one level above/up
{
fileConncetion = (FileConnection) Connector.open(path, Connector.READ);
}
// Check if the selected item is a directory
if (fileConncetion.isDirectory()) {
if (selectedItem != null) {
path = path + selectedItem;
selectedItem = null;
}
//gathers the directory elements
Enumeration files = fileConncetion.list();
while (files.hasMoreElements()) {
String file = (String) files.nextElement();
append(file, null);
}
//
myForm.getDisplay().setCurrent(this);
try {
if (fileConncetion != null) {
fileConncetion.close();
fileConncetion = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}//if (fileConncetion.isDirectory())
else {
System.out.println(path);
//if it gets a file then calls the publishToServer() method
myForm.publishToServer();
}