JCRExportCommand execute() throws exception error in magnolia cms - magnolia

I would like to create a YAML export file on my local folder for the node on which I executed the Custom Action. The code below gives me NullPointerException:
java.lang.NullPointerException at java.util.Hashtable.get(Hashtable.java:364)
info.magnolia.repository.WorkspaceMapping.getWorkspaceMapping(WorkspaceMapping.java:124)
info.magnolia.repository.DefaultRepositoryManager.getSession(DefaultRepositoryManager.java:308)
info.magnolia.context.DefaultRepositoryStrategy.internalGetSession(DefaultRepositoryStrategy.java:61)
info.magnolia.context.AbstractRepositoryStrategy.getSession(AbstractRepositoryStrategy.java:75) info.magnolia.context.AbstractContext.getJCRSession(AbstractContext.java:124) info.magnolia.importexport.command.JcrExportCommand.execute(JcrExportCommand.java:117)
ch.xxx.module.versioning.MyAction.execute(MyAction.java:60)
public class MyAction extends AbstractMultiItemAction<xxxVersioning> {
public MyAction(xxxVersioning definition, JcrItemAdapter item, UiContext uiContext) {
super(definition, item, uiContext);
// TODO Auto-generated constructor stub
}
#Override
public void execute() {
//export nodes from a JCR workspace
JcrExportCommand exporter = new JcrExportCommand();
//sets export format to yaml
exporter.setFormat("yaml");
//setup the root directory for exports
File rootDir = new File("/Users/asusti/Downloads/yamlExport");
// clean up first
rootDir.delete();
rootDir.mkdirs();
//get root node
Node node = (Node) getItems().get(0).getJcrItem();
try {
exporter.setPath(node.getPath());
File file = new File(rootDir+node.getName()+".yaml");
FileOutputStream out = new FileOutputStream(file);
exporter.setOutputStream(out);
exporter.execute(MgnlContext.getInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Do I have to set some other methods for the exporter before I execute it?

You have to set the name of the workspace you want to export via JcrExportCommand#setRepository(). E.g.
exporter.setRepository("website");
to export the web site workspace.

Related

How to reload apache commons configurations2 properties

can anyone guide me on how to perform a reload of an apache commons configuration2 properties. I'm unable to find any implementation of this anywhere. The apache docs are a bit too abstract. This is what I have so far but it's not working.
CombinedConfiguration cc = new CombinedConfiguration();
Parameters params = new Parameters();
File configFile = new File("config.properties");
File emsFile = new File("anotherconfig.properties");
ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> configBuilder =
new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.fileBased()
.setFile(configFile));
PeriodicReloadingTrigger reloadTrg = new PeriodicReloadingTrigger(configBuilder.getReloadingController(), null, 5, TimeUnit.SECONDS);
reloadTrg.start();
cc.addConfiguration(configBuilder.getConfiguration());
FileBasedConfigurationBuilder<FileBasedConfiguration> emsBuilder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.properties()
.setFile(emsFile));
cc.addConfiguration(emsBuilder.getConfiguration());
DataSource ds = EmsDataSource.getInstance().getDatasource(this);
BasicConfigurationBuilder<DatabaseConfiguration> dbBuilder =
new BasicConfigurationBuilder<DatabaseConfiguration>(DatabaseConfiguration.class);
dbBuilder.configure(
params.database()
.setDataSource(ds)
.setTable("EMS_CONFIG")
.setKeyColumn("KEY")
.setValueColumn("VALUE")
);
cc.addConfiguration(dbBuilder.getConfiguration());
The configuration obtained from a builder is not updated automatically. You need to get the configuration from the builder every time you read it.
From Automatic Reloading of Configuration Sources:
One important point to keep in mind when using this approach to reloading is that reloads are only functional if the builder is used as central component for accessing configuration data. The configuration instance obtained from the builder will not change automagically! So if an application fetches a configuration object from the builder at startup and then uses it throughout its life time, changes on the external configuration file become never visible. The correct approach is to keep a reference to the builder centrally and obtain the configuration from there every time configuration data is needed.
use following code:
#Component
public class ApplicationProperties {
private PropertiesConfiguration configuration;
#PostConstruct
private void init() {
try {
String filePath = PropertiesConstants.PROPERTIES_FILE_PATH;
System.out.println("Loading the properties file: " + filePath);
configuration = new PropertiesConfiguration(filePath);
//Create new FileChangedReloadingStrategy to reload the properties file based on the given time interval
FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy();
fileChangedReloadingStrategy.setRefreshDelay(PropertiesConstants.REFRESH_DELAY);
configuration.setReloadingStrategy(fileChangedReloadingStrategy);
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
public String getProperty(String key) {
return (String) configuration.getProperty(key);
}
public void setProperty(String key, Object value) {
configuration.setProperty(key, value);
}
public void save() {
try {
configuration.save();
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}

How can I inject a testing value for a Spring Batch configuration class?

I have a Spring Boot / Batch application and would like to write several integration tests. The batch has a FlatFileItemReader and pulls in the file to be read in via yml configuration file. Here's the batch config class:
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Value("${file}")
private File file;
#Bean
public ItemReader<MyClass> reader(LineMapper<MyClass> lineMapper) {
FlatFileItemReader<MyClass> flatFileItemReader = new FlatFileItemReader<MyClass>();
flatFileItemReader.setResource(new FileSystemResource(file));
final int NUMBER_OF_HEADER_LINES = 1;
flatFileItemReader.setLinesToSkip(NUMBER_OF_HEADER_LINES);
flatFileItemReader.setLineMapper(lineMapper);
return flatFileItemReader;
}
The integration test class for testing the reader is:
#SpringApplicationConfiguration(classes = LoadApplication.class)
#TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
StepScopeTestExecutionListener.class })
#RunWith(SpringJUnit4ClassRunner.class)
public class StepScopeTestExecutionListenerIntegrationTests {
#Autowired
private ItemReader<MyClass> reader;
#Rule
public TemporaryFolder testFolder = new TemporaryFolder();
#Bean
public StepExecution getStepExection() {
StepExecution execution = MetaDataInstanceFactory.createStepExecution();
return execution;
}
#Test
public void testGoodData() throws Exception {
try {
File testFile = testFolder.newFile();
PrintWriter writer = new PrintWriter(testFile, "UTF-8");
writer.println("a,b,c");
writer.println("1,2,3");
writer.close();
//ReflectionTestUtils.setField(someObject, "file", testFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
assertNotNull(reader.read());
}
}
In the above test code, what should someObject be set to? Or is there some other way to inject the test file?
The reader has already been created before the call to testGoodData. Simply override the resource that was set on the reader.
That is, replace
ReflectionTestUtils.setField(someObject, "file", testFile);
with this line of code
reader.setResource(new FileSystemResource(testFile));

How to open a repository creating it if it does not exist in JGit?

Came up with:
/**
* Create a repo at the specified directory or open one if it already
* exists. Return a {#link Git} object...
*
* #param p
* Path to the repo root (the dir that contains the .git folder)
* #return a "Git" object to run porcelain commands on...
* #throws GitterException
* if the specified path cannot be resolved to a directory, or
* the repository failed to be build (...) or created
*/
public static Git open(Path p) throws GitterException {
if (!Files.isDirectory(p)) // default LinkOption is follow links
throw new GitterException(p + " can't be resolved to a directory");
Repository localRepo = null;
try {
localRepo = new FileRepository(Paths.get(p.toString(), ".git")
.toFile()); // do I have to specify the .git folder ?
} catch (IOException e) {
throw new GitterException("Failed to build Repository instance", e);
}
try {
localRepo.create();
} catch (IllegalStateException e) {
// ISE when the repo exists !
} catch (IOException e) {
throw new GitterException("Failed to create Repository instance", e);
}
return new Git(localRepo);
}
Am I missing something obvious ? Is it as complicated as this ?
Run across setMustExist(boolean) in the BaseRepositoryBuilder could it be used ?
The shortest solution I could find is to always call create() and ignore the already exists exception.
static Git openOrCreate(File gitDirectory) throws IOException {
Repository repository = new FileRepository(gitDirectory);
try {
repository.create();
} catch(IllegalStateException repositoryExists) {
}
return new Git(repository);
}
The code has its caveats though. The IllegalStateException seems to be an implementation detail that might change and break the above code. In addition, FileRepository resides in an internal package and is not part of the public JGit API.
The following is a solution that avoids these problems:
static Git openOrCreate(File gitDirectory) throws IOException, GitAPIException {
Git git;
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.addCeilingDirectory(gitDirectory);
repositoryBuilder.findGitDir(gitDirectory);
if( repositoryBuilder.getGitDir() == null ) {
git = Git.init().setDirectory(gitDirectory.getParentFile()).call();
} else {
git = new Git(repositoryBuilder.build());
}
return git;
}
Note that exception handling was left out in order to focus on the actual purpose of the snippets.
setMustExist doesn't help with creating a repository on demand. It only causes build()to raise a RepositoryNotFoundException if no repository can be found at the specified location.
Repository represents the repository itself whereas Git serves as a factory to create commands which operate on the repository that it wraps. Next to the factory methods there is close(), which simply delegates to Repository.close().
A Repository maintains a use counter that is decremented by close(). You can continue to use a repository after it was closed (through Git or the Repository's own methods) but it will be re-opened if necessary. To avoid leaking file handles you should not use a repository after it was closed.
An in-depth discussion of of how to access and initialize repositories with JGit can be found
here: http://www.codeaffine.com/2014/09/22/access-git-repository-with-jgit/ and
here: http://www.codeaffine.com/2015/05/06/jgit-initialize-repository/
After RĂ¼diger Herrmann's answer
public static Git open(Path p) throws GitterException {
// default LinkOption is follow links
try {
Files.createDirectories(p);
} catch (IOException e) {
throw new GitterException("Directory " + p + " can't be created", e);
}
RepositoryBuilder repositoryBuilder = new RepositoryBuilder();
if (!isRepo(p, repositoryBuilder)) {
LOGGER.debug(p.toAbsolutePath() + " is not a git repository.");
try {
return Git.init().setDirectory(p.toFile()).call();
} catch (GitAPIException e) {
throw new GitterException("Failed to create Git repository at "
+ p, e);
}
}
try {
return new Git(repositoryBuilder.build());
} catch (IOException e) {
throw new GitterException(
"Failed to create Repository instance at " + p, e);
}
}
static boolean isRepo(Path p, RepositoryBuilder rb)
throws GitterException {
if (!Files.isDirectory(p))
throw new GitterException(p + " can't be resolved to a directory");
final File directory = p.toFile();
rb.addCeilingDirectory(directory); // for find() below
// the docs say "Add a ceiling directory to the search limit list" which
// means in plain english that it will search up to this directory,
// which happens to be our directory, so it will only search there
rb.findGitDir(directory); // find **and** add it to the builder
return rb.getGitDir() != null;
}

how to load class from jar inside equinox server side application in jboss 7

I'm face a problem since few days and I can't get solution. below is my app structure:
I have ejbapp.jar inside MyearDeployedOnJboss7.ear at the same level of equinox-server-side-app.war (built using warproduct) and I want to load class from MyJarToLaoadForEjbapp.jar which is in iModernizeWebClient_1.0.0.jar which is in plugins folder of equinox-server-side-app.war (I want show image of app structure but I cannot send image because forum rules need 10 score to be able to do that)
My question is how to allow ejbapp.jar load classes from "MyJarToLaoadForEjbapp.jar" inside MyWebClient_1.0.0.jar's plugin folder which is in the equinox-server-side-app.war.
I think using servletbridge classloader but no idea how to use it.
in my launch.ini I've:
osgi.*=#null org.osgi.*=#null eclipse.*=#null osgi.parentClassloader=app osgi.contextClassLoaderParent=app
I resolved my proble using Servlet HttpServiceTracker from the OSGI spec. how to do it : write HttpServiceTracker liket that :
public class HttpServiceTracker extends ServiceTracker {
private static final Logger logger = Logger
.getLogger(HttpServiceTracker.class.getName());
public HttpServiceTracker(BundleContext context) {
super(context, HttpService.class.getName(), null);
}
public Object addingService(ServiceReference reference) {
HttpService httpService = (HttpService) context.getService(reference);
logger.info("default context path : "
+ org.eclipse.rap.ui.internal.servlet.HttpServiceTracker.ID_HTTP_CONTEXT);
try {
logger.info("will register servlet ");
httpService.registerServlet("/programLauncherServlet",
new ProgramLauncherServlet(), null, null);
logger.info("servlet has been registred with http context ");
// httpService.registerResources( "/", "/html", null );
} catch (Exception e) {
//e.printStackTrace();
logger.info("The alias '/programLauncherServlet' is already in use");
}
return httpService;
}
public void removedService(ServiceReference reference, Object service) {
logger.info("will unregister servlet ");
HttpService httpService = (HttpService) service;
httpService.unregister("/programLauncher");
super.removedService(reference, service);
logger.info("servlet has been unregistred");
}
in your plugin activator class at method start :
#Override
public void start(BundleContext context) throws Exception {
super.start(context);
Activator.plugin = this;
BundleContext osgiContext = BundleReference.class
.cast(AnyClassOfYourProject.class.getClassLoader()).getBundle()
.getBundleContext();
serviceTracker = new HttpServiceTracker(osgiContext);
serviceTracker.open();
LOGGER.info("servlet published !!");
LOGGER.info("Bundle started.");
}
and for unregister the servlet at the stop method :
public void stop(BundleContext context) throws Exception {
Activator.plugin = null;
serviceTracker.close();
serviceTracker = null;
LOGGER.info("servlet unregistered from context !!");
super.stop(context);
}
that's all. your servlet is accessible outside your eclipse bundle and you can call methods inside the bundle.

Create a cache dependancy on a folder and its sub-folder

In ASP.NET I would like to store an object in the cache which has a dependancy on all the files in specific folder and its sub-folders. Just adding the object with a dependancy on the root folder doesn't work. Is there in any reasonable way to do this other than creating a chain of dependancies on all the files?
I believe you can roll your own cache dependency and use FileSystemMonitor to monitor the filesystem changes.
Update: Sample code below
public class FolderCacheDependency : CacheDependency
{
public FolderCacheDependency(string dirName)
{
FileSystemWatcher watcher = new FileSystemWatcher(dirName);
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Changed);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
}
void watcher_Renamed(object sender, RenamedEventArgs e)
{
this.NotifyDependencyChanged(this, e);
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
this.NotifyDependencyChanged(this, e);
}
}

Resources