What permission do I need to read zip files - android 11? - android-permissions

I'm working on zip files (android-studio-java)
and I tried below solutions:
android.permission.READ_EXTERNAL_STORAGE ---> failed (no read access for zip file)
Access documents and other files ---> failed (no read access for zip file)
android.permission.MANAGE_EXTERNAL_STORAGE ---> passed
My question is: Is there any lower level of permission for zip files or I have to use MANAGE_EXTERNAL_STORAGE?
Thank you,

Actually you can use ACTION_OPEN_DOCUMENT, no need for MANAGE_EXTERNAL_STORAGE
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// you can set here the type you need setType(application/zip)
intent.setType("*/*");
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(intent, ZIP_READ_CODE);
OnActivityResult
if (resultCode == RESULT_OK) {
case ZIP_READ_CODE: {
Uri uri = data.getData();
File file = null;
try {
file = read_uri_to_file(uri);
} catch (IOException e) {
//handle error
}
}
}
Read the File:
private File read_uri_to_file(Uri uri) throws IOException {
String displayName = "";
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor != null && cursor.moveToFirst()){
try {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}finally {
cursor.close();
}
}
//create temp file to copy and handle selected file
File file = File.createTempFile(
FilenameUtils.getBaseName(displayName),
"."+FilenameUtils.getExtension(displayName)
);
//copy selected file, to a temp file
InputStream inputStream = getContentResolver().openInputStream(uri);
FileUtils.copyInputStreamToFile(inputStream, file);
return file;
}

Related

How to checkout a file using sharpsvn

