What is the equivalent of "git rev-parse HEAD:directoryPath" in JGit - jgit

I tried this - but it does not give the same result as command line:
ObjectId headID = repo.resolve(Constants.HEAD);
RevCommit commit = revWalk.parseCommit(headID);
try (TreeWalk walk = new TreeWalk(repo)) {
walk.setRecursive(true);
walk.setFilter(PathFilter.create("directoryPath"));
walk.reset(commit.getTree());
if (!walk.next()) {
return null;
}
ObjectId id = walk.getObjectId(0);
return ObjectId.toString(id);
}

Related

arcengine isaveas2 Failed to copy raster dataset

The source code are following:
when run into the last pSaveAs.SaveAs... then the computer say "failed to copy raster dataset".
The source code are following:
private void SaveRaster(IRasterDataset2 mygeoDataset,string sFormat,string filePath,string fileName )
{
`ISaveAs2` pSaveAs = mygeoDataset as ISaveAs2;
if(!pSaveAs.CanSaveAs(sFormat))
{
MessageBox.Show("no support file type");
return;
}
IWorkspaceFactory pworspaceFactory = new RasterWorkspaceFactoryClass();
IWorkspace pWorkspace = null;
pWorkspace = pworspaceFactory.OpenFromFile(filePath, 0);
pSaveAs.SaveAs(fileName, pWorkspace, "GRID");
}

SQLite SQLITE_MISUSE error in Swift 3

