I have a SHA-1 of a newly cloned repository. I want the author indent of this SHA-1.
So I need to use RevWalk and iterate the whole repository? Or is there a findXX method or other code I can use to get the RevCommit or another object that has the PersonIdent?
What I tried:
public void authorInfoOf(Repository repo, AnyObjectId head) {
try {
try (RevWalk walk = new RevWalk(repo)) {
ObjectDatabase db = repo.getObjectDatabase();
ObjectLoader k = repo.newObjectReader().open(head);
ObjectReader s;
// repo.newObjectReader().open(head);
ObjectStream st = k.openStream();
// RevWalk rw2 = new RevWalk(k);
RevCommit commit = null;// walk.parseCommit(ref.getObjectId());
PersonIdent authorIndent = commit.getAuthorIdent();
System.out.println("\nCommit-Message: " + commit.getFullMessage() + " " + authorIndent.getEmailAddress());
}
} catch (Exception e) {
System.out.println("Authir info of Anybject id Err " + e);
e.printStackTrace();
}
}
The RevCommit represents a particular commit in a Git repository. Use RevWalk::parseCommit() to obtain the RevCommit for a specific object id/SHA-1.
For example:
try( RevWalk walk = new RevWalk( repository ) ) {
RevCommit commit = walk.parseCommit( ref.getObjectId() );
}
parseCommit returns the matching commit object for the given ObjectId.
In order to convert a SHA-1 (string) into an ObjectId, use ObjectId::fromString():
ObjectId commitId = ObjectId.fromString( "ab434..." );
See also: How to obtain the RevCommit or ObjectId from a SHA1 ID string with JGit?
In the above example, a Ref was used to reference the object id. Refs represent named references to object ids like branches, tags, or special refs like HEAD. Repository::exactRef() can be used to resolve a string to a Ref object.
For example:
Ref headRef = repository.exactRef( "HEAD" );
This worked for me:
public RevCommit getCommit(String idString, Repository repository, Git git){
try{
ObjectId o1 = repository.resolve(idString);
if(o1 != null){
try( RevWalk walk = new RevWalk( repository ) ) {
RevCommit commit = walk.parseCommit( o1 );
PersonIdent ai = commit.getAuthorIdent();
System.out.println("bbb >>" + ai.getEmailAddress() + "|" + ai.getTimeZone() + "|" + ai.getWhen() + ", ref :" + idString);
return commit;
}
}else{
System.err.println("Could not get commit with SHA :" + idString);
}
}catch (Exception e) {
System.out.println("err :" + e);
e.printStackTrace();
}
return null;
}
Related
I have several CMIS requests and need to do them in parallel. But when I try it (using CompletableFutire or stream().parallel(), I got:
java.util.concurrent.ExecutionException: net.sf.acegisecurity.AuthenticationCredentialsNotFoundException: A valid SecureContext was not provided in the RequestContext
For that queries I do :
#Autowired
#Qualifier("searchService")
private org.alfresco.service.cmr.search.SearchService searchService;
....
searchService.query(searchParameters);
What am I doing wrong?
The following code is one of my attempt to perform CMIS in parallel:
List<CompletableFuture<Form14Row>> requests = Arrays.asList(setUpRow(1,beginnigString, endString, docType, NDBaseDocumentModel.DOC_KIND_GOST_R, searchParameters, "ГОСТ Р"),
setUpRow(2,beginnigString, endString, docType, NDBaseDocumentModel.DOC_KIND_GOST, searchParameters, "ГОСТ") );
CompletableFuture<Void> allRequests = CompletableFuture.allOf(
requests.toArray(new CompletableFuture[requests.size()])
);
CompletableFuture<List<Form14Row>> allPageContentsFuture = allRequests.thenApply(v -> {
return requests.stream()
.map(pageContentFuture -> pageContentFuture.join())
.collect(Collectors.toList());
});
//java.util.concurrent.ExecutionException: net.sf.acegisecurity.AuthenticationCredentialsNotFoundException: A valid SecureContext was not provided in the RequestContext
try {
List<Form14Row> rowss = allPageContentsFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
...
private CompletableFuture<Form14Row> setUpRow(Integer index, String beginnigString, String endString, String docType, String docKind, SearchParameters searchParameters, String groupPosition) {
return CompletableFuture.supplyAsync(() -> {
String cql = "SELECT p.cmis:objectId FROM ecmcnddoc:common_attr_aspect AS d JOIN ecmcnddoc:biblio_attr_aspect AS p ON d.cmis:objectId = p.cmis:objectId JOIN ecmcnddoc:reg_attr_aspect AS s ON s.cmis:objectId = p.cmis:objectId JOIN ecmcnddoc:spec_attr_aspect AS asp ON asp.cmis:objectId = p.cmis:objectId WHERE p.cmis:objectTypeId='D:" + docType + "' AND d.ecmcnddoc:doc_kind_cp_ecmcdict_value='" + docKind + "' AND p.ecmcnddoc:biblio_fond='" + NDBaseDocumentModel.BIBLIO_FUND + "' AND s.ecmcnddoc:doc_reg_date >= TIMESTAMP '" + beginnigString + "T00:00:00.000+00:00' AND s.ecmcnddoc:doc_reg_date <= TIMESTAMP '" + endString + "T00:00:00.000+00:00' AND (asp.ecmcnddoc:doc_status='draft' OR asp.ecmcnddoc:doc_status='actual')";
searchParameters.setQuery(cql);
ResultSet rs = customSearchService.query(searchParameters); // Exception here
Form14Row isoRow = new Form14Row();
isoRow.setCount(rs.length());
isoRow.setIndex(index);
isoRow.setKindName(groupPosition);
return isoRow;
});
}
Everything works fine in serial execution
Security context is binded to main thread and is not propagated to children threads, you would need to set one.
Maybe you could try to adapt this snippet:
CompletableFuture.runAsync(() -> {
try {
AuthenticationUtil.pushAuthentication();
AuthenticationUtil.setFullyAuthenticatedUser(userName);
// Do your stuff...
} finally {
AuthenticationUtil.popAuthentication();
}
});
public ActionResult Edit([Bind(Include = "id,category,title,image,active,ImageFile")] page_image page_image)
{
if (ModelState.IsValid)
{
if (page_image.ImageFile != null)
{
string fileName = Path.GetFileNameWithoutExtension(page_image.ImageFile.FileName);
string extension = Path.GetExtension(page_image.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssff") + extension;
page_image.image = "/Uploads/page_images/" + fileName;
fileName = Path.Combine(Server.MapPath("/Uploads/page_images"), fileName);
page_image.ImageFile.SaveAs(fileName);
}
db.Entry(page_image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.category = new SelectList(db.page, "id", "title", page_image.category);
return View(page_image);
}
Here I'm able to edit the User but is not showing the previous Image so If I click submit with out loading a new Image it will delete the previous one. What I have to do is the Edit view, I want it to show the name of the image. Can you guide me to the right direction?
The problem is because you save the view model as is to the Database, you should have a DTO. Anyway, try to get the ImageFile from the DB again, in case it submitted null.
if(page_image.ImageFile != null)
{
// your uploading logic
}
else
{
var oldData = db.Set<page_image>().Where(x => x.id == page_image.id).FirstOrDefault();
page_image.ImageFile = oldData.ImageFile;
}
If page_image.Image is null then get previous image and assign
if (page_image.ImageFile != null)
{
string fileName = Path.GetFileNameWithoutExtension(page_image.ImageFile.FileName);
string extension = Path.GetExtension(page_image.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssff") + extension;
page_image.image = "/Uploads/page_images/" + fileName;
fileName = Path.Combine(Server.MapPath("/Uploads/page_images"), fileName);
page_image.ImageFile.SaveAs(fileName);
} else {
// get existing image from database
var data = db.page_image.AsNoTracking().Where(b => b.id == page_image.id).FirstOrDefault();
//assign to existing image
page_image.image = data.image ;
}
db.Entry(page_image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
Update :
Error is throwing here because of same instance of dbcontext. You can create new instance to fetch or do as following.
var data = db.page_image.AsNoTracking().Where(b => b.id == page_image.id).FirstOrDefault();
or
using (var db2 = new YourDbContext())
{
var data = db2.page_image.Where(b => b.id == page_image.id).FirstOrDefault();
}
guys! I'm trying to append folder to user.home property. It working nice, while I'm using just one additional folder. But when I try to make another two additions (so it looks like user.home+folder1+folder2+folder3) it trows ---
java.lang.IllegalArgumentException: Folder parameter must be a valid folder---
. My though that there is some restriction, but can't find out where.
String fullRoute = null;
File homeDir = new File("MLog");
if (!SiteCo.getEditor().getText().isEmpty() &&
!InciDate.getEditor().getText().isEmpty()) {
homeDir.mkdirs();
fullRoute = System.getProperty("user.home") + File.separator +
//SaveVarTo.getLastVisitedDirectory() +
SaveVarTo.AddPath(SiteCo.getValue().toString()) +
File.separator + SaveVarTo.AddPath(InciDate.getValue().toString());
}
else {homeDir.mkdirs();
// File.separator+homeDir.toString() - without it
fullRoute =
System.getProperty("user.home")+File.separator+homeDir.toString();}
System.out.println(fullRoute);
fileChooser.setInitialDirectory(new File(fullRoute));
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("XML Files", "*.xml"));
//sample of method
public class Variables{
public String AddPath(String name) {
if (!name.isEmpty()) {
//File nou = new File(getLastVisitedDirectory() +"\\" + name);
File nou = new File(name);
if (!nou.exists()) {
nou.mkdirs();
} else {
System.out.println("Folder already exists");
}
}
else{name = null;}
return name;
}}
String fullRoute = null;
File homeDir = new File(System.getProperty("user.home"));
if (SiteCo.getValue() !=null && InciDate.getValue() !=null) {
System.out.println(SaveVarTo.getMainFolder());
fullRoute = homeDir + File.separator + SaveVarTo.getMainFolder() +
File.separator + SiteCo.getValue().toString() +
File.separator + InciDate.getValue().toString();
} else {
fullRoute = homeDir.toString();
}
System.out.println(fullRoute);
File fhd = new File(fullRoute);
if (!fhd.exists())
fhd.mkdirs();
fileChooser.setInitialDirectory(fhd);
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("XML Files", "*.xml"));
My program is caught in a cycle that never ends, and I can't see how it get into this trap, or how to avoid it.
It's parsing Wikipedia data and I think it's just following a connected component around and around.
Maybe I can store the pages I've visited already in a set and if a page is in that set I won't go back to it?
This is my project, its quite small, only three short classes.
This is a link to the data it generates, I stopped it short, otherwise it would have gone on and on.
This is the laughably small toy input that generated that mess.
It's the same project I was working on when I asked this question.
What follows is the entirety of the code.
The main class:
public static void main(String[] args) throws Exception
{
String name_list_file = "/home/matthias/Workbench/SUTD/nytimes_corpus/NYTimesCorpus/2005/01/02/test/people_test.txt";
String single_name;
try (
// read in the original file, list of names, w/e
InputStream stream_for_name_list_file = new FileInputStream( name_list_file );
InputStreamReader stream_reader = new InputStreamReader( stream_for_name_list_file , Charset.forName("UTF-8"));
BufferedReader line_reader = new BufferedReader( stream_reader );
)
{
while (( single_name = line_reader.readLine() ) != null)
{
//replace this by a URL encoder
//String associated_alias = single_name.replace(' ', '+');
String associated_alias = URLEncoder.encode( single_name , "UTF-8");
String platonic_key = single_name;
System.out.println("now processing: " + platonic_key);
Wikidata_Q_Reader.getQ( platonic_key, associated_alias );
}
}
//print the struc
Wikidata_Q_Reader.print_data();
}
The Wikipedia reader / value grabber:
static Map<String, HashSet<String> > q_valMap = new HashMap<String, HashSet<String> >();
//public static String[] getQ(String variable_entity) throws Exception
public static void getQ( String platonic_key, String associated_alias ) throws Exception
{
//get the corresponding wikidata page
//check the validity of the URL
String URL_czech = "https://www.wikidata.org/wiki/Special:ItemByTitle?site=en&page=" + associated_alias + "&submit=Search";
URL wikidata_page = new URL(URL_czech);
HttpURLConnection wiki_connection = (HttpURLConnection)wikidata_page.openConnection();
InputStream wikiInputStream = null;
try
{
// try to connect and use the input stream
wiki_connection.connect();
wikiInputStream = wiki_connection.getInputStream();
}
catch(IOException e)
{
// failed, try using the error stream
wikiInputStream = wiki_connection.getErrorStream();
}
BufferedReader wiki_data_pagecontent = new BufferedReader(
new InputStreamReader(
wikiInputStream ));
String line_by_line;
while ((line_by_line = wiki_data_pagecontent.readLine()) != null)
{
// if we can determine it's a disambig page we need to send it off to get all
// the possible senses in which it can be used.
Pattern disambig_pattern = Pattern.compile("<div class=\"wikibase-entitytermsview-heading-description \">Wikipedia disambiguation page</div>");
Matcher disambig_indicator = disambig_pattern.matcher(line_by_line);
if (disambig_indicator.matches())
{
//off to get the different usages
Wikipedia_Disambig_Fetcher.all_possibilities( platonic_key, associated_alias );
}
else
{
//get the Q value off the page by matching
Pattern q_page_pattern = Pattern.compile("<!-- wikibase-toolbar --><span class=\"wikibase-toolbar-container\"><span class=\"wikibase-toolbar-item " +
"wikibase-toolbar \">\\[<span class=\"wikibase-toolbar-item wikibase-toolbar-button wikibase-toolbar-button-edit\"><a " +
"href=\"/wiki/Special:SetSiteLink/(.*?)\">edit</a></span>\\]</span></span>");
Matcher match_Q_component = q_page_pattern.matcher(line_by_line);
if ( match_Q_component.matches() )
{
String Q = match_Q_component.group(1);
// 'Q' should be appended to an array, since each entity can hold multiple
// Q values on that basis of disambig
put_to_hash( platonic_key, Q );
}
}
}
wiki_data_pagecontent.close();
// \\ // ! PRINT IT ! // \\ // \\ // \\ // \\ // \\ // \\
for (Map.Entry<String, HashSet<String> > entry : q_valMap.entrySet())
{
System.out.println(entry.getKey()+" : " + Arrays.deepToString(q_valMap.entrySet().toArray()) );
}
}
// add Q values to their arrayList in the hash map at the index of the appropriate entity
public static HashSet<String> put_to_hash(String key, String value )
{
HashSet<String> valSet;
if (q_valMap.containsKey(key)) {
valSet = q_valMap.get(key);
} else {
valSet = new HashSet<String>();
q_valMap.put(key, valSet);
}
valSet.add(value);
return valSet;
}
// add Q values to their arrayList in the hash map at the index of the appropriate entity
public static void print_data()
{
System.out.println("THIS IS THE FINAL DATA SET!!!");
// \\ // ! PRINT IT ! // \\ // \\ // \\ // \\ // \\ // \\
for (Map.Entry<String, HashSet<String> > entry : q_valMap.entrySet())
{
System.out.println(entry.getKey()+" : " + Arrays.deepToString(q_valMap.entrySet().toArray()) );
}
}
Dealing with disambiguation pages:
public static void all_possibilities( String platonic_key, String associated_alias ) throws Exception
{
System.out.println("this is a disambig page");
//if it's a disambig page we know we can go right to the Wikipedia
//get it's normal wiki disambig page
String URL_czech = "https://en.wikipedia.org/wiki/" + associated_alias;
URL wikidata_page = new URL(URL_czech);
HttpURLConnection wiki_connection = (HttpURLConnection)wikidata_page.openConnection();
InputStream wikiInputStream = null;
try
{
// try to connect and use the input stream
wiki_connection.connect();
wikiInputStream = wiki_connection.getInputStream();
}
catch(IOException e)
{
// failed, try using the error stream
wikiInputStream = wiki_connection.getErrorStream();
}
// parse the input stream using Jsoup
Document docx = Jsoup.parse(wikiInputStream, null, wikidata_page.getProtocol()+"://"+wikidata_page.getHost()+"/");
//this can handle the less structured ones.
Elements linx = docx.select( "p:contains(" + associated_alias + ") ~ ul a:eq(0)" );
for (Element linq : linx)
{
System.out.println(linq.text());
String linq_nospace = URLEncoder.encode( linq.text() , "UTF-8");
Wikidata_Q_Reader.getQ( platonic_key, linq_nospace );
}
}
I'm having a hard time getting any of the inserts to work with SqlLite. I have a table created with the following schema:
create table drink_category ( _id integer not null primary key autoincrement, value unique);
When the attached code runs, I get a SQLiteCantOpenDatebaseException with the error message "cannot open database file (code 14)".
As you can see in the code, I access the table with a query without a problem. I also do a db.isOpen() to verify the database is OK. I have even added code after the block with the insert and everything works OK. Any help would be greatly appreciated.
public Boolean add(String strValue)
{
Boolean bStatus = true;
String strSql;
String sqlValue = strValue.replaceAll("'","\'\'");
if (bStatus)
{
if (strValue.isEmpty())
{
BarDB.getInstance().setErrorMessage("No value entered.");
bStatus = false;
}
}
if (bStatus)
{
strSql = "select value from " + "drink_category" + " where value = '" + sqlValue + "' ";
Cursor cursor = SqlDbAdapter.getInstance().getDatabase().rawQuery(strSql, null);
if (null == cursor)
{
BarDB.getInstance().setErrorMessage("Problem with the database.");
bStatus = false;
}
else if (cursor.getCount() > 0)
{
BarDB.getInstance().setErrorMessage("A Drink Category with that name already exists.");
bStatus = false;
}
}
if (bStatus)
{
ContentValues cvValues = new ContentValues();
cvValues.put("value", sqlValue);
SQLiteDatabase db = SqlDbAdapter.getInstance().getDatabase();
if (db.isOpen())
{
try
{
long lerror = db.insertOrThrow("drink_category", null, cvValues);
}
catch (SQLiteException sqle)
{
BarDB.getInstance().setErrorMessage(sqle.toString());
bStatus = false;
}
}
}
return bStatus;
}
FOUND IT: I am running this on an emulator and I was storing the database file in /data/data. I guess when you do an insert, sqlite needs to write to a journal file and that directory is read only. I moved the database to /data/data//databases and things are working OK now. A better error message would have been much more helpful!