Magnolia cms: resources module proper usage - java

I am learning magnolia cms. I am trying to use the resources module. I have actually 2 problems.
Cannot upload a bunch of files. I have a few files, but in some time I will have to upload some more. Modules import feature wants me to upload an xml file. But I don't know how to generate it properly. Tried to import through JCR, but after that I can't see those files in resources app. Tried to configure the module to search files in file system: I set fileSystemLoader to class info.magnolia.module.resources.loaders.FileSystemResourceLoader and set some path. It did not work for me too. Maybe I just don't understand at what time should be activated files upload feature. At the application start up time it did not work.
How to properly use these resources in my template? What ftl tag should I use?
I don't use STK module.
Thanks for your patience if you decide to help me.
Magnolia version: 5.2 CE
JDK iced tea: 1.7.0_51
OS: Linux/OpenSUSE 12.3

I've used previously (on 4.5.x) script below to perform the task via groovy module. It should work on 5.2 as well.
import static groovy.io.FileType.FILES
import info.magnolia.jcr.util.NodeUtil
import org.apache.commons.lang.StringUtils
import info.magnolia.cms.util.ContentUtil
class Globals {
static def folderName = '//some/folder/in/filesystem/on/server'
}
def loadImageFolder() {
session = ctx.getJCRSession("resources")
parentFolder = session.getNode("/templating-kit/jelinek-image/obrazky-produkty")
new File(Globals.folderName).eachFileRecurse(FILES) {
name = it.name
// set file name
extension = StringUtils.substringAfterLast(name, '.')
name = StringUtils.substringBeforeLast(name, '.')
// persist
resource = NodeUtil.createPath(parentFolder,name , "mgnl:content")
// persistResource
resource.setProperty("mgnl:template", "resources:binary")
resource.setProperty("extension", extension)
binary = resource.addNode("binary", "mgnl:resource")
binary.setProperty("jcr:data", new FileInputStream(it.absolutePath))
binary.setProperty("extension", extension)
binary.setProperty("fileName", name)
binary.setProperty("jcr:mimeType", "image/"+extension)
binary.setProperty("size", it.length())
}
session.save()
}
loadImageFolder()
return 'done'

Related

Using Batik 1.14 with Java: How to import modules or classes?

The purpose of my project is to create PNG pictures from SVG using specific fonts (I have tried numerous converter services on the web but none of them worked with external fonts, and the JAVA program I have developed 10 years ago does no longer work).
My actual problem is the import of the batik.transcoder components into my program. Currently, it looks as follows:
<code>
// is this the really the parent of JPEGTranscoder / PNGTranscoder??
import javax.imageio.ImageTranscoder;
// Neither org.apache.batik... nor batik... is correct !!??
import org.apache.batik.transcoder.SVGAbstractTranscoder;
import batik.transcoder.TranscoderException;
import batik.transcoder.TranscoderInput;
import batik.transcoder.TranscoderOutput;
import batik.transcoder.PNGTranscoder;
import batik.transcoder.image.JPEGTranscoder;<br>
// or did I import the wrong jars ??
// (taken from batik-1.14 and afterwards from batik-1.7; neither did work!)
public class SVGConverter {
...
// all code lines below return the same error: "... cannot be resolved to a type"
TranscoderInput input = new TranscoderInput(svgURI);
TranscoderOutput output = new TranscoderOutput(ostream);
ImageTranscoder t;
...
t = new JPEGTranscoder();
...
t = new PNGTranscoder();
...
}
</code>
First I tried to import the batik components as modules on the module path but without success. In a contribution to stackoverflow I then found the hint to put the batik components not onto the module path but to the class path (Has batik not been converted into modules?). However, no success either.
I have copied all jar's contained in batik-1.14.zip and later of batik-1.7.zip into the lib directory within the project. No effect whatsoever...
I was using "import org.apache.batik.transcoder.XXX" in my previous program in 2013: Doesn't work any more. But using "import batik.transcoder.XXX" doesn't work either.
Thus, the following questions:
1. Is it correct that batik classes/jars have to be used via the class path?
2. What is the correct package name to address the respective packages and classes?
3. Is it correct to load the corresponding jar's into the lib directory of the project?

JDK Mission Control: Modifying Stack data from jfr files

