I am very new in Jack Rabbit repository.! So please guide me for fetching recent version of a file from Jackrabbit repository.
My code is :
try{
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
Node root = session.getRootNode();
if (!root.hasNode(nodeName)) {
root.addNode(nodeName, "nt:unstructured");
session.save();
}
String extention = FilenameUtils.getExtension(originalFileName);
InputStream stream = new BufferedInputStream(new FileInputStream(file));
Node roseNode = session.getRootNode().getNode(nodeName);
VersionManager vm = session.getWorkspace().getVersionManager();
Node fileNode = null;
if(roseNode.hasNode(fileName.toString()+"."+extention)){
fileNode = roseNode.getNode(fileName.toString()+"."+extention);
vm.checkout(fileNode.getPath());
} else {
fileNode = roseNode.addNode(fileName.toString()+"."+extention, "nt:unstructured");
fileNode.addMixin("mix:versionable");
fileNode.setProperty(extention, fileName.toString());
session.save();
}
Node content = fileNode.addNode("jcr:content", "nt:resource");
Binary binary = session.getValueFactory().createBinary(stream);
content.setProperty("jcr:data", binary);
stream.close();
session.save();
vm.checkin(fileNode.getPath());
I tried this.. But I am getting the older file while fetching..
Please help me on this...
Thanks in advance..
Finally I got it in this way, I tried following query as:
String expression = "select * from [nt:base] as b where name(b)= '"+fileName+"' ";
Query query = queryManager.createQuery(expression, Query.JCR_SQL2);
QueryResult result = query.execute();
NodeIterator iterator = result.getNodes();
VersionManager vm = session.getWorkspace().getVersionManager();
if(iterator.getSize() > 0){
Node node = iterator.nextNode();
Node recentVersionNode = null;
NodeIterator versionIterator = node.getNodes();
/*
A node has multiple content nodes with ("jcr:content", "nt:resource")
these are of different versions, so the file with name abc.pdf
will have multiple versions/content so that we can get
the recent version of content node of the same file.
*/
while(versionIterator.hasNext()){
recentVersionNode = versionIterator.nextNode();
}
finally I got the file node that is uploaded recently in to the Jackrabbit repository.
And we can fetch any version of the file by specifying the index of "jcr:content"
Related
The problem I am facing is I have a file which is having a dynamic number at the last.
For example: Tax_subscription_124.pdf which changes everytime.
Can I upload this particular file as currently I am downloading it in a particular location but not able to upload the same due to dynamic name?
The following code returns the last modified file or folder:
public static File getLastModified(String directoryFilePath)
{
File directory = new File(directoryFilePath);
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
}
}
}
return chosenFile;
}
Note that it required Java 8 or newer due to the lambda expression.
After that
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys(chosenFile);
I have a scenario where a repository contains several version nodes that don't reference any mix:versionable nodes. This is because those versionable nodes have been removed from repository but not their corresponding versions.
This is causing that the JackRabbit Garbage collector cannot remove some files from datastore, because there are versions that still reference them, and consequently the disk space is not properly freed.
I tried to manually remove those versions with the following algorithm:
Obtain a version by its path, let's say: /jcr:system/jcr:versionStorage/40/05/a9/4005a9b2-51d1-4ed1-8c30-934409e05f86/1.14/jcr:frozenNode
Get the jcr:frozenUuid property from the obtained node
Get the node by identifier, using the frozenUuid from step 2
If no such node exists, remove the version
But in the last step I get the following exception:
javax.jcr.nodetype.ConstraintViolationException: Unable to perform operation. Node is protected.
So, my question is. How can I remove the version nodes that are unused?
I'm using jackrabbit-2.2.13.
This is how I remove my versions...
String nodePath...
String versionName...
Session session...
VersionManager versionManager = session.getWorkspace().getVersionManager()
VersionHistory versionHistory = versionManager.getVersionHistory(nodePath);
versionHistory.removeVersion(versionName);
I think this will help you to traverse all the versions so that you can remove or restore.
Node vs = session.getRootNode().getNode("jcr:system").getNode("jcr:versionStorage");
Version v = traverseVersionStorage(vs, 0);
private static Version traverseVersionStorage(Node n, int level)
throws Exception {
Version v = null;
for (NodeIterator it = n.getNodes(); it.hasNext();) {
Node n2 = it.nextNode();
if (n2 instanceof Version && !n2.getName().startsWith("jcr:")) {
v = (Version) n2;
System.out.println("version " + n2.getName() + " of node "+ n2.getParent().getName() + ":");
Node n3 = n2.getNode("jcr:frozenNode");
VersionManager vman=session.getWorkspace().getVersionManager();
Node parent=n3.getParent();
System.out.println(parent.getName());
vman.restore("/any/path/where/to/restore", v, true);
session.save();
}
Version v2 = traverseVersionStorage(n2, level + 1);
v = v == null ? v2 : v;
}
return v;
}
below code is to traverse all versions of a node and remove by versionName
VersionManager versionManager=jcrsession.getWorkspace().getVersionManager();
VersionHistory vHistory=versionManager.getVersionHistory("/absolute/path/of/node/which/versions/to/be/removed");
for (VersionIterator pt = vHistory.getAllVersions(); pt.hasNext();)
{
Version p = pt.nextVersion();
if(p.getName()!="jcr:rootVersion")
{
vHistory.removeVersion(p.getName());
}
}
i have some problem using JSCH to retrieve files/folders and populate them in JTree.
In JSCH to list files using :
Vector list = channelSftp.ls(path);
But i need that lists as java.io.File type. So i can get absolutePath and fileName,
And i don't know how to retrieve as java.io.File type.
Here is my code, and i try it work for local directory.
public void renderTreeData(String directory, DefaultMutableTreeNode parent, Boolean recursive) {
File [] children = new File(directory).listFiles(); // list all the files in the directory
for (int i = 0; i < children.length; i++) { // loop through each
DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());
// only display the node if it isn't a folder, and if this is a recursive call
if (children[i].isDirectory() && recursive) {
parent.add(node); // add as a child node
renderTreeData(children[i].getPath(), node, recursive); // call again for the subdirectory
} else if (!children[i].isDirectory()){ // otherwise, if it isn't a directory
parent.add(node); // add it as a node and do nothing else
}
}
}
Please help me, thanks before :)
you can define some variable in your java bean like
Vector<String> listfiles=new Vector<String>(); // getters and setters
Vector list = channelSftp.ls(path);
setListFiles(list); // This will list the files same as new File(dir).listFiles
in JSCH you can absolute path using ChannelSftp#realpath but unfortunately there no way to get Exact file with extension .But you can use something like this to check whether that file name existed in the target directory or not.
SftpATTRS sftpATTRS = null;
Boolean fileExists = true;
try {
sftpATTRS = channelSftp.lstat(path+"/"+"filename.*");
} catch (Exception ex) {
fileExists = false;
}
Try this (linux in remote server):
public static void cargarRTree(String remotePath, DefaultMutableTreeNode parent) throws SftpException {
//todo: change "/" por remote file.separator
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remotePath); // List source directory structure.
for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.
DefaultMutableTreeNode node = new DefaultMutableTreeNode(oListItem.getFilename());
if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
parent.add(node); // add as a child node
} else{
if (!".".equals(oListItem.getFilename()) && !"..".equals(oListItem.getFilename())) {
parent.add(node); // add as a child node
cargarRTree(remotePath + "/" + oListItem.getFilename(), node); // call again for the subdirectory
}
}
}
}
After you can invoque this method as:
DefaultMutableTreeNode nroot = new DefaultMutableTreeNode(sshremotedir);
try {
cargarRTree(sshremotedir, nroot);
} catch (SftpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
yourJTree = new JTree(nroot);
How to read data of each cell in Selenium WebDriver using Java?
I have tried with following code:
CSVReader reader = new CSVReader(new FileReader("D:/data1.csv"));
expectedLabels = reader.readNext();
FieldNames = reader.readNext();
FieldValues = reader.readNext();
File file = new File("D:/data.csv");
if(file.exists()){
System.out.println("File Exists");
}
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
while((line = bufRdr.readLine()) != null){
StringTokenizer st = new StringTokenizer(line,",");
col=0;
while (st.hasMoreTokens()){
//Following stroing the data of csv
numbers[row][col] = st.nextToken();
col++;
}
System.out.println();
row++;
}
bufRdr.close();
reading csv files become very easy with OPENCSV jar file. I have used this jar file couple of time to read file.
We have predefined class called CSVReader, create an object and pass the csv file path
call readAll() method which will return the csv content in List
using Iterator, you can iterate all the values and use according to application
I have written article on this have a look it might help you.
http://learn-automation.com/how-to-read-csv-files-using-java/
I am not able to provider string type variable in FileReader() function , it shows error while passing filereader() method with parameter in buffer reader fn
code shown below:
String f1= (System.getProperty("User.dir") + "\\Module9TestNG\\src\\TestLogin.xlsx");
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String record;
String url= null;
while ((record = bufRdr.readLine()) != null)
{
String fields[] = record.split(",");
url= fields[0].toString();
}
private String Fpath ="D:\\CkycApps.csv";
String line;
File file = new File(Fpath);
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
while((line = bufRdr.readLine()) != null){
System.out.println(line);
String[] cell= line.split(",");
String FirstName=cell[0];
String MiddleName=cell[1];
}
I have the following code to insert "rose.gif" into a roseNode. But how do I retrieve the file from the repository?
Node roseNode = session.getRootNode().getNode("wiki:encyclopedia/wiki:entry[1]/");
File file = new File("rose.gif");
MimeTable mt = MimeTable.getDefaultTable();
String mimeType = mt.getContentTypeFor(file.getName());
if (mimeType == null) mimeType = "application/octet-stream";
Node fileNode = roseNode.addNode(file.getName(), "nt:file");
System.out.println( fileNode.getName() );
Node resNode = fileNode.addNode("jcr:content", "nt:resource");
resNode.setProperty("jcr:mimeType", mimeType);
resNode.setProperty("jcr:encoding", "");
resNode.setProperty("jcr:data", new FileInputStream(file));
Calendar lastModified = Calendar.getInstance();
lastModified.setTimeInMillis(file.lastModified());
resNode.setProperty("jcr:lastModified", lastModified);
//retrieve file and output as rose-out.gif
File outputFile = new File("rose-out.gif");
FileOutputStream out = new FileOutputStream(outputFile);
The only thing you really need to do is get the name of the file from the name of the "nt:file" node, and the content for the file from the "jcr:data" property on the "jcr:content" child node.
JCR 1.0 and 2.0 differ a bit in how you get the stream for the binary "jcr:data" property value. If you're using JCR 1.0, then the code would be like this:
Node fileNode = // find this somehow
Node jcrContent = fileNode.getNode("jcr:content");
String fileName = fileNode.getName();
InputStream content = jcrContent.getProperty("jcr:data").getStream();
If you're using JCR 2.0, the last line is a bit different because you first have to get the Binary object from the property value:
InputStream content = jcrContent.getProperty("jcr:data").getBinary().getStream();
You can then use standard Java stream utility to write the bytes from the 'content' stream into the file.
When you're done with the Binary object, be sure to call the Binary's dispose() method to tell signal that you're done with the Binary and that the implementation can release all resources acquired by the Binary object. You should always do this, even though some JCR implementations try to catch programming errors by returning a stream that, when closed, will automatically call dispose() for you.