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
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'm trying to access the details of the Facebook pages I'm an admin on through restfb. I can get my user details but when I try to get the details from 'me/accounts' it just returns null.
I've tried using different types and classes but still won't show what I need. However it works fine using the Facebook Graph API tool
private void authUser(ActionEvent event) {
String appId = "(My App ID)";
String domain = "https://www.google.com";
String authUrl = "https://graph.facebook.com/oauth/authorize?type=user_agent&client_id="+appId+"&redirect_uri="+domain+"&scope=ads_management, ads_read, business_management, email, groups_access_member_info, leads_retrieval, manage_pages, pages_manage_cta, pages_manage_instant_articles, pages_messaging, pages_messaging_phone_number, pages_messaging_subscriptions, pages_show_list, publish_pages, publish_to_groups, publish_video, read_audience_network_insights, read_insights, read_page_mailboxes, user_age_range, user_birthday, user_events, user_friends, user_gender, user_hometown, user_likes, user_link, user_location, user_photos, user_posts, user_status, user_tagged_places, user_videos";
System.setProperty("webdriver.chrome.driver", "chromedriver");
WebDriver driver = new ChromeDriver();
driver.get(authUrl);
String accessToken;
String accessToken2 = null;
while(true){
if(!driver.getCurrentUrl().contains("facebook")){
String url = driver.getCurrentUrl();
accessToken = url.replaceAll(".*#access_token=(.+)&.*","$1");
int indexOfLast = accessToken.lastIndexOf("&");
if(indexOfLast >=0) accessToken2 = accessToken.substring(0, indexOfLast);
System.out.println(accessToken);
System.out.println(accessToken2);
driver.quit();
driver = null;
FacebookClient fbClient = new DefaultFacebookClient(accessToken2, com.restfb.Version.VERSION_3_2);
User user = fbClient.fetchObject("me", User.class, Parameter.with("fields", "name, email"));
User account = fbClient.fetchObject("me/accounts", User.class, Parameter.with("fields", "name"));
name.setText(user.getName());
id.setText(user.getId());
if (user.getEmail() == null) {
email.setText("Unable to show email");
} else {
email.setText(user.getEmail());
}
if (account.getName()== null) {
System.out.println("Null");
} else {
System.out.println(account.getName());
}
}
}
}
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.
I am trying to display all users usernames from a Cassandra database using an AJAX script in the jsp page.This would display a list of the users usernames when a view all button is clicked. However the Server throws a Null pointer exception on Session session = cluster.connect("");
java.lang.NullPointerException
User.searchAll(User.java:87)
Search.doGet(Search.java:82)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
Model
public class User {
Cluster cluster;
public User() {
}
public java.util.LinkedList<ProfileBean> searchAll(){
Session session = cluster.connect("instagrim");
LinkedList<ProfileBean> profileBeanList = new LinkedList();
String cqlQuery = "select * from userprofiles";
PreparedStatement ps = session.prepare(cqlQuery);
ResultSet rs;
BoundStatement bs = new BoundStatement(ps);
rs = session.execute(bs.bind());
if(rs.isExhausted()){
System.out.println("Profile not found");
}
else
{
for (Row row : rs){
ProfileBean profile = new ProfileBean();
profile.setLogin(row.getString("login"));
profileBeanList.add(profile);
}
}
session.close();
return profileBeanList;
}
Servlet
public class Search extends HttpServlet {
Cluster cluster = null;
public void init(ServletConfig config)
{
cluster = CassandraHosts.getCluster();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User us = new User();
String output ="";
LinkedList<ProfileBean> profileBeanList = new LinkedList();
profileBeanList = us.searchAll();
for (int i=0;i<profileBeanList.size();i++)
{
output="<p>"+profileBeanList.get(i).getLogin() +"</p>";
}
response.getWriter().write(output);
RequestDispatcher rd = request.getRequestDispatcher("search.jsp");
rd.forward(request,response);
}
cluster is null, therefore it does not have a connect method. The system lets you know about the situation with the error message.
The solution is to make sure that cluster is properly initialized before you try to connect.
Is it possible to create Group and User in AEM6.2 by using Jackrabbit User Manager API with permissions.
I have just followed below URL's but the code is throwing some exception :
https://helpx.adobe.com/experience-manager/using/jackrabbit-users.html
https://stackoverflow.com/questions/38259047/how-to-give-permission-all-in-aem-through-programatically
ResourceResolverFactory getServiceResourceResolver throws Exception in AEM 6.1
As getAdministrativeResourceResolver(Map) method is deprecated then how can we use getServiceResourceResolver(Map) method instead.
Sharing my solution which will be helpful for others.
Following is the code using getServiceResourceResolver(Map) method for creating Group first and then User and then add user into group with ACL privileges and permission:
public void createGroupUser(SlingHttpServletRequest request) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String groupName = request.getParameter("groupName");
Session session = null;
ResourceResolver resourceResolver = null;
try {
Map<String, Object> param = new HashMap<String, Object>();
param.put(ResourceResolverFactory.SUBSERVICE, "datawrite");
resourceResolver = resourceResolverFactory.getServiceResourceResolver(param);
session = resourceResolver.adaptTo(Session.class);
// Create UserManager Object
final UserManager userManager = AccessControlUtil.getUserManager(session);
// Create a Group
Group group = null;
if (userManager.getAuthorizable(groupName) == null) {
group = userManager.createGroup(groupName);
ValueFactory valueFactory = session.getValueFactory();
Value groupNameValue = valueFactory.createValue(groupName, PropertyType.STRING);
group.setProperty("./profile/givenName", groupNameValue);
session.save();
log.info("---> {} Group successfully created.", group.getID());
} else {
log.info("---> Group already exist..");
}
// Create a User
User user = null;
if (userManager.getAuthorizable(userName) == null) {
user = userManager.createUser(userName, password);
ValueFactory valueFactory = session.getValueFactory();
Value firstNameValue = valueFactory.createValue("Arpit", PropertyType.STRING);
user.setProperty("./profile/givenName", firstNameValue);
Value lastNameValue = valueFactory.createValue("Bora", PropertyType.STRING);
user.setProperty("./profile/familyName", lastNameValue);
Value emailValue = valueFactory.createValue("arpit.p.bora#gmail.com", PropertyType.STRING);
user.setProperty("./profile/email", emailValue);
session.save();
// Add User to Group
Group addUserToGroup = (Group) (userManager.getAuthorizable(groupName));
addUserToGroup.addMember(userManager.getAuthorizable(userName));
session.save();
// set Resource-based ACLs
String nodePath = user.getPath();
setAclPrivileges(nodePath, session);
log.info("---> {} User successfully created and added into group.", user.getID());
} else {
log.info("---> User already exist..");
}
} catch (Exception e) {
log.info("---> Not able to perform User Management..");
log.info("---> Exception.." + e.getMessage());
} finally {
if (session != null && session.isLive()) {
session.logout();
}
if (resourceResolver != null)
resourceResolver.close();
}
}
public static void setAclPrivileges(String path, Session session) {
try {
AccessControlManager aMgr = session.getAccessControlManager();
// create a privilege set
Privilege[] privileges = new Privilege[] {
aMgr.privilegeFromName(Privilege.JCR_VERSION_MANAGEMENT),
aMgr.privilegeFromName(Privilege.JCR_MODIFY_PROPERTIES),
aMgr.privilegeFromName(Privilege.JCR_ADD_CHILD_NODES),
aMgr.privilegeFromName(Privilege.JCR_LOCK_MANAGEMENT),
aMgr.privilegeFromName(Privilege.JCR_NODE_TYPE_MANAGEMENT),
aMgr.privilegeFromName(Replicator.REPLICATE_PRIVILEGE) };
AccessControlList acl;
try {
// get first applicable policy (for nodes w/o a policy)
acl = (AccessControlList) aMgr.getApplicablePolicies(path).nextAccessControlPolicy();
} catch (NoSuchElementException e) {
// else node already has a policy, get that one
acl = (AccessControlList) aMgr.getPolicies(path)[0];
}
// remove all existing entries
for (AccessControlEntry e : acl.getAccessControlEntries()) {
acl.removeAccessControlEntry(e);
}
// add a new one for the special "everyone" principal
acl.addAccessControlEntry(EveryonePrincipal.getInstance(), privileges);
// the policy must be re-set
aMgr.setPolicy(path, acl);
// and the session must be saved for the changes to be applied
session.save();
} catch (Exception e) {
log.info("---> Not able to perform ACL Privileges..");
log.info("---> Exception.." + e.getMessage());
}
}
In code "datawrite" is a service mapping which is mapped with system user in "Apache Sling Service User Mapper Service" which is configurable in the OSGI configuration admin interface.
For more detail about system user check link - How to Create System User in AEM?
I am providing this code direcly from a training of an official Adobe channel, and it is based on AEM 6.1. So I assume this might be the best practice.
private void modifyPermissions() {
Session adminSession = null;
try{
adminSession = repository.loginService(null, repository.getDefaultWorkspace());
UserManager userMgr= ((org.apache.jackrabbit.api.JackrabbitSession)adminSession).getUserManager();
AccessControlManager accessControlManager = adminSession.getAccessControlManager();
Authorizable denyAccess = userMgr.getAuthorizable("deny-access");
AccessControlPolicyIterator policyIterator =
accessControlManager.getApplicablePolicies(CONTENT_GEOMETRIXX_FR);
AccessControlList acl;
try{
acl=(JackrabbitAccessControlList) policyIterator.nextAccessControlPolicy();
}catch(NoSuchElementException nse){
acl=(JackrabbitAccessControlList) accessControlManager.getPolicies(CONTENT_GEOMETRIXX_FR)[0];
}
Privilege[] privileges = {accessControlManager.privilegeFromName(Privilege.JCR_READ)};
acl.addAccessControlEntry(denyAccess.getPrincipal(), privileges);
accessControlManager.setPolicy(CONTENT_GEOMETRIXX_FR, acl);
adminSession.save();
}catch (RepositoryException e){
LOGGER.error("**************************Repo Exception", e);
}finally{
if (adminSession != null)
adminSession.logout();
}