Like this question - I'm trying to load in an existing jfr file that has been recorded on another machine external to our organisation. I now want to deobfuscate the information, either as a plugin for JDK Mission Control, or as a utility for reading in a jfc file and writing out a de-obfuscated version.
My class does the relevant implementation of the API
public class JFRProcessor implements IParserExtension {
//impementation details below
And I have tested it (successfully) with the following
List<File> files = new ArrayList<>();
files.add(new File("/user/rafe/Input001.jfr"));
List<IParserExtension> extensions = new ArrayList<>();
extensions.add(new JFRProcessor());
IItemCollection events = JfrLoaderToolkit.loadEvents(files, extensions);
//write out to xml to validate the change
RecordingPrinter printer = new RecordingPrinter(new PrintWriter(new File("/user/rafe/Output0001.xml")), Verbosity.HIGH, false);
printer.print(events);
When I then try to export this as a jar, I have the fully qualified classname (com.extension.JFRProcessor) in the relevant META-INF/services/org.openjdk.jmc.flightrecorder.parser.IParserExtension file - and JDK Mission Control doesn't do anything with the plugin (when put in the drop-ins directory).
This was then verified by exporting the jar and in a separate project (with the exported jar in the build path):
ServiceLoader<IParserExtension> loader = ServiceLoader.load(IParserExtension.class,
IParserExtension.class.getClassLoader());
Another approach that I took was to write out the events:
I have also tried using the latest SNAPSHOT release of JDK Mission Control with the new Recordings class in org.openjdk.jmc.flightrecorder.writer.api but I am struggling to see how to get between the IItemCollection and any useful data to feed into the Recording instance that I'm trying to rewrite into.
final Recording rec = Recordings.newRecording("/user/rafe/Output-001.jfr");
events.forEach(event -> {
IType<IItem> type = event.getType();
rec.writeEvent(typedValue);
});
Any help would be appreciated for either approach - as I'm struggling to see how to use this without de-obfuscating the data first!

Undefined function or variable 'BufferedImageLuminanceSource'

I recently used decode_qr from this FEX submission to decode my QR code. It ran quite well one or two weeks ago, but today it generate an error for me:
Undefined function or variable 'BufferedImageLuminanceSource'
Error in decode_qr (line 34);
source = BufferedImageLuminanceSource(jig);
I just checked the zxing repository and found that some files were updated several days ago. So I guess the path of some imported file from the package has been changed.
Here is the importing code from the decode_qr function:
import com.google.zxing.qrcode.*;
import com.google.zxing.client.j2se.*;
import com.google.zxing.*;
import com.google.zxing.common.*;
import com.google.zxing.Result.*;
How can I get it to work again? Do I need to change the import paths?
Here's what I did to get it to work (Win 10 x64, R2017b, ZXing 3.3.1):
Downloaded the latest prebuilt .jar artifacts from Sonatype:
core.
javase.
Added the files to my dynamic java classpath using javaaddpath:
javaaddpath('G:\core-3.3.1.jar');
javaaddpath('G:\javase-3.3.1.jar');
% Verify using: javaclasspath('-dynamic');
Note:
To add folders to the static path, which MATLAB loads at startup, create a javaclasspath.txt file, as described in Static Path.
Generated some example QR code using unitag.io:
Tried to decode it using Lior Shapira's decode_qr:
>> out = decode_qr(qr)
out =
'https://stackoverflow.com/users/3372061/dev-il'
Full code:
function out = q47223578()
javaaddpath('G:\core-3.3.1.jar');
javaaddpath('G:\javase-3.3.1.jar');
% Verify using: javaclasspath('-dynamic');
qr = imread('https://i.stack.imgur.com/mA4eP.png');
out = decode_qr(qr);

AWS Java SDK credentials

I am using the AWS Java SDK and trying to run some tests; getting:
Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath
The credentials file # ~/.aws/ is correct per AWS specs; 777'd it to ensure no access issues.
I am not using any IDE plug-ins; per AWS docs, having a credentials file # ~/.aws/ should suffice. Anyone have this working with just the SDK installed? If I hard-code the file path into the ClasspathPropertiesFileCredentialsProvider() request it spits the error back with the path instead of the AwsCredentials.properties string, which doesn't exist anywhere (yes, tried making one of those in ~/.aws/ as well).
Thanks much for any insights, code is below straight from Amazon:
import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
public class SNS {
public static void main(String[] args) {
AmazonSNSClient snsClient = new AmazonSNSClient(new ClasspathPropertiesFileCredentialsProvider());
snsClient.setRegion(Region.getRegion(Regions.US_EAST_1));
String msg = "this is a test";
PublishRequest publishRequest = new PublishRequest("my arn", msg);
PublishResult publishResult = snsClient.publish(publishRequest);
System.out.println("MessageId - " + publishResult.getMessageId());
}
}
If you use DefaultAWSCredentialsProviderChain instead of ClasspathPropertiesFileCredentialsProvider, it will automatically check various default locations for AWS credentials. (Documentation)
Have you verified that your $HOME environment variable is set for the process you are running? The AWS SDK relies on $HOME to determine the proper location of your .aws folder.
Well that didn't work the way I'd planned it; couldn't get the .aws path as a classpath (tried adding as an external class folder).
Ran the below to find the actual classpaths in my project:
public static void main (String args[]) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}
}
and then dropped my AWS credentials into a new AwsCredentials.properties file in one of the dirs from above (I had one; the rest were jar files).
Changed the tag values in the file to "accessKey" and "secretKey" from what was there (aws_access_key, aws_secret_access_key) and it worked.
Thanks to everyone for their inputs.