I tried to checkout a file using sharpsvn from remote repository,but i found sharpsvn can not to checkout single file only checkout folder,please help me to know how to checkout a file?Thx.
My code
SvnUpdateResult result;
SvnCheckOutArgs checkoutArgs = new SvnCheckOutArgs();
string target = txtRepository.Text.Trim();
SvnUriTarget url = new SvnUriTarget(target);
string fileName = url.FileName;
string path = folder + "\\" + fileName;
using (SvnClient client = new SvnClient())
{
try
{
client.CheckOut(url,txtLocalFilePath.Text.Trim(),out result);//.Update(path,updateArgs,out result);
if (result != null)
{
WriteCheckOutTime(txtRepository.Text.Trim(), result.Revision);
MessageBox.Show("Check out success!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
catch (SvnException svnException)
{
MessageBox.Show(svnException.Message + "Check out error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch (UriFormatException uriException)
{
MessageBox.Show(uriException.Message + "Check out error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
The smallest element you can check out with Subversion is a directory. It is not possible to check out a single file.
You can check out a directory, but leave it empty, via the Sparse Directories feature. Then update only the file you're interested in. But you must start with a directory.
FYI if you want to checkout empty use following syntax
//first define args
SvnCheckOutArgs args = new SvnCheckOutArgs();
// then for checkout only forlder empty
args.Depth = SvnDepth.Empty;
//checkout folder
client.CheckOut(url,txtLocalFilePath.Text.Trim(),args,out result)

signed applet, downloading file from server and place it in the file system

I have signed applet, I want to download any kind of file from the server and place it in the file system using the applet.
Please give some pointer.
Thanks in advance.
You'll have to write servlet for this. Because servlets can access to server local file system and get files you want for your applet :)
Make bound like a
applet <-servlet<-server
Good luck
The applet need to be signed to access the file system.
public String downloadFile(final String filename) {
return (String)AccessController.doPrivileged(new PrivilegedAction(){
public Object run() {
try {
// downloadURL is the server URL say http://localhost/downloads
// filename is a file want to download from the server
// localpath is the path you want to download in the file system
URL finalURL = new URL(downloadURL + filename);
ReadableByteChannel rbc = Channels.newChannel(finalURL.openStream());
FileOutputStream fos = new FileOutputStream("/"+localpath.replace("\\","/") + filename);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
fos.close();
return "true";
}catch (ConnectException ce) {
e.printStackTrace();
return "false";
}
catch (Exception e) {
e.printStackTrace();
return "false";
}
}
});
}

How to get alerts from action in asp.net mvc

as far as I know we can not call the javascript method in controller's action method. but how to consider that a particular code line get executed ? As i asked earlier here
we must have to get acknowledgment that line number so and so get executed. see this action in my controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult uploadfile(FormCollection fc)
{
UserMaster objUMaster = objAM.GetUser(new Guid(fc["userIdForFile"].ToString()));
try
{
string imagename = "";
//Check for files uploaded here.
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
imagename = objUMaster.UserId.ToString() + file.FileName;
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Content/UserUploads"), objUMaster.UserId.ToString() + Path.GetFileName(file.FileName));
file.SaveAs(filePath);
string filePathThumb = Path.Combine(HttpContext.Server.MapPath("../Content/UserUploads/Thumbnails"), objUMaster.UserId.ToString() + Path.GetFileName(file.FileName));
var fl = Request.Files.Get(inputTagName);
Stream strm = fl.InputStream;
Image img = Image.FromStream(strm);
ResizeAndSaveHighQualityImage(img, 120, 120, filePathThumb, 100);
}
}
objUMaster.ProfilePhoto = imagename;
objAM.Save();
return RedirectToAction("EditProfile", new { id = objUMaster.UserId });
}
catch (Exception ex)
{
//SendEmail(ex.Message);
string strPath = HttpContext.Server.MapPath("../Content/UserUploads");
StreamWriter SW;
SW = System.IO.File.CreateText(strPath+"/log.txt");
SW.WriteLine(ex.Message.ToString());
SW.Close();
return RedirectToAction("EditProfile", new { id = objUMaster.UserId });
}
}
Here I am trying to upload the image in my domains file system (dir). but I want get alert so that I can confirm , this lie get executed successfully. because nothing happening as expected from this action. so can we call Javascript's "alert", or something else remedy?
Some pointers to help you:
See if Network service/account under which your application is running has permission on the location where you are saving your file.
Besides this to make sure that your file is saved, after save call you can make another call File.IsExist. If it exists then you can log the success/failure in some log file. Wouldn't that work for you?

How to test if a URL from an Eclipse bundle is a directory?

I'm trying to populate a directory from the contents of a bundle built into my plug-in. The following code works when the bundle is a file-system, but fails when the bundle is a JAR.
What is the best way to test if a URL is a directory? Or is there a completely different, better approach for creating a file structure from a resource bundle?
static private void bundleCopy(String dir, String destination) throws IOException {
Bundle bundle = com.mds.apg.Activator.getDefault().getBundle();
for (#SuppressWarnings("unchecked")
Enumeration<URL> en = (Enumeration<URL>) bundle.findEntries(dir, "*", true);
en.hasMoreElements();) {
URL url = en.nextElement();
String toFileName = destination + url.getPath().substring(dir.length());
File toFile = new File(toFileName);
InputStream in;
try {
in = url.openStream();
} catch (FileNotFoundException e) {
// this exception get thrown for file system directories but not for jar file ones
if (!toFile.mkdir()) {
throw new IOException("bundleCopy: " + "directory Creation Failed: "
+ toFileName);
}
continue;
}
FileCopy.coreStreamCopy(in, toFile);
}
}
I found an answer:
The key point is that the Enumeration entries for directories end in a '/'.
The following correctly distinguishes between directories and files for both JARs and file systems:
static private void bundleCopy(String dir, String destination)
throws IOException, URISyntaxException {
Bundle bundle = com.mds.apg.Activator.getDefault().getBundle();
Enumeration<URL> en = bundle.findEntries(dir, "*", true);
while (en.hasMoreElements()) {
URL url = en.nextElement();
String pathFromBase = url.getPath().substring(dir.length()+1);
String toFileName = destination + pathFromBase;
File toFile = new File(toFileName);
if (pathFromBase.lastIndexOf('/') == pathFromBase.length() - 1) {
// This is a directory - create it and recurse
if (!toFile.mkdir()) {
throw new IOException("bundleCopy: " + "directory Creation Failed: " + toFileName);
}
} else {
// This is a file - copy it
FileCopy.coreStreamCopy(url.openStream(), toFile);
}
}
}
You could try something like new File(FileLocator.resolve(url).toUri()) to convert from the Eclipse-specific URL to one using a native Java protocol.

How can i iterate throught my emf model from a gmf editor without parsing the xml model file?

I have successfully created a GMF editor which draws models based on my EMF model.What i wanted to do is to iterate through my model's EClasses .Can this be achieved at runtime through my plugin code without having to read the xml file that the gmf editor creates ?Is there such an API from EMF?
When you generate test code from the genmodel file then inside the XYZ.test plugin there is such type of code that i was searching.It traverses through the xmi file of your model
// Create a resource set to hold the resources.
//
ResourceSet resourceSet = new ResourceSetImpl();
// Register the appropriate resource factory to handle all file extensions.
//
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put
(Resource.Factory.Registry.DEFAULT_EXTENSION,
new XMIResourceFactoryImpl());
// Register the package to ensure it is available during loading.
//
resourceSet.getPackageRegistry().put
(XYZmetamodelPackage.eNS_URI,
XYZmetamodelPackage.eINSTANCE);
// If there are no arguments, emit an appropriate usage message.
//
if (args.length == 0) {
System.out.println("Enter a list of file paths or URIs that have content like this:");
try {
Resource resource = resourceSet.createResource(URI.createURI("http:///My.metamodel"));
ModelObject root = atagmetamodelFactory.eINSTANCE.createModelObject();
resource.getContents().add(root);
resource.save(System.out, null);
}
catch (IOException exception) {
exception.printStackTrace();
}
}
else {
// Iterate over all the arguments.
//
for (int i = 0; i < args.length; ++i) {
// Construct the URI for the instance file.
// The argument is treated as a file path only if it denotes an existing file.
// Otherwise, it's directly treated as a URL.
//
File file = new File(args[i]);
URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath()): URI.createURI(args[i]);
try {
// Demand load resource for this file.
//
Resource resource = resourceSet.getResource(uri, true);
System.out.println("Loaded " + uri);
// Validate the contents of the loaded resource.
//
for (EObject eObject : resource.getContents()) {
Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eObject);
if (diagnostic.getSeverity() != Diagnostic.OK) {
printDiagnostic(diagnostic, "");
}
}
}
catch (RuntimeException exception) {
System.out.println("Problem loading " + uri);
exception.printStackTrace();
}
}
}
}