I´m trying to create a function that injects queries to SQLite in Swift 3 but I´m having problems with the escaping chars
class SQLiteQueryManager {
static func insertNewStore(StoreId: Int64, Name: String, Address: String) -> Bool {
let vCommand = "INSERT INTO Store (Id, StoreId, Name, Address) VALUES (\(SQLiteConnectionManager.nextID("Store")),\(StoreId),'\(Name)','\(Address)')"
return SQLiteConnectionManager.insertDatabase(vCommand)
}
}
The problem ins that when I´m trying to execute SQLiteConnectionManager.insertDatabase function the string that I´m sending to SQLite looks like this:
INSERT INTO Store (Id, StoreId, Name, Address) VALUES (1,1,\'Tienda
1\',\'Dirección 1\')
And SQLite is rejecting the query.
I have tried .replacingOccurrences(of: "\", with: "") but it dose not work.
I have tested in DB Browser the query and works
INSERT INTO Store (Id, StoreId, Name, Address) VALUES (1,1,'Tienda
1','Dirección 1')
How can I remove the \??
My SQLite function is this:
static func insertDatabase(_ pCommand: String) -> Bool
{
var vInsertStatement: OpaquePointer? = nil
let vDB: OpaquePointer = SQLiteConnectionManager.openDatabase()
var vReturn: Bool
if sqlite3_prepare_v2(vDB, pCommand.replacingOccurrences(of: "\\", with: ""), -1, &vInsertStatement, nil) == SQLITE_OK {
if sqlite3_step(vInsertStatement) == SQLITE_DONE {
print("insertDatabase() correct with statement \(pCommand)")
vReturn = true
} else {
print("insertDatabase() fail with statement \(pCommand)")
vReturn = false
}
} else {
print("insertDatabase() pCommand could not be prepared")
vReturn = false
}
sqlite3_finalize(vInsertStatement)
sqlite3_close(vDB)
return vReturn
}
The Open function return ok so my guess is the escaping char or something like that.
This is the print output of the function:
insertDatabase() fail with statement INSERT INTO Store (Id, StoreId,
Name, Address) VALUES (1,1,'Tienda 1','Dirección 1')
UPDATE 1:
sqlite3_step(vInsertStatement) is returning SQLITE_MISUSE but I can't find the mistake, the DB is in the bundle and the open() statement work and a select I'm doing works, what can be wrong?
UPDATE 2:
This is how I open de DB and returns OK:
private static func openDatabase() -> OpaquePointer {
var vDB: OpaquePointer? = nil
mDBURL = Bundle.main.url(forResource: "ARDB", withExtension: "db")
if let vDBURL = mDBURL{
if sqlite3_open(vDBURL.absoluteString, &vDB) == SQLITE_OK {
print("The database is open.")
} else {
print("Unable to open database in method openDatabase().")
}
return vDB!
} else {
return vDB!
}
}
Then I run this to get the last Id and works:
static func nextID(_ pTableName: String!) -> Int
{
var vGetIdStatement: OpaquePointer? = nil
let vDB: OpaquePointer = SQLiteConnectionManager.openDatabase()
let vCommand = String(format: "SELECT Id FROM %# ORDER BY Id DESC LIMIT 1", pTableName)
var vResult: Int32? = 0
if sqlite3_prepare_v2(vDB, vCommand, -1, &vGetIdStatement, nil) == SQLITE_OK {
if sqlite3_step(vGetIdStatement) == SQLITE_ROW {
vResult = sqlite3_column_int(vGetIdStatement, 0)
print("nextID() correct with statement \(vCommand)")
} else {
print("nextID() fail with statement \(vCommand)")
}
} else {
print("nextID() statement could not be prepared")
}
sqlite3_finalize(vGetIdStatement)
sqlite3_close(vDB)
var id: Int = 1
if (vResult != nil)
{
id = Int(vResult!) + 1
}
return id
}
I have change my insert function to this with or without cString statement:
static func insertDatabase(_ pCommand: String) -> Bool
{
var vInsertStatement: OpaquePointer? = nil
let vDB: OpaquePointer = SQLiteConnectionManager.openDatabase()
var vReturn: Bool
if sqlite3_prepare_v2(vDB, pCommand.cString(using: .utf8), -1, &vInsertStatement, nil) == SQLITE_OK {
if sqlite3_step(vInsertStatement) == SQLITE_DONE {
print("insertDatabase() correct with statement \(pCommand)")
vReturn = true
} else {
print("insertDatabase() fail with statement \(pCommand) with error: \(sqlite3_step(vInsertStatement)) : \(sqlite3_errmsg(vDB))")
vReturn = false
}
} else {
print("insertDatabase() \(pCommand) could not be prepared with error: \(sqlite3_prepare_v2(vDB, pCommand.cString(using: .utf8), -1, &vInsertStatement, nil))")
vReturn = false
}
sqlite3_finalize(vInsertStatement)
sqlite3_close(vDB)
return vReturn
}
If I print the sqlite3_errmsg(vDB) in the console I get this that does not help:
▿ Optional> ▿ some : 0x0000000105347e80
- pointerValue : 4382293632
If I print sqlite3_step(vInsertStatement) returns 21 SQLITE_MISUSE
Any help will be appreciated.
Thanks in advance.
I just found the problem, we don´t have permission of writing in the main bundle.
So you have to copy the DB first, here is the code:
private static func copyFromBundle () {
let vBundlePath = Bundle.main.path(forResource: "ARDB", ofType: ".db")
let vDestPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let vFileManager = FileManager.default
let vFullDestPath = URL(fileURLWithPath: vDestPath).appendingPathComponent("ARDB.db")
mDocumentsPath = ""
if vFileManager.fileExists(atPath: vFullDestPath.path){
print("Database file exist don´t copy.")
mDocumentsPath = vFullDestPath.path
} else {
if vFileManager.fileExists(atPath: vBundlePath!) {
do {
try vFileManager.copyItem(atPath: vBundlePath!, toPath: vFullDestPath.path)
print("Database file does´t exist copy it.")
mDocumentsPath = vFullDestPath.path
} catch {
print("copyFromBundle() fail with error: ",error)
}
}
}
}
Thanks for the help.
Happy coding.

FileStatus use to recurse directory

I have following directory structure,
Dir1
|___Dir2
|___Dir3
|___Dir4
|___File1.gz
|___File2.gz
|___File3.gz
The subdirectories are just nested and donot contain any files
I am trying to use the following for recursing through a directory on HDFS.If its a directory I append /* to the path and addInputPath
arg[0] = "path/to/Dir1"; // given at command line
FileStatus fs = new FileStatus();
Path q = new Path(args[0]);
FileInputFormat.addInputPath(job,q);
Path p = new Path(q.toString()+"/*");
fs.setPath(p);
while(fs.isDirectory())
{
fs.setPath(new Path(p.toString()+"/*"));
FileInputFormat.addInputPath(job,fs.getPath());
}
But the code doesnt seem to go in the while loop and I get not a File Exception
Where is the if statement you are referring to?
Anyway, you may have a look at these utility methods which add all files within a directory to a job's input:
Utils:
public static Path[] getRecursivePaths(FileSystem fs, String basePath)
throws IOException, URISyntaxException {
List<Path> result = new ArrayList<Path>();
basePath = fs.getUri() + basePath;
FileStatus[] listStatus = fs.globStatus(new Path(basePath+"/*"));
for (FileStatus fstat : listStatus) {
readSubDirectory(fstat, basePath, fs, result);
}
return (Path[]) result.toArray(new Path[result.size()]);
}
private static void readSubDirectory(FileStatus fileStatus, String basePath,
FileSystem fs, List<Path> paths) throws IOException, URISyntaxException {
if (!fileStatus.isDir()) {
paths.add(fileStatus.getPath());
}
else {
String subPath = fileStatus.getPath().toString();
FileStatus[] listStatus = fs.globStatus(new Path(subPath + "/*"));
if (listStatus.length == 0) {
paths.add(fileStatus.getPath());
}
for (FileStatus fst : listStatus) {
readSubDirectory(fst, subPath, fs, paths);
}
}
}
Use it in your job runner class:
...
Path[] inputPaths = Utils.getRecursivePaths(fs, inputPath);
FileInputFormat.setInputPaths(job, inputPaths);
...

How to store tree structure using neo4j and gremlin

I want to store following directory tree structure using neo4j local database and Gremlin in Java.
(ROOT)
/ \
Dir2 Dir3
/ \ \
Dir4 Dir5 Dir6
/
Dir7
I have defined a method StorePath(String path).
What i want : When i call StorePath(path) with path = "Root\Dir2\Dir4\Dir7" then data should be stored as follows
Root
/
Dir2
/
Dir4
/
Dir7
where Root and Dir* are vertices with blank edges.
Please help me with the java code.
private static final RelationshipType SUB_DIR = DynamicRelationshipType.withName("SUB_DIR");
public void storePath(String path) {
Node dir = graphDb.getReferenceNode();
for (String name : path.split(File.separator)) {
dir = obtainSubDir(dir, name);
}
}
private Node obtainSubDir(Node dir, String name) {
Node subDir = getSubDir(dir,name);
if (subDir!=null) return subDir;
return createSubDir(dir, name);
}
private Node getSubDir(Node dir, String name) {
for (Relationship rel : dir.getRelationships(SUB_DIR, Direction.OUTGOING)) {
final Node subDir = rel.getEndNode();
if (subDir.getProperty("name", "").equals(name)) return subDir;
}
return null;
}
private Node createSubDir(Node dir, String name) {
Node subDir = dir.getGraphDatabase().createNode();
subDir.setProperty("name", name);
dir.createRelationshipTo(subDir, SUB_DIR);
return subDir;
}

Updating a foreign key to Null value using nhibernate

I have two table BuildGroup and table DocumentTemplate. DocumentTemplate table has BuildGroupId as foreign key which is nullable. In a certain senario I update BuildGroupId in DocumentTemplate table.
public bool EditDocTempForBldGrp(int docId, int bldGrpId)
{
try
{
using (ISession session = Document.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
HSDocumentTemplate objDocBO = new HSDocumentTemplate();
objDocBO = GetDocumentDetailsById(docId);
HSBuildGroup objBldGrp = new HSBuildGroup();
if (bldGrpId != 0)
{
objBldGrp.Id = bldGrpId;
}
else
{
//int ? bldid = null;
//objDocBO.HSBuildGroup.Id = null;
//objDocBO.HSBuildGroup.Id = DBNull.Value;
//objDocBO.HSBuildGroup.Id = -1;
}
objDocBO.HSBuildGroup = objBldGrp;
session.Update(objDocBO);
transaction.Commit();
}
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
In another senario I need to set BuildGroupId in DocumentTemplate table again to
dbnull.value. I tried with different cases as in else block. It giving the error : Cannot
implicitly convert type 'System.DBNull' to 'int'.
How can I update a foreign key value with NULL? Any help will be appreciated.
A few observations:
You should not assign the Id to a HSBuildGroup object, but instead load the instance via Session.Load() in case the bldGrpId is not 0.
You can just set the build group of a document to null like this:
objDocBO.HSBuildGroup = null;
NHibernate will take care of the rest.
Hope that helps.
Use Session.Load and null as Kay Herzam said.
You must to be sure than the document exist to call session.Load. Example:
public bool EditDocTempForBldGrp(int docId, int bldGrpId)
{
try
{
using (ISession session = Document.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Get<HSDocumentTemplate>(docId).HSBuildGroup
= bldGrpId = 0 ? null : session.Load<HSBuildGroup>(bldGrpId);
transaction.Commit();
}
}
}
This way nhibernate will execute something like,
select ... from DocumentTemplate where DocId = ..;
UPDATE DocumentTemplate SET .... , BuildGroupId = null where DocumentId = XX;
or
select ... from DocumentTemplate where DocId = ..;
UPDATE DocumentTemplate SET .... , BuildGroupId = YY where DocumentId = XX;
Note there is no select for BuildGroup to the database.
If you are not sure about the existence of the build group, your code should look like:
public bool EditDocTempForBldGrp(int docId, int bldGrpId)
{
try
{
using (ISession session = Document.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Get<HSDocumentTemplate>(docId).HSBuildGroup
= session.Get<HSBuildGroup>(bldGrpId);
transaction.Commit();
}
}
}
This way nhibernate will execute something like,
select ... from DocumentTemplate where DocId = ..;
SELECT .... FROM BuildGroup where buildgroupid = ZZ;
UPDATE DocumentTemplate SET .... , BuildGroupId = null where DocumentId = XX;
Get automatically returns null if the object doesn't exist.
Finally you don't need to call Session.Update() this is for reattaching an entity. Everything associated to a Session will be flushed when you commit the transaction.

Resources