Delete a file inside a folder in Google cloud storage - google-cloud-storage

My wish is very simple and basic. However, I can't find any working/clear answer for it :D
I want to know how to delete a file inside a folder in Google Cloud storage.
If let's say I have a bucket name of xxxx.appspot.com and I have a folder inside called images and I have an image inside this folder (E.g. 123.jpg) which I want to delete.
This is the code I wrote, however it didn't delete it:
String bucketName = "xxxx.appspot.com";
GcsService gcsService = GcsServiceFactory.createGcsService();
gcsService.delete(new GcsFilename(bucketName,"images/123.jpg"));
Did I miss anything?
Thanks in Advance!

You can find some code samples in the documentation. In short, what you want to achieve can be done in Java using a couple of lines of code, given that you have the right permissions:
BlobId b = BlobId.of(bucketName, blobName);
boolean deleted = storage.delete(b);

The correct answer as of 2022 is the following:
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class DeleteObject {
public static void deleteObject(String projectId, String bucketName, String objectName) {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
// The ID of your GCS object
// String objectName = "your-object-name";
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
storage.delete(bucketName, objectName);
System.out.println("Object " + objectName + " was deleted from " + bucketName);
}
}
Example taken from this page

Related

How to create a folder with % character on SharePoint 2019 using rest calls via postman?

I want to create a folder with % character on SharePoint 2019 and I am using the below call:
POST http://<site>/_api/web/folders
{
"__metadata": {
"type": "SP.Folder"
},
"ServerRelativeUrl": "/SP 2019/Folder%"
}
But this is creating a Folder%25 instead of Folder%.
If I change the character in the JSON to #, it creates a folder with '#' character.
This does the job.
POST http://<site>/_api/web/folders/AddUsingPath(decodedurl='Path')
It will create a folder with % character. It was introduced for SP Online but also works with SP 2019.
The issue i am running into is the api returns 400 Bad Request in two cases:
a) The folder already exists.
b) The URL is malformed.
I need to distinguish between the two.
You may take a look at this Microsoft's page for further refrence.
The value we passed in was ‘%’, but it seems that the server escaped it.
As a workaround ,you could create a event receiver(item added) . When a folder is created, if its name contains ‘%25’, rename it.
Sample code:
public override void ItemAdded(SPItemEventProperties properties)
{
SPFolder folder = properties.ListItem.Folder;
string name= folder.Name;
if (name.Contains("%25")) {
string newName=name.Replace("%25", "%");
folder.Item["Name"] = newName;
folder.ParentWeb.AllowUnsafeUpdates = true;
folder.Item.Update();
folder.ParentWeb.AllowUnsafeUpdates = false;
}
base.ItemAdded(properties);
}
Best regards,
Amos

google apps script: file.setOwner() Not Transferring Ownership in Google Drive

I am trying to transfer ownership of all my .pdf files to another account with more space. I am testing the code with a single folder in my drive.
function transfer() {
var user = Session.getActiveUser();
var folder = DriveApp.getFolderById('123folder-id456789-VxdZjULVQkPAaJ');
var files = folder.getFilesByType(MimeType.PDF);
while (files.hasNext()) {
var file = files.next();
if (file.getOwner() == user) file.setOwner('example#gmail.com');
}
}
When I run the code, none of the files change ownership.
How about this modification?
Modification points:
In your script, it tries to compare the objects of Session.getActiveUser() and file.getOwner(). I think that this is the reason of your issue.
So how about this modification? Please think of this as just one of several answers.
Modified script:
function transfer() {
var user = Session.getActiveUser().getEmail(); // Modified
var folder = DriveApp.getFolderById('123folder-id456789-VxdZjULVQkPAaJ');
var files = folder.getFilesByType(MimeType.PDF);
while (files.hasNext()) {
var file = files.next();
if (file.getOwner().getEmail() == user) file.setOwner('example#gmail.com'); // Modified
}
}
In this modification, the emails are compared.
References:
getActiveUser()
getOwner()
Class User
If this didn't resolve your issue, I apologize.
Currently drive can't transefere the ownership of file that are not build-in, like pdf, zip, etc. So you must download them and reupload from the other account. I wrote a colab to do that without consume my bandwith. It can recursively transfere an entire folder with both build-in file types and other file types.

Save json files in android

I have my files saved on resources folder and when I try to write other thing it does not work. Could anyone help me?
public void SaveGameData()
{
PlayerSavedData aux = new PlayerSavedData();
aux.allSavedPlayerData = SavePlayerInformation.playerDataList.ToArray<PlayerData> ();
string dataAsJson = JsonUtility.ToJson (aux);
string filePath = Application.persistentDataPath + "playerInformation.json";
File.WriteAllText (filePath, dataAsJson);
}
This is wrong
string filePath = Application.persistentDataPath + "playerInformation.json";
Try this instead
string filePath = Path.Combine(Application.persistentDataPath,"playerInformation.json");
Also note that you need WRITE_EXTERNAL_STORAGE permission
The Resoures folder simply doens't exist any more afer your build. The assets in the Resources folder get packed into the game's archive for assets.
Better you put file in StreamingAssets folder.

How to read Group permissions and write it to an Excel in AEM

We have a requirement in which we have to read all the permissions given to a group and write it to an excel. I want to know how to read the group permission programmaticaly. Any help is highly appreciated.
Thanks,
Tushar
AEM 6.0+ (Apache OAK)
The permissioning scheme is replicated in the separated branch under /jcr:system/rep:permissionStore. A node for each authorizable (user/group) is available under /jcr:system/rep:permissionStore/crx.default/$authId. You can simply iterate over all permissions then using e.g. AEM Groovy Console or through JCR/Sling API.
def crawlAcls(authId) {
getResource("/jcr:system/rep:permissionStore/crx.default/$authId").getChildren().each{ r ->
def path = r.valueMap["rep:accessControlledPath"]
doTheStuff(authId, path)
}
}
AEM 5.6 and previous
Use search query. You should be looking for nodes of rep:ACL type. The basic query (which is highly ineffective!) but may be a starting point for further improvements is as following:
String queryString = "SELECT * FROM [rep:ACL] WHERE ISDESCENDANTNODE('" + rootPath + "')";
Iterator<Resource> resouces = resourceResolver.findResources(queryString, Query.JCR_SQL2);
while (resultNodes.hasNext()) {
Resource resource = resouces.next();
checkAndDoTheStuff(resource.getPath(), authorizable, acm)
}
private void checkAndDoTheStuff(String path, Authorizable authorizable, AccessControlManager acm) throws RepositoryException {
Principal principal = authorizable.getPrincipal();
JackrabbitAccessControlList jackrabbitAcl = JackrabbitAccessControlListUtil.getModifiableAcl(acm, path);
AccessControlEntry[] accessControlEntries = jackrabbitAcl.getAccessControlEntries();
for (AccessControlEntry accessControlEntry : accessControlEntries) {
if (accessControlEntry.getPrincipal().equals(principal)) {
doTheStuff(authorizable, path)
}
}
}

Upload Servlet with custom file keys

I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename