I'm pretty new to java so bear with me. I'm trying to retrieve the properties of a child node. For instance I'm trying to retrieve all the properties associated with the image property:
/content
/foo
/jcr:content
/page
/page_child
/image <-----
Currently my script is retrieving all the properties from page_child but how do I get the properties of "image"
public void setPageContext(PageContext context) {
ValueMap properties = (ValueMap) context.getAttribute("properties");
closeText = properties.get("closeText", "");
imageURL = properties.get("fileReference", "");
}
public String getCloseText() { return closeText; }
public String getCloseText() { return imageURL; }
Take a look at /libs/foundation/components/adaptiveimage
In the JSP, they are creating a new Resource using the jcr:content of the image file.
Resource fileJcrContent = resource.getChild("file").getChild("jcr:content");
if (fileJcrContent != null) {
ValueMap fileProperties = fileJcrContent.adaptTo(ValueMap.class);
String mimeType = fileProperties.get("jcr:mimeType", "jpg");
extension = mimeType.substring(mimeType.lastIndexOf("/") + 1);
}
From there, all properties will be accessible through fileProperties.
Related
I have the following class (below). The file corresponding to vocabLookupFile is found when in the root directory of my SpringBoot project. However, I really want it in the src/main/resources directory of the project. With the below setup, it is not found there. By the way, the LookupMapper component is autowired in a #Service class, and other than not finding the file in src/main/resources, it works fine.
I am hoping someone can tell me how to modify the below so it can be found there. Thanks for any ideas.
#Component
public class LookupMapper {
public HashMap<String, LookUp> entry = new HashMap<>();
#Autowired
public LookupMapper(#Value("${vocab.lookup.mapper}") String vocabLookupFile) throws IOException {
try (CSVReader csvReader = new CSVReader(new FileReader(vocabLookupFile))) {
String[] values = null;
while ((values = csvReader.readNext()) != null) {
LookUp lookUp = new LookUp(values[1], Boolean.parseBoolean(values[2]));
this.entry.put(values[0].toUpperCase(), lookUp);
}
}
}
}
as per Mark Rotteveel, suggestion, with my file in the resource directory, in general, I need a solution that could retrieve the file from the context of the jar (and those things in the jar are considered "resources"). I used Classloader to get the resource as a stream. So the below works for me. Thanks to Mark.
#Component
public class LookupMapper {
public HashMap<String, LookUp> entry = new HashMap<>();
#Autowired
public LookupMapper(#Value("${vocab.lookup.mapper}") String vocabLookupFile) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
try (CSVReader csvReader = new CSVReader(new InputStreamReader(classLoader.getResourceAsStream(vocabLookupFile)))) {
String[] values = null;
while ((values = csvReader.readNext()) != null) {
LookUp lookUp = new LookUp(values[1], Boolean.parseBoolean(values[2]));
this.entry.put(values[0].toUpperCase(), lookUp);
}
}
}
}
Sending the request to Server with the below xml for downloading
<?xml version="1.0" encoding="UTF-8"?>
<ResourceSet xmlns:v01"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<cycleTime>123</cycleTime>
<object>
<sourceUrl>http://10.34894.494/23.png</sourceUrl>
<accessUrl>http://10.126.45.72/cme/23.png</accessUrl>
<objectMetadata>
<headerName>Content-Length</headerName>
<headerName>E-Tag</headerName>
</objectMetadata>
</object>
<object>
<sourceUrl>http://10.84375.72/cme/23.png</sourceUrl>
<accessUrl>http://10.4575.572/cme/logo/23.png</accessUrl>
<objectMetadata>
<headerName>Content-Length</headerName>
<headerName>E-Tag</headerName>
</objectMetadata>
</object>
</ResourceSet>
There are 2 objects and which has same source URL and different Access URl .
My job is to download the image only once because source URL’s are duplicated .
Am iterating through the objects , but how I will know two objects has same source URL to download ?
There are 2 objects and which has same source URL and different Access URl .
My job is to download the image only once because source URL’s are duplicated .
Am iterating through the objects , but how I will know two objects has same source URL to download ?
public void download_resourceset_object_urls_images_to_local() throws Throwable {
List<String> sourceURis = GFDUtils.getSourceOrAccessURLs(xmlPath + xmlFileName, "sourceUrl");
dwInfoList = new HashMap<String, DownloadFileInfo>();
NSAUtils.removeFiles(ConfigLoader.DOWNLOAD_DIR);
boolean flag = HTTPClientFileDownload.downloadFile(sourceURis, ConfigLoader.DOWNLOAD_DIR, dwInfoList);
if (flag == true) {
logger.info("All URL files / images are downloaded successfully....");
} else
throw new GenericException("Files are not available / Failed download ");
}
here am iterating Xml and getting the Source URL to download
public static List<String> getSourceOrAccessURLs(String xmlPath, String urlname) throws IOException {
XStream xs = new XStream();
boolean flag = XMLValidation.validateXMLSchema(xmlPath);
File file = new File(xmlPath);
String xml = FileUtils.readFileToString(file);
if (flag == true) {
List<String> urls = new ArrayList<>();
try {
xs.processAnnotations(Resourceset.class);
Resourceset rs = (Resourceset) xs.fromXML(xml);
List<ResourcesetObject> rsoOject = rs.getResourcesetObject();
for (ResourcesetObject resourcesetObject : rsoOject) {
if (urlname.equals("sourceUrl")) {
urls.add(resourcesetObject.getSourceUrl());
} else {
urls.add(resourcesetObject.getAccessUrl());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return urls;
}
return null;
}
This URL Am passing for downloading.
Please help
Thanks,
I want to be able to use a variable that can be changed within a file path. The username relevant to the file path is declared in the constructor then I have tried to assign this to the file path in the below method.
What I wanted to happen when calling:
System.out.format("%s%n", documentsPath.resolve(username +"\\Documents"));
Was that the documents Path would then be:
C:\Users\ryanb\Documents
Instead when I call documentsPath.toString() I only get returned:
C:\Users\
How do I get the documentsPath variable to be assigned with the String username and the "\\Documents" at the end.
This is my code:
class profileCopy{
/*global variables */
private Path documentsPath;
private Path desktopPath;
private Path favoritesPath;
private Path networkFolder;
private String username;
private String foldername;
public profileCopy(String username, String foldername)
{
this.username = username;
this.foldername = foldername;
documentsPath = Paths.get("C:\\Users");
desktopPath = Paths.get("C:\\Users");
favoritesPath = Paths.get("C:\\Users");
networkFolder = (Paths.get("F:\\Data\\WP51"));
}
public void copyDocumentsFolder() throws IOException
{
Path newDir = Paths.get("C:\\Users\\ryanb\\Documents\\TestCopy");
System.out.format("%s%n", documentsPath.resolve(username +"\\Documents"));
System.out.format("%s%n", networkFolder.resolve(foldername + "\\Backup"));
System.out.println(networkFolder.getFileName());
Files.move(documentsPath, networkFolder.resolve(documentsPath.getFileName()));
System.out.println(newDir.toString());
}
The main point in order to your code doesn't work is that you don't re-assign the return value of resolve() method to your path variable, since the method returns a new object.
In order to build your Paths, you can use something like this:
documentsPath = Paths.get(string.format("C:\\Users\\%s\\%s", username, "Documents");
If you want to reuse some code, you can use an array of folders and create them:
List<Path> paths = new ArrayList();
String[] defaultFolders = {"Documents", "Desktop", "Music"};
foreach (folder : defaultFolders) {
paths.add(Path.get(string.format("C:\\Users\\%s\\%s", username, folder)));
PS: Since you're developing that in java, you should consider to make the Path's UNIX or Windows Compatible, since UNIX environments doensn't recognize the "C:/Users" path.
The resolve methods returns a Path
public void copyDocumentsFolder() throws IOException
{
Path newDir = Paths.get("C:\\Users\\ryanb\\Documents\\TestCopy");
documentsPath = documentsPath.resolve(username + "\\Documents");
networkFolder = networkFolder.resolve(foldername + "\\Backup");
System.out.format("%s%n", documentsPath);
System.out.format("%s%n", networkFolder);
System.out.println(networkFolder.getFileName());
Files.move(documentsPath, networkFolder.resolve(documentsPath.getFileName()));
System.out.println(newDir.toString());
}
I'm writing a NetBeans plugin and would like to register a file type. The file type is a hidden file (e.g. ".something") with mime-type text/plain and a settled name (".something"). The registration looks like this:
#MIMEResolver.ExtensionRegistration(
displayName = "#Label",
mimeType = "text/plain+something",
extension = {"something"}
)
#DataObject.Registration(
mimeType = "text/plain+something",
iconBase = "com/welovecoding/netbeans/plugin/logo.png",
displayName = "#Label",
position = 300
)
public class SomethingDataObject extends MultiDataObject {
public SomethingDataObject(FileObject pf, MultiFileLoader loader) throws DataObjectExistsException, IOException {
super(pf, loader);
registerEditor("text/plain", true);
}
//...
}
The problem with this is NetBeans will only recognize the filetype if the name of the file has a name, a point and an extension (e.g. "name.something"). Just a point and an extension (e.g. ".something") is not recognized properly. Is there a solution for this kind of problem?
I solved the problem by implementing a custom non-declarative MIMEResolver. Here's the code:
#ServiceProvider(service = MIMEResolver.class, position = 3214328)
public class FilenameResolver extends MIMEResolver {
private static final String mimetype = "text/plain+something";
public FilenameResolver() {
super(mimetype);
}
#Override
public String findMIMEType(FileObject fo) {
String nameExt = fo.getNameExt();
if (".something".equalsIgnoreCase(nameExt)) {
return mimetype;
}
return null;
}
}
There's a declarative MIMEResolver too. Note that the declarative way seems to be preferred by NetBeans-Devs.
I have a form with that code:
public Form()
{
initComponents();
try
{
File file= new File("avatar.jpg");
BufferedImage image= ImageIO.read(file);
}
catch (IOException ex)
{
System.out.println("Failed to load image");
}
}
The problem is that the code always throws the IOException and enters in the catch block.
So the file isn't read.
I have created the project with Netbeans 7.2, and the directory looks like this:
What's the problem? Maybe the file shouldn't be there but in the father directory? Or what?
Is your image being packaged within your jar? to find this out, extract you jar file like you would an ordinary zip file and check if the image is anywhere there (normally located by jarname\packagename\filename. If so then you'll need to extract your image as a resource using getResourceAsStream().
It would be something like:
public class Test {
private static final String absName = "/yourpackage/yourimage.jpg";
public static void main(String[] args) {
Class c=null;
try {
c = Class.forName("yourpackage.Test");//pkg is the package name in which the resource lies
} catch (Exception ex) {
// This should not happen.
}
InputStream s = c.getResourceAsStream(absName);
// do something with it.
}
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResourceAsStream(name); // A system class.
}
return cl.getResourceAsStream(name);
}
public java.net.URL getResource(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResource(name); // A system class.
}
return cl.getResource(name);
}
private String resolveName(String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
Class c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/') + "/" + name;
}
} else {
name = name.substring(1);
}
return name;
}
}
Reference:
Accessing Resources
It looks like you have a namespace of poker.*
It all depends on where the jvm is initialized from.
Where is your main? Is it in /Users/ramy/NetBeansProjects/Poker/src?
Also, I suggest you use getResource() for all of your file loading needs, especially inside jars.
this.getClass().getResource("/resource/buttons1.png")
or
this.getClass().getResourceAsStream("/resource/TX_Jello2.ttf")
You can find out where your programs default path is by doing the following:
System.getProperty("user.dir");
Without seeing the error I would say the most likely cause is it can't find the file. So I suggest you replace "avatar.jpg" in the File constructor with the absolute file path to it. e.g.
File file = new File("INSERT_PATH_TO_FILE/avatar.jpg");
You cannot assume the image will be "there" because the relative path between your .java and the image seems ok.
Accessing a resource depends of your "kind" of project (Web, standalone....). In your case, you can try to get the image from your classpath
final File inputFile = new ClassPathResource("....").getFile();
final BufferedImage inputImg = ImageIO.read(inputFile);