I am trying to do a git pull using JGit's API with the following code
public class gitHubTest {
JSch jsch = new JSch();
// Defining the private key file location explicitly
String userHome = System.getProperty("user.home");
String privateKey = userHome + "/.ssh/id_rsa";
String knownHostsFile = userHome + "/.ssh/known_hosts";
Repository localRepo = new FileRepository("/LocalPath/.git");
public gitHubTest() throws Exception {
jsch.setConfig("StrictHostKeyChecking", "no");
jsch.setKnownHosts(knownHostsFile);
jsch.addIdentity(privateKey);
System.out.println("privateKey :" + privateKey);
Git git = new Git(localRepo);
PullCommand pullcmd = git.pull();
pullcmd.call();
}
}
Error Stack Trace :
org.eclipse.jgit.api.errors.TransportException: git#github.example.com:remote.git: USERAUTH fail
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:245)
at org.eclipse.jgit.api.PullCommand.call(PullCommand.java:288)
at gitHubTest.<init>(gitHubTest.java:47)
at WebhooksServer.main(WebhooksServer.java:13)
Caused by: org.eclipse.jgit.errors.TransportException: git#github.example.com:remote.git: USERAUTH fail
at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:160)
at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:137)
at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:274)
at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:169)
at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:136)
at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:122)
at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1236)
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:234)
... 3 more
Caused by: com.jcraft.jsch.JSchException: USERAUTH fail
at com.jcraft.jsch.UserAuthPublicKey.start(UserAuthPublicKey.java:119)
at com.jcraft.jsch.Session.connect(Session.java:470)
at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:117)
... 10 more
Some suggestions I have checked show, we need to instantiate JschConfigSessionFactory and then overrride configure() method to pass passphrase . I have tried doing it already. Then it shows an error. I have referred to http://www.codeaffine.com/2014/12/09/jgit-authentication/ which reads just right but not for my PullCommand.
Can anyone please help? I have already read and tried a lot of posts here but nothing addresses my problem accurately.
Code implemenatation with configure() method :
public class gitHubTest {
JSch jsch = new JSch();
String userHome = System.getProperty("user.home");
String privateKey = userHome + "/.ssh/id_rsa";
String knownHostsFile = userHome + "/.ssh/known_hosts";
public gitHubTest() throws IOException, JSchException, GitAPIException {
Repository localRepo = new FileRepository("/LocalPath/branch.git");
final String remoteURL = "git#github.example.com:remote.git";
JSch.setConfig("StrictHostKeyChecking", "no");
jsch.setKnownHosts(knownHostsFile);
jsch.addIdentity(privateKey);
JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
#Override
protected void configure(OpenSshConfig.Host host, Session session) {
CredentialsProvider cp = new CredentialsProvider() {
#Override
public boolean isInteractive() {
return false;
}
#Override
public boolean supports(CredentialItem... credentialItems) {
return false;
}
#Override
public boolean get(URIish urIish, CredentialItem... credentialItems) throws UnsupportedCredentialItem {
return false;
}
};
UserInfo userInfo = new CredentialsProviderUserInfo(session,cp);
session.setUserInfo(userInfo);
}
};
SshSessionFactory.setInstance(sessionFactory);
Git git = new Git(localRepo);
PullCommand pullcmd = git.pull();
pullcmd.call();
}}
this gives the same error.
I could figure out some of the issues I was facing. Here's solution to it:
if auth has to be done without the passphrase, generate the id_rsa without passphrase
We needed to override getJSch(final OpenSshConfig.Host hc, FS fs) making use of addIdentity in the configure of SshSessionfactory:
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
#Override
protected void configure(OpenSshConfig.Host host, Session sess ion) {
session.setConfig("StrictHostKeyChecking", "no");
}
#Override
protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
JSch jsch = super.getJSch(hc, fs);
jsch.removeAllIdentity();
jsch.addIdentity("/path/to/private/key");
return jsch;
}
};
We need to call needs to be instantiated differently:
PullCommand pull = git.pull().setTransportConfigCallback(new TransportConfigCallback() {
#Override
public void configure(Transport transport) {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
}
});
And then call pull instance:
PullResult pullResult = pull.call();
I hope this helps.
Related
so i got a very strange error message. Im currently working on a java web project with maven and testing the project with Eclipse and Tomcat. So I imported all the neccessary dependencys (mongo java driver, mongodb driver, mongodb driver core, bson and javax.servlet api), or so i thought. But still i'm getting this error over and over again.
If I run the code as part of a main method it works just fine...so im in the dark what could have caused this problem.
this is my MongoDB connector,
public class Connector {
final String HOST = "localhost";
final int PORT = 27017;
final String DBNAME = "mitfahrapp";
public static Connector instance;
public MongoClient connection;
public MongoDatabase database;
public Connector(){
this.connection = new MongoClient(this.HOST, this.PORT);
this.database = connection.getDatabase(DBNAME);
}
public MongoClient getClient() {
return connection;
}
public static Connector createInstance() throws UnknownHostException {
if (Connector.instance == null) {
Connector.instance = new Connector();
}
return Connector.instance;
}
public MongoCollection<Document> getCollection(String name) {
return this.database.getCollection(name);
}
public void CloseMongo() {
connection.close();
}
}
and this is part of my LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connector c = Connector.createInstance();
MongoCollection<Document> collection = c.getCollection("users");
String username = request.getParameter("username");
String password = request.getParameter("password");
Bson filterUsername = Filters.eq("username", username);
Bson filterPwd = Filters.eq("password", password);
Bson bsonFilter = Filters.and(filterUsername, filterPwd);
FindIterable<Document> doc = collection.find(bsonFilter);
if (doc != null) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
Thanks for any answers in advance!
This means that the classes are not included in the jar, if you are using maven you should use the maven shade plugin to include those.
I am working on a web_application sing Java,servlets,JSP and using apache Tomcat as application server
What I have done
i have created a UI where user is selecting mail Ids (they can select more than one)
And when user is clicking on send button i am triggering my java class and sending the mail
Now What i have to do
Now i have to do this dynamically,every night at 12:00 O'clock i have to send mail to some particular users
User to whom i have to send mail i am getting that mail id from login query so that is not an issue
I just want to know how can I send mail when it is midnight 12:00 O'clock
Codding I have done till now
servlet class
public class EmailSendingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String host;
private String port;
private String user;
private String pass;
public void init() {
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String recipient = request.getParameter("To"); // this i will get from login query
String subject = request.getParameter("subject");//this i can define manually
String content = request.getParameter("content");//same for this also
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
}
}
}
Java Utility classs
public class EmailUtility {
public static void sendEmail(String host, String port, final String userName, final String password,
String toAddress, String subject, String message) throws AddressException, MessagingException {
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
session.setDebug(false);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
if (toAddress!= null) {
List<String> emails = new ArrayList<>();
if (toAddress.contains(",")) {
emails.addAll(Arrays.asList(toAddress.split(",")));
} else {
emails.add(toAddress);
}
Address[] to = new Address[emails.size()];
int counter = 0;
for(String email : emails) {
to[counter] = new InternetAddress(email.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, to);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
Transport.send(msg);
}
}
You can use a ScheduledExecutorService for handling this in "plain" Java:
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
int count = 0;
Runnable task = () -> {
count++;
System.out.println(count);
};
ScheduledFuture<?> scheduledFuture = ses.scheduleAtFixedRate(task, 12, TimeUnit.HOURS);
There is also a method for using an initial delay, but you can read more here:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html
For your use case:
Introduce a new class EmailSendJobUtil:
public class EmailSendUtil {
public void createAndSubmitSheduledJob() {
ScheduledExecutorService ses = Executors.sheduledThreadPool(1);
ScheduledFuture<> sheduledFuture = ses.sheduleAtFixedRate(EmailUtility.sendMail(), 12, TimeUnit.HOURS);
}
}
However, you will get troubles with your code structure. Try to introduce a method in your EmailUtility that encapsulates the automatated sending of mails.
Introduce a repository for saving to which users you have to send mails automatically and read this data in the new method that only handles the automatic sending. You could do something like this:
public class MailJobRepository {
private List<MailJob> jobs;
void add();
void remove();
List<> getJobs();
}
And in your EmailUtility introduce a new method:
public void sendAutomatedEmails() {
jobRepository.getJobs().foreach(job -> {
sendMail(job.getToAddress(), job.getSubject(), job.getMessage());
});
}
Then you can shedule this new method and you have splitted your code into logical seperate parts.
Just a little hint:
String host, String port, final String userName, final String password
This is data for your "side" of the email sending and should not be passed as a method parameter. You can save this data into your EmailUtility class.
In java the scheduler is used to schedule a thread or task that executes at a certain period of time or periodically at a fixed interval. There are multiple ways to schedule a task in Java :
java.util.TimerTask
java.util.concurrent.ScheduledExecutorService
Quartz Scheduler
org.springframework.scheduling.TaskScheduler
For pure java implementation without any framework usage, using ScheduledExecutorService running a task at certain periods:
public void givenUsingExecutorService_whenSchedulingRepeatedTask_thenCorrect()
throws InterruptedException {
TimerTask repeatedTask = new TimerTask() {
public void run() {
EmailUtility.sendEmail(host, port, user, pass, recipient,object,content);
System.out.println("The e-mail was sent successfully");
}
};
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime nextRun = now.withHour(5).withMinute(0).withSecond(0);
if(now.compareTo(nextRun) > 0)
nextRun = nextRun.plusDays(1);
Duration duration = Duration.between(now, nextRun);
long initalDelay = duration.getSeconds();
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(repeatedTask,
initalDelay,
TimeUnit.DAYS.toSeconds(1),
TimeUnit.SECONDS);
executor.shutdown();
}
You should take a look to isocline's Clockwork it's a java process engine. It is capable of coding various functions more efficiently than Quartz, and has specific execution function.
I created app for getting info from upwork.com. I use java lib and Upwork OAuth 1.0. The problem is local request to API works fine, but when I do deploy to Google Cloud, my code does not work. I get ({"error":{"code":"503","message":"Exception: IOException"}}).
I create UpworkAuthClient for return OAuthClient and next it is used for requests in JobClient.
run() {
UpworkAuthClient upworkClient = new UpworkAuthClient();
upworkClient.setTokenWithSecret("USER TOKEN", "USER SECRET");
OAuthClient client = upworkClient.getOAuthClient();
//set query
JobQuery jobQuery = new JobQuery();
jobQuery.setQuery("query");
List<JobQuery> jobQueries = new ArrayList<>();
jobQueries.add(jobQuery);
// Get request of job
JobClient jobClient = new JobClient(client, jobQuery);
List<Job> result = jobClient.getJob();
}
public class UpworkAuthClient {
public static final String CONSUMERKEY = "UPWORK KEY";
public static final String CONSUMERSECRET = "UPWORK SECRET";
public static final String OAYTРCALLBACK = "https://my-app.com/main";
OAuthClient client ;
public UpworkAuthClient() {
Properties keys = new Properties();
keys.setProperty("consumerKey", CONSUMERKEY);
keys.setProperty("consumerSecret", CONSUMERSECRET);
Config config = new Config(keys);
client = new OAuthClient(config);
}
public void setTokenWithSecret (String token, String secret){
client.setTokenWithSecret(token, secret);
}
public OAuthClient getOAuthClient() {
return client;
}
public String getAuthorizationUrl() {
return this.client.getAuthorizationUrl(OAYTРCALLBACK);
}
}
public class JobClient {
private JobQuery jobQuery;
private Search jobs;
public JobClient(OAuthClient oAuthClient, JobQuery jobQuery) {
jobs = new Search(oAuthClient);
this.jobQuery = jobQuery;
}
public List<Job> getJob() throws JSONException {
JSONObject job = jobs.find(jobQuery.getQueryParam());
jobList = parseResponse(job);
return jobList;
}
}
Local dev server works fine, I get resilts on local machine, but in Cloud not.
I will be glad to any ideas, thanks!
{"error":{"code":"503","message":"Exception: IOException"}}
doesn't seem like a response return by Upwork API. Could you please provide the full response including the returned headers? So, we will take a more precise look into it.
Hello i´m having problems in Java Null Pointer Exception in Session
This is my code:
public Configs(String uri, String username, String password)
{
Driver driver = GraphDatabase.driver(uri, AuthTokens.basic(username, password) );
}
.....
public Boolean existMachine(){
machine mach = new machine();
try (Session session = driver.session())
{
}
}
And i call the Function in main(String[] args):
Configs connections = new Configs("bolt://localhost:7474", "neo4j", "");
if(connections.existMachine().booleanValue() == false)
{
...
}
else{
..
}
I´m getting error in:
try (Session session = driver.session())
You don't set drivers as an instance field of your class.
You have to make it available in existMachine
i am developing the java application in JDeveloper.which is use to connect with oracle sales cloud web services so for this i have did the following steps.
step 1: created the custom Application
step 2: Then i have generated the client from wsdl using web service client and proxy.
its generated the successfully and i have added the credential to main class . this is my main class.
public class PersonServiceSoapHttpPortClient {
private static final AddressingVersion WS_ADDR_VER = AddressingVersion.W3C;
public static void main(String[] args) throws Exception{
PersonService_Service personService_Service = new PersonService_Service();
PersonService personService = personService_Service.getPersonServiceSoapHttpPort();
// Configure credential providers
Map<String, Object> requestContext = ((BindingProvider) personService).getRequestContext();
try {
setPortCredentialProviderList(requestContext);
} catch (Exception ex) {
ex.printStackTrace();
}
// Add your code to call the desired methods.
FindCriteria findCriteria=new FindCriteria();
findCriteria.setFetchSize(1);
findCriteria.setFetchSize(10);
FindControl findControl=new FindControl();
findControl.setRetrieveAllTranslations(true);
System.out.println("before invoking method");
PersonResult personResult=personService.findPerson(findCriteria, findControl);
List<Person> persons=personResult.getValue();
System.out.println("The Response size is ::"+persons.size());
}
#Generated("Oracle JDeveloper")
public static void setPortCredentialProviderList(Map<String, Object> requestContext) throws Exception {
// TODO - Provide the required credential values
String username = "abc";
String password = "acdd";
String clientKeyStore = "";
String clientKeyStorePassword = "";
String clientKeyAlias = "";
String clientKeyPassword = "";
String serverKeyStore = "";
String serverKeyStorePassword = "";
String serverKeyAlias = "";
List<CredentialProvider> credList = new ArrayList<CredentialProvider>();
credList.add(getUNTCredentialProvider(username, password));
credList.add(getBSTCredentialProvider(clientKeyStore, clientKeyStorePassword, clientKeyAlias, clientKeyPassword, serverKeyStore, serverKeyStorePassword, serverKeyAlias, requestContext));
credList.add(getSAMLTrustCredentialProvider());
requestContext.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credList);
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getSAMLTrustCredentialProvider() {
return new SAMLTrustCredentialProvider();
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getUNTCredentialProvider(String username, String password) {
return new ClientUNTCredentialProvider(username.getBytes(), password.getBytes());
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getBSTCredentialProvider(String clientKeyStore, String clientKeyStorePwd,
String clientKeyAlias, String clientKeyPwd,
String serverKeyStore, String serverKeyStorePwd,
String serverKeyAlias,
Map<String, Object> requestContext) throws Exception {
List serverCertList = CertUtils.getCertificate(serverKeyStore, serverKeyStorePwd, serverKeyAlias, "JKS");
List clientCertList = CertUtils.getCertificate(clientKeyStore, clientKeyStorePwd, clientKeyAlias, "JKS");
final X509Certificate serverCert =
(serverCertList != null && serverCertList.size() > 0) ? (X509Certificate) serverCertList.get(0) : null;
final X509Certificate clientCert =
(clientCertList != null && clientCertList.size() > 0) ? (X509Certificate) clientCertList.get(0) : null;
requestContext.put(WSSecurityContext.TRUST_MANAGER, new TrustManager() {
public boolean certificateCallback(X509Certificate[] chain, int validateErr) {
boolean result =
(chain != null && chain.length > 0) && (chain[0].equals(serverCert) || chain[0].equals(clientCert));
return result;
}
});
return new ClientBSTCredentialProvider(clientKeyStore, clientKeyStorePwd, clientKeyAlias, clientKeyPwd, "JKS",
serverCert);
}
}
while running this client stub i am getting following exception.
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory) INFO: Policy subject is not registered.
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
INFO: EffectivePolicySetFeature not on the binding,
will look up policy set for; ResourcePattern
[absolutePortableExpression=///UNKNOWN|#MODULE|
WS-Client({http://xmlns.oracle.com/apps/cdm/foundation
/parties/personService/applicationModule/}
PersonService#PersonServiceSoapHttpPort,wls)]
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
INFO: EffectivePolicySetFeature=oracle.j2ee.ws.common.wsm
.EffectivePolicySetFeature#76f6c7e1
INFO: WSM Security is not enabled for Policy Subject:
ResourcePattern [absolutePortableExpression=
///UNKNOWN|#MODULE|WS-
Client({http://xmlns.oracle.com/apps/cdm/foundation
/parties/personService/applicationModule/}PersonService
#PersonServiceSoapHttpPort,wls)]
java.lang.SecurityException: keyStoreFilename is either null
or empty string
at weblogic.wsee.security.util.CertUtils.getCertificate
(CertUtils.java:89)
at com.oracle.xmlns.apps.cdm.foundation.parties.personservice
.applicationmodule.PersonServiceSoapHttpPortClient
.getBSTCredentialProvider(PersonServiceSoapHttpPortClient.java:129)
at com.oracle.xmlns.apps.cdm.foundation.parties.personservice
.applicationmodule.PersonServiceSoapHttpPortClient
.setPortCredentialProviderList
(PersonServiceSoapHttpPortClient.java:106)
at com.oracle.xmlns.apps.cdm.foundation.parties.personservice
.applicationmodule.PersonServiceSoapHttpPortClient.main
(PersonServiceSoapHttpPortClient.java:52)
Which version are you runnning? I had the same problem with version 12.1.3 of JDeveloper. Try downloading 12.1.2 from the Oracle website. This did it for me.
Apparently your app requires the JPS library and system picked up the default JPS configuration file, given that the -Doracle.security.jps.config option was not specified. As a result, system is searching ./config/jps-config.xml, which does not exist, at least in that location. Typically, that file should be located at $DOMAIN_HOME/config/fmwconfig.
Ensure your JVM options includes the right JPS config file. This should help at least with this type of error:
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml (No such file or directory)
Example:
-Doracle.security.jps.config=/dfaut6/otm/product/BIP1117/user_projects/domains/bifoundation_domain/config/fmwconfig/jps-config.xml
Some useful references: http://docs.oracle.com/cd/E25178_01/core.1111/e10043/apjpscfg.htm