jgit pull issue HEAD DETACHED - jgit

I am trying to use jgit to pull the changes from a git repository.
I am facing minor issues with HEAD DETACHED error when I do a pull
I have read other answers here on stackoverflow. Trying those solutions does not seem to help.
I have 2 remote branches
1. staging
2. master
Here is the sample code:
public static void main(String [] args){
final String GIT_STR = "https://github.com/newlifer2/testNewLiferRepo.git";
final String localRepositoryPath = new File("").getAbsolutePath() + File.separatorChar;
try{
//setting up local repository as just testNewLiferRepo
String repoName = localRepositoryPath + "testNewLiferRepo";
File f = new File(repoName);
Repository localRepo = new FileRepository(repoName + File.separatorChar + ".git");
ObjectId oldObjid = null;
Git git = null;
if (f.exists()) {
oldObjid = localRepo.resolve(Constants.HEAD);
git = Git.open(f);
git.pull().call();
ObjectId currentObjid = localRepo.resolve(Constants.HEAD);
git.getRepository().close();
} else {
git = Git.cloneRepository().setURI(GIT_STR).setDirectory(new File(repoName)).call();
ObjectId currentObjid =localRepo.resolve(Constants.HEAD);
if(!localRepo.getBranch().equalsIgnoreCase("staging")){
git.checkout().setName("refs/remotes/origin/staging").setForce(true).call();
}
git.getRepository().close();
}
} catch (InvalidRemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GitAPIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RevisionSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AmbiguousObjectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IncorrectObjectTypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can update the version in the testXML file on the repository to test the pull.
Any pointers are highly appreciated
Thanks

Looks like I had my statements switched. Here is a new solution
public static void main(String [] args){
final String GIT_STR = "https://github.com/newlifer2/testNewLiferRepo.git";
final String localRepositoryPath = new File("").getAbsolutePath() + File.separatorChar;
SSHSessionFactory sessionFactory = new SSHSessionFactory();
sessionFactory.Initialize();
SshSessionFactory.setInstance(sessionFactory);
try{
//setting up local repository as just testNewLiferRepo
String repoName = localRepositoryPath + "testNewLiferRepo";
File f = new File(repoName);
Repository localRepo = new FileRepository(repoName + File.separatorChar + ".git");
ObjectId oldObjid = null;
Git git = null;
if (f.exists()) {
oldObjid = localRepo.resolve(Constants.HEAD);
git = Git.open(f);
Map<String,Ref> m = git.getRepository().getAllRefs();
System.out.println("Current Branch: "+git.getRepository().getBranch());
if(git.getRepository().isValidRefName("refs/remotes/origin/staging")){
System.out.println("Valid");
}
git.pull().call();
git.checkout().setName("staging").call();
ObjectId currentObjid = localRepo.resolve(Constants.HEAD);
git.getRepository().close();
} else {
git = Git.cloneRepository().setURI(GIT_STR).setDirectory(new File(repoName)).call();
ObjectId currentObjid =localRepo.resolve(Constants.HEAD);
if(!localRepo.getBranch().equalsIgnoreCase("staging")){
git.branchCreate().setForce(true).setName("staging").setStartPoint("refs/remotes/origin/staging").call();
}
git.checkout().setName("staging").call();
git.getRepository().close();
}
} catch (InvalidRemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GitAPIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RevisionSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AmbiguousObjectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IncorrectObjectTypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

Calling git.init() when repository already exists

I am using the following snippet of code to initialize the git repository:
try (Git git = Git.init().setDirectory(gitFilename).call()) {
log.info("Created repository: " + git.getRepository().getDirectory());
} catch (GitAPIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What happens when the repository is already created and I call git.init() on it?
Thanks! Ana
This appeared to work for me:
//initialize git repository
String gitDirectory = getGitRepoDirectory();
File gitFilename = new File(gitDirectory);
try (Git git = Git.open(gitFilename)){
log.info("Git repo " + gitDirectory + " exists!");;
} catch (RepositoryNotFoundException e) {
log.info("Initialising " + gitDirectory + " as a git repo for backup purposes");
try {
Git git = Git.init().setDirectory(gitFilename).call();
} catch (GitAPIException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to Write/Read in JavaFX with Gluon Plugin

I am trying to write/read files in JavaFX while using the Gluon plugin, and I am not having any luck. If i run the program as a Desktop App, it works fine, I've even used the same functions in Android IDE and it works fine, however if I send the program to my phone with Gluon, it does not work. I wanting to know how to save/read to files in Gluon, and what have I done wrong, and why does it work as Desktop and on Android but not Gluon. The two fcns I used are:
public void writeToFile() {
try {
FileOutputStream f = new FileOutputStream("Meal1_Protein.txt");
f.write(choice.getBytes()); //Choice is input from a dropdown
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast toast = new Toast(choice);
toast.show();
}
public void readFromFile(){
try {
FileInputStream f = new FileInputStream("Meal1_Protein.txt");
InputStreamReader is = new InputStreamReader(f);
BufferedReader br = new BufferedReader(is);
StringBuffer buff = new StringBuffer();
String lines;
while((lines = br.readLine())!=null){
buff.append(lines);
buff.append("\n");
}
carbInput.setText(buff.toString()); // inserting into a txtfield
//to see if it I can read strings back in.
Toast toast = new Toast(buff.toString());
toast.show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

getServletContext().getResource(file3) returns null url resource

Here is my code which reads excelsheet files.but i can see my other functions are working fine but when try to get resource as url it return null.
URL resource = null;
try {
System.out.println(file3);
resource = getServletContext().getResource(file3);
System.out.println("Problem with getting resource"+resource);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = null;
try {
System.out.println(resource.toURI());
file = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileInputStream input = null;
try {
input = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Workbook w;
w = Workbook.getWorkbook(input);
// Get the first sheet
Sheet sheet = w.getSheet(0);
return sheet;

Get Action Name from Servlet Request

I have ABC.action which invokes the doFilter method of Filter Class which is configured properly in web.xml
I need to find action name from request object. How can i achieve this?
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
long t1 = System.nanoTime();
filterChain.doFilter(request, response);
long t2 = System.nanoTime();
long time = t2 - t1;
// Just writing statistics to servlet's log
System.out.println("## " +
"ArriveTime ns " + t1 + " Departtime ns " + t2 + " ServiceTime : " + time);
// System.out.println("Time taken to process request to "
// + ((HttpServletRequest) request).getRequestURI()
// + ": " + totalTime + " ms.");
}
Try below code(working in JBOSS).
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain fc) throws IOException, ServletException {
System.out.println("Request");
System.out.println(req);
// req instance of HttpServletRequest
if (req instanceof HttpServletRequest) {
HttpServletRequest httpReq = (HttpServletRequest) req;
System.out.println(httpReq.getRequestURI());
} else {
// req is not instance of HTTPServletRequest then try reflection
try {
Class clazz = Class
.forName("org.apache.catalina.connector.RequestFacade");
Method method = clazz.getMethod("getContextPath", new Class[0]);
String actionName = (String) method.invoke(req, new Object[0]);
System.out.println(actionName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

SAML2 assertion encryption using public key (opensaml)

I've recently tried to encrypt Saml2 assertion using relaying-party service public key. Unfortunately I can't finalise even the test phase
here is my code
public class EncryptionTest {
public static void main(String args[]){
try {
// The Assertion to be encrypted
FileInputStream fis;
DataInputStream in, in2;
File f = new File("src/main/resources/AssertionTest");
byte[] buffer = new byte[(int) f.length()];
in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
//Assertion = DataInputStream.readUTF(in);
String in_assert = new String(buffer);
System.out.println(in_assert);
org.apache.axiom.om.OMElement OMElementAssertion = org.apache.axiom.om.util.AXIOMUtil.stringToOM(in_assert);
Assertion assertion = convertOMElementToAssertion2(OMElementAssertion);
// Assume this contains a recipient's RSA public key
Credential keyEncryptionCredential;
keyEncryptionCredential = getCredentialFromFilePath("src/main/resources/cert.pem");
EncryptionParameters encParams = new EncryptionParameters();
encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
kekParams.setEncryptionCredential(keyEncryptionCredential);
kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
Encrypter samlEncrypter = new Encrypter(encParams, kekParams);
samlEncrypter.setKeyPlacement(KeyPlacement.PEER);
EncryptedAssertion encryptedAssertion = samlEncrypter.encrypt(assertion);
System.out.println(encryptedAssertion);
} catch (EncryptionException e) {
e.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (KeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (XMLStreamException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
public static Credential getCredentialFromFilePath(String certPath) throws IOException, CertificateException, KeyException {
InputStream inStream = new FileInputStream(certPath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(inStream);
inStream.close();
//"Show yourself!"
System.out.println(cert.toString());
BasicX509Credential cred = new BasicX509Credential();
cred.setEntityCertificate((java.security.cert.X509Certificate) cert);
cred.setPrivateKey(null);
//System.out.println(cred.toString());
return cred;
//return (Credential) org.opensaml.xml.security.SecurityHelper.getSimpleCredential( (X509Certificate) cert, privatekey);
}
public static Assertion convertOMElementToAssertion2(OMElement element) {
Element assertionSAMLDOOM = (Element) new StAXOMBuilder(DOOMAbstractFactory.getOMFactory(), element.getXMLStreamReader()).getDocumentElement();
try {
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(Assertion.DEFAULT_ELEMENT_NAME);
return (Assertion) unmarshaller.unmarshall(assertionSAMLDOOM);
} catch (Exception e1) {
System.out.println("error: " + e1.toString());
}
return null;
}
}
I constantly recive Null pointer exception in
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
How can I set GlobalSecurityConfiguration or is there different approach of encrypting Assertion which will work?
This question was laying open for too long. The problem was initialization of OpenSaml.
Simple
DefaultBootstrap.bootstrap();
helped and solved problem.

Resources