Get version of a .pkg file?

I have a Java application for MAC OSX that I have coded and made a .pkg of it. While creating the .pkg I gave it a version number also. Now I need to get the version number of this application in my java code so that i can check for updates when the application runs. When I right-click on my app file it doesn't show me the version I entered while creating the package.
Do I need to set the version of my app file that I created using the jar bundler for building the pkg???
Please suggest me how I could accomplish this.
The version number you set while creating the package (in the PackageMaker Project) is the version of the installer, not the version of your .app-File. It is needed, so that another installer can see if he downgrades the current installation or not. The installer will never ever look at the contents it is installing to the system.
To set the version of your your .app-Bundle, right-click your .app-file and select "Show Package Contents" from the appearing menu. Open the folder "Contents", there you will find a file called "Info.plist". You have to edit this file and have to set your version-info for your application there. You can do this by using Property List Editor (included in the Apple Developer Tools) or another tool like BBEdit for example.
To read from your .plist in your application, you need a special library. I recommend the Java property list library from Daniel Dreibrodt (more information about the .plist-Format you'll find in this post on my blog).
Generelly, you should set the version-info of your app-bundle, anyway you use it for updating-purposes or not. If it is not set, the user has no chance to get information about the version he has installed without launching your software.
What you need is not the version of your .pkg file, you need the version of your .app-Bundle. Anyway - the version of your .pkg-file is handled the same way as your .app-file. There is also the Info.plist, where you find the informations. It can also be parsed with the same library.
The pkg is a zip file containing a.o. a file called PackageInfo. PackageInfo is an XML file looking like this:
<pkg-info format-version="2" identifier="com.mycompany.pkg.MyApp" version="1.2.0" overwrite-permissions="false" install-location="/" auth="root">
<payload installKBytes="4717" numberOfFiles="146"/>
<scripts>
<preinstall file="./preinstall"/>
<postinstall file="./postinstall"/>
</scripts>
<bundle-version>
<bundle path="./Applications/MyApp.app" CFBundleShortVersionString="1.2.0" CFBundleVersion="166" id="com.mycompany.MyApp" CFBundleIdentifier="com.mycompany.MyApp">
<bundle path="./Contents/Library/LoginItems/HelperApp.app" CFBundleShortVersionString="1.0" CFBundleVersion="1" id="com.mycompany.HelperApp" CFBundleIdentifier="com.mycompany.HelperApp"/>
</bundle>
</bundle-version>
</pkg-info>
To get the package version, you could use the following XPath:
pkg-info/#version
To get the application version:
pkg-info/bundle-version/bundle/#CFBundleShortVersionString
And the build number is here:
pkg-info/bundle-version/bundle/#CFBundleVersion
I know it is a quite old question but the answers are not satisfying. Here is my solution:
A MacOS .pkg file is an archive in XAR format. So any XAR archive reader can read its contents. I found an XAR reader for Java from Sprylab here. This library has Apache 2.0 license so it is free to use also for commercial products. It is quite old but it works. The file "Distribution" in the archive is in XML format and gives details about the installer bundle, e.g. the version ;)
I am using JSON so I did not want to add an XML reader for reading just one value. So the following code uses the XAR library and a custom XML reader to extract the version of the bundle in the .pkg installer.
public static void main(String [ ] args) throws XarException {
XarSource xar = new FileXarSource(new File("PathToPkgFile/PkgFilename.pkg"));
XarEntry entry = xar.getEntry("Distribution");
String distributionStr = new String(entry.getBytes());
String bundleVersionXml = getSubstringByStr(distributionStr, "<bundle-version>", "</bundle-version>");
String bundleAttrStr = getSubstringByStr(bundleVersionXml, "<bundle", "/>");
String version = getAttributeValue(bundleAttrStr, "CFBundleVersion");
System.out.println(bundleVersionXml);
System.out.println(bundleAttrStr);
System.out.println(version);
}
private static String getSubstringByStr(String xmlString, String start, String end) {
int startIdx = xmlString.indexOf(start);
int endIdx = xmlString.indexOf(end);
return xmlString.substring(startIdx + start.length(), endIdx);
}
private static String getAttributeValue(String tagContentString, String attribute) {
int startIdx = tagContentString.indexOf(attribute) + attribute.length() + "=\"".length();
int endIdx = startIdx + tagContentString.substring(startIdx).indexOf("\"");
return tagContentString.substring(startIdx, endIdx);
}

Categories

Resources