How to find unused images from CQ DAM - aem

Is there a way to find to unused assets from CQ DAM? Currently our CQ instance has accumulated huge amount of assets and at least 25% is not being used as of now. Our CQ instance is running on windows (5.6). Is there a cleaner way to do the same?
Thanks,
Santhosh

You may use the following XPATH query to get all assets:
/jcr:root/content/dam//*[#jcr:primaryType='dam:Asset']
Using QueryManger you may get list of asset nodes:
Workspace workspace = session.getWorkspace();
QueryManager qm = workspace.getQueryManager();
Query query = qm.createQuery(xpathQuery, Query.XPATH);
QueryResult queryResult = query.execute();
result = queryResult.getNodes();
Next you need to get path of every asset and verify is it used:
while(result.hasNext()) {
Node assetNode = result.nextNode();
String assetPath = assetNode.getPath();
}
To verify is it asset used you need again run xpath :
/jcr:root/content/mywebsite//*[#fileReference='putAssetPathHere']
Now result.hasNext() == true means asset is used

Another solution is to use ReferenceSearch
for (String path : paths) {
if (resourceResolver.getResource(path) != null) {
Map<String, ReferenceSearch.Info> searchResult = referenceSearch.search(resourceResolver, path);
if (searchResult.isEmpty()) {
//path is unused asset
}
//get used pages
for (Map.Entry<String, ReferenceSearch.Info> info : searchResult.entrySet()) {
info.getKey();//will return page path
}
//get used properties paths
for (Map.Entry<String, ReferenceSearch.Info> info : searchResult.entrySet()) {
for (String prop : info.getValue().getProperties()) {
//prop is property path
}
}
}
}

For me following code worked.
help link : http://wemcode.wemblog.com/get_asset_reference_in_page
String damPath = "/content/dam/geometrixx/offices/basel kitchen.jpg";
for (ReferenceSearch.Info info: new ReferenceSearch().search(resourceResolver, damPath).values()) {
for (String p: info.getProperties()) {
out.println("Path is "+info.getPage().getPath());
}

Related

Take all text files in a folder and combine then into 1

I'm trying to merge all my text files into one file.
The problem I am having is that the file names are based on data previously captured in my app. I don't know how to define my path to where the text files are, maybe. I keep getting a error, but the path to the files are correct.
What am I missing?
string filesread = System.AppDomain.CurrentDomain.BaseDirectory + #"\data\Customers\" + CustComboB.SelectedItem + #"\";
Directory.GetFiles(filesread);
using (var output = File.Create("allfiles.txt"))
{
foreach (var file in new[] { filesread })
{
using (var input = File.OpenRead(file))
{
input.CopyTo(output);
}
}
}
System.Diagnostics.Process.Start("allfiles.txt");
my error:
System.IO.DirectoryNotFoundException
HResult=0x80070003
Message=Could not find a part of the path 'C:\Users\simeo\source\repos\UpMarker\UpMarker\bin\Debug\data\Customers\13Dec2018\'.
I cant post a pic, but let me try and give some more details on my form.
I select a combobox item, this item is a directory. then I have a listbox that displays the files in my directory. I then have a button that executes my desires of combining the files. thanks
I finally got it working.
string path = #"data\Customers\" + CustComboB.SelectedItem;
string topath = #"data\Customers\";
string files = "*.txt";
string[] txtFiles;
txtFiles = Directory.GetFiles(path, files);
using (StreamWriter writer = new StreamWriter(topath + #"\allfiles.txt"))
{
for (int i = 0; i < txtFiles.Length; i++)
{
using (StreamReader reader = File.OpenText(txtFiles[i]))
{
writer.Write(reader.ReadToEnd());
}
}
System.Diagnostics.Process.Start(topath + #"\allfiles.txt");
}

Google script: Download web image and save it in a specific drive folder

I need to download an image with GS and save it in a specific drive folder.
I'm able to save the image in the root folder but i cannot save it in a specific folder:
function downloadFile(fileURL,folder) {
var fileName = "";
var fileSize = 0;
var response = UrlFetchApp.fetch(fileURL, {muteHttpExceptions: true});
var rc = response.getResponseCode();
if (rc == 200) {
var fileBlob = response.getBlob()
var folder = DriveApp.getFoldersByName(folder);
if (folder != null) {
var file = DriveApp.createFile(fileBlob);
fileName = file.getName();
fileSize = file.getSize();
}
}
var fileInfo = { "rc":rc, "fileName":fileName, "fileSize":fileSize };
return fileInfo;
}
Question: what have I to add to use the variable "folder"?
I found a lot of examples with "DocList" Class that is not in use anymore
Many thanks
Well, I guess GAS has make a lot of progress on developing its API, the function
createFile(blob) of an object Folder will do the job:
https://developers.google.com/apps-script/reference/drive/folder#createfileblob
// Create an image file in Google Drive using the Maps service.
var blob = Maps.newStaticMap().setCenter('76 9th Avenue, New York NY').getBlob();
DriveApp.getRootFolder().createFile(blob);
It's quite late for the answer but just incase some one runs into the situation.
Are you familiar with this app? It does exactly what you're asking for.
However, if you want to re-create this for your own purposes, I would change your declaration of variable file to read as such:
var file = folder.next().createFile(fileBlob);
when you create your variable folder, the method you use creates a FolderIterator, not a single folder. You have to call the next() method to get a Folder object.
To be precise with your script and avoid saving to an incorrect-but-similarly-named folder, I would recommend passing the folder ID to your script rather than the folder Name. If you pass the folder ID, you could declare folder as:
var folder = DriveApp.getFolderById(folder);
and then continue the script as you have it written. I hope that helps.
Working on similar problem, I came up with the solution below to save a file to a folder. If the folder doesn't exist it creates it, otherwise it saves the file specified by "FOLDER_NAME"
var folderExists = checkFolderExists("FOLDER_NAME");
if (folderExists) {
saveFolder = DriveApp.getFolderById(folderExists);
} else {
saveFolder = DriveApp.createFolder("FOLDER_NAME");
}
// Make a copy of the file in the root drive.
var file = DriveApp.getFileById(sheetID);
// Take the copy of the file created above and move it into the folder:
var newFile = DriveApp.getFolderById(saveFolder.getId()).addFile(file);
// Remove the copy of the file in the root drive.
var docfile = file.getParents().next().removeFile(file);
Further to Eric's answer, I have also provided a utility function that checks if the folder exists. It's reusable in any project.
function checkFolderExists(fName) {
try {
var folderId;
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
folderName = folder.getName();
if (folderName == fName) {
folderId = folder.getId();
}
}
} catch(e) {
log("Services::checkFolderExists()" + e.toString());
throw e;
}
return folderId;
}

dynamic connection string with EF4, get metadata path is not valid

Here is my problem.
I use a dynamic connection string for my Entity Framework context.
//In Web Config
add key="DataSource" value="WIN-QBRH0MJL8IT\ISS" />
//In my EntityFactory.cs
public static DBEntities GetEntity()
{
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = ConfigurationManager.AppSettings["DataSource"];
scsb.InitialCatalog = "db1";
scsb.MultipleActiveResultSets = true;
scsb.IntegratedSecurity = true;
if (HttpContext.Current.Session["DBName"] == null)
{
HttpContext.Current.Response.Redirect("/Account/Step1");
}
else
{
scsb.InitialCatalog = HttpContext.Current.Session["DBName"].ToString();
}
var builder = new EntityConnectionStringBuilder();
builder.Metadata = "metadata=~/bin/Models/DBModel.csdl|~/bin/Models/DBModel.ssdl|~/bin/Models/DBModel.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = scsb.ConnectionString;
DBEntities db = new DBEntities(builder.ConnectionString);
return db;
}
I Know the problem is for this line :
builder.Metadata =
"metadata=~/bin/Models/DBModel.csdl|~/bin/Models/DBModel.ssdl|~/bin/Models/DBModel.msl";
I check and the csdl, ssdl, msl are in /mvcinfosite/bin/Models/.csdl,.ssdl,.msl
The configuration for my edmx is:
Metadata Artifact Processing : Copy to Output Directory
Here is the full error
The specified metadata path is not valid. A valid path must be either
an existing directory, an existing file with extension '.csdl',
'.ssdl', or '.msl', or a URI that identifies an embedded resources
Thanks
Try to remove ~ character and use valid relative path to your app root. I think it is not able to work with this special character used on in ASP.NET application.

how to programmatically access the builtin properties of an open xml worddoc file

i would like to access some built in properties(like author,last modified date,etc.) of an open xml word doc file. i would like to use open xml sdk2.0 for this purpose. so i wonder if there is any class or any way i could programmatically access these builtin properties.
An explanation of the following method can be found here, but pretty much you need to pass in the properties that you want to get out of the core.xml file to this method and it will return the value:
public static string WDRetrieveCoreProperty(string docName, string propertyName)
{
// Given a document name and a core property, retrieve the value of the property.
// Note that because this code uses the SelectSingleNode method,
// the search is case sensitive. That is, looking for "Author" is not
// the same as looking for "author".
const string corePropertiesSchema = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
const string dcPropertiesSchema = "http://purl.org/dc/elements/1.1/";
const string dcTermsPropertiesSchema = "http://purl.org/dc/terms/";
string propertyValue = string.Empty;
using (WordprocessingDocument wdPackage = WordprocessingDocument.Open(docName, true))
{
// Get the core properties part (core.xml).
CoreFilePropertiesPart corePropertiesPart = wdPackage.CoreFilePropertiesPart;
// Manage namespaces to perform XML XPath queries.
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("cp", corePropertiesSchema);
nsManager.AddNamespace("dc", dcPropertiesSchema);
nsManager.AddNamespace("dcterms", dcTermsPropertiesSchema);
// Get the properties from the package.
XmlDocument xdoc = new XmlDocument(nt);
// Load the XML in the part into an XmlDocument instance.
xdoc.Load(corePropertiesPart.GetStream());
string searchString = string.Format("//cp:coreProperties/{0}", propertyName);
XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);
if (!(xNode == null))
{
propertyValue = xNode.InnerText;
}
}
return propertyValue;
}
You can also use the packaging API:
using System.IO.Packaging.Package;
[...]
using (var package = Package.Open(path))
{
package.PackageProperties.Creator = Environment.UserName;
package.PackageProperties.LastModifiedBy = Environment.UserName;
}
That works also for other open XML formats like power point.
package.Save();
Then
package.closed;
I think that Is the best way.

In an Eclipse plugin, how can I make a DirectoryFieldEditor start with a particular path?

I am making an Eclipse plugin which on right clicking a project produces a UI.
In this UI I have used DirectoryFieldEditor. This produces directory dialog starting at "MyComputer" as root. What i want is it to show paths starting at the project which i right clicked. how can this be achieved?
I am trying to mimic when you right click a project and say "new package" - the source folder browse give a directory dialog with only those folders which are open projects.... I want a similar directory dialog.
Can somebody help and give me some code snippets or suggestions?
Well, considering the "new package" is actually the class:
org.eclipse.jdt.internal.ui.wizards.NewPackageCreationWizard
which uses NewPackageWizardPage (source code), you will see:
public void init(IStructuredSelection selection) {
IJavaElement jelem = getInitialJavaElement(selection);
initContainerPage(jelem);
String pName = ""; //$NON-NLS-1$
if (jelem != null) {
IPackageFragment pf = (IPackageFragment) jelem
.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
if (pf != null && !pf.isDefaultPackage())
pName = pf.getElementName();
}
setPackageText(pName, true);
updateStatus(new IStatus[] { fContainerStatus, fPackageStatus });
}
With the getInitialJavaElement() being part of superclass NewContainerWizardPage:
/**
* Utility method to inspect a selection to find a Java element.
*
* #param selection the selection to be inspected
* #return a Java element to be used as the initial selection, or <code>null</code>,
* if no Java element exists in the given selection
*/
protected IJavaElement getInitialJavaElement(
IStructuredSelection selection) {
IJavaElement jelem = null;
if (selection != null && !selection.isEmpty()) {
Object selectedElement = selection.getFirstElement();
if (selectedElement instanceof IAdaptable) {
IAdaptable adaptable = (IAdaptable) selectedElement;
jelem = (IJavaElement) adaptable
.getAdapter(IJavaElement.class);
if (jelem == null) {
IResource resource = (IResource) adaptable
.getAdapter(IResource.class);
if (resource != null
&& resource.getType() != IResource.ROOT) {
while (jelem == null
&& resource.getType() != IResource.PROJECT) {
resource = resource.getParent();
jelem = (IJavaElement) resource
.getAdapter(IJavaElement.class);
}
if (jelem == null) {
jelem = JavaCore.create(resource); // java project
}
}
}
}
}
if (jelem == null) {
IWorkbenchPart part = JavaPlugin.getActivePage()
.getActivePart();
if (part instanceof ContentOutline) {
part = JavaPlugin.getActivePage().getActiveEditor();
}
if (part instanceof IViewPartInputProvider) {
Object elem = ((IViewPartInputProvider) part)
.getViewPartInput();
if (elem instanceof IJavaElement) {
jelem = (IJavaElement) elem;
}
}
}
if (jelem == null
|| jelem.getElementType() == IJavaElement.JAVA_MODEL) {
try {
IJavaProject[] projects = JavaCore.create(
getWorkspaceRoot()).getJavaProjects();
if (projects.length == 1) {
jelem = projects[0];
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return jelem;
}
Between those two methods, you should be able to initialize your custom UI with the exact information (i.e., "relative source path") you want.
If you look at the source of DirectoryFieldEditor, you will see it open its directory chooser dialog based on the value if its main Text field defined in StringFieldEditor:doLoad():
String JavaDoc value = getPreferenceStore().getString(getPreferenceName());
textField.setText(value);
That means you need, in your custom UI, to get the preference store and associate the right path with an id. You will use that id for your DirectoryFieldEditor initialization. Y oucan see an example here.
public static final String MY_PATH = "my.init.path";
IPreferenceStore store = myPlugin.getDefault().getPreferenceStore();
store.setValue(MY_PATH, theRightPath);
myDirFieldEditor = new DirectoryFieldEditor(MY_PATH, "&My path", getFieldEditorParent());
As you mention in the comments, all this will only initialize the eclipse-part GUI, not the native windows explorer launched by a DirectoryDialog:
this (the native interface) is based on:
parameters stored in BROWSEINFO Structure
used by the actual GUI SHBrowseForFolder Function, which actually displays a dialog box that enables the user to select a Shell folder.
That GUI initialize a root path based on filter path, so you need to also initialize (on eclipse side) that filter field with a path in order to get it pick up by the Windows-GUI SHBrowseForFolder.
According to DirectoryFieldEditor, that is exactly what getTextControl() (the field you initialized above) is for.
But the problem comes from the fact that field has been initialized with a relative path. Since that path is unknown by the underlying OS, it defaults back to root OS path.
You need to find a way to store the full system path of the project, not the relative path.
That way, that full path will be recognized by the Os and used as initial path.
For instance, from a IJavaElement, you can get its associated resource, and try to get the (full system) path from there.
Actually, from the IPackageFragment you should be able to call getPath(), and check if the IPath returned contains the full system path.