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());
}
}
}
}
Related
I created Jira issue by using jira liberary
<dependency>
<groupId>com.atlassian.jira</groupId>
<artifactId>jira-rest-java-client-app</artifactId>
<version>5.2.1</version>
</dependency>
but while creating I am not able to set Assignee or AssigneeName for created JiraIssue
below is my code
BasicUser user = projectType.get().getLead();
System.out.println(user.getDisplayName());
builder = new IssueInputBuilder(project, issueType, issueDTO.getIssueSummery());
builder.setProject(project);
builder.setDescription(issueDTO.getIssueDescription());
IssueInput input = builder.build();
IssueRestClient client = restClient.getIssueClient();
BasicIssue issue = client.createIssue(input).claim();
//input = IssueInput.createWithFields(new FieldInput(IssueFieldId.ASSIGNEE_FIELD, ComplexIssueInputFieldValue.with("name", "Wraplive User")));
builder.setPriorityId(1L);
builder.setAssigneeName("Wraplive User");
IssueInput issueInput = builder.build();
client.updateIssue(issue.getKey(), issueInput);
I tried builder.setAssignee(user); // here it sets AssigneeName as Project lead which I don't require, I want to set another user or logged in username.
Can anyone help me where I am going wrong.
I tried with FieldInput which is commented in above code.
public JiraRestClient getJiraRestClient()
{
return new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(getJiraUri(), JIRA_USERNAME, JIRA_PASSWORD);
}
public URI getJiraUri()
{
return URI.create(JIRA_URL);
}
//loadConnectionProperties();
restClient = getJiraRestClient();
BasicProject project = null;
IssueType issueType = null;
IssueInputBuilder builder = null;
try
{
final Iterable<BasicProject> projects = restClient.getProjectClient().getAllProjects().claim();
for(BasicProject projectStr : projects)
{
if(projectStr.getKey().equalsIgnoreCase(PROJECT_KEY))
{
project = projectStr;
}
}
Promise<Project> projectType = restClient.getProjectClient().getProject(PROJECT_KEY);
for(IssueType type : (projectType.get()).getIssueTypes())
{
if(type.getName().equalsIgnoreCase(Issue_Type))
{
issueType = type;
}
}
builder = new IssueInputBuilder(project, issueType, issueDTO.getIssueSummery());
builder.setProject(project);
builder.setDescription(issueDTO.getIssueDescription());
builder.setPriorityId(1L);
***builder.setFieldInput(new FieldInput("assignee", ComplexIssueInputFieldValue.with("accountId", "557058:0fa57746-30a2-498c-9e34-9306679d0be7")));***
IssueInput input = builder.build();
IssueRestClient client = restClient.getIssueClient();
BasicIssue issue = client.createIssue(input).claim();
System.out.println(issue.getKey());
LOG.error("Jira Created for " + issueDTO.getIssueSummery() + " ID is :: " + issue.getKey());
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
return true;
I am testing android managment API using localhost as call back url. I followed each and every step following this url Android Management API Sample.
Now i m stuck on place.. according to this guide, i download the json file from service account. Now i copy that json file and save in app folder of my project.
This is my enterprise.json file
Screenshot of json file in android studio
and i just give folder location as enterprise.json in location string
This is my code
private static final String PROJECT_ID = "enterprise-271814";
private static final String SERVICE_ACCOUNT_CREDENTIAL_FILE =
"enterprise.json";
private static final String POLICY_ID = "samplePolicy";
/** The package name of the COSU app. */
private static final String COSU_APP_PACKAGE_NAME =
"com.ariaware.devicepoliceycontroller";
/** The OAuth scope for the Android Management API. */
private static final String OAUTH_SCOPE =
"https://www.googleapis.com/auth/androidmanagement";
private static final String APP_NAME = "Device Policey Controller";
private final AndroidManagement androidManagementClient;
public Sample(AndroidManagement androidManagementClient) {
this.androidManagementClient = androidManagementClient;
}
public void run() throws IOException {
// Create an enterprise. If you've already created an enterprise, the
// createEnterprise call can be commented out and replaced with your
// enterprise name.
String enterpriseName = createEnterprise();
System.out.println("Enterprise created with name: " + enterpriseName);
// Set the policy to be used by the device.
setPolicy(enterpriseName, POLICY_ID, getCosuPolicy());
// Create an enrollment token to enroll the device.
String token = createEnrollmentToken(enterpriseName, POLICY_ID);
System.out.println("Enrollment token (to be typed on device): " + token);
// List some of the devices for the enterprise. There will be no devices for
// a newly created enterprise, but you can run the app again with an
// existing enterprise after enrolling a device.
List<Device> devices = listDevices(enterpriseName);
for (Device device : devices) {
System.out.println("Found device with name: " + device.getName());
}
// If there are any devices, reboot one.
if (devices.isEmpty()) {
System.out.println("No devices found.");
} else {
rebootDevice(devices.get(0));
}
}
public static AndroidManagement getAndroidManagementClient()
throws IOException, GeneralSecurityException {
try (FileInputStream input =
new FileInputStream(SERVICE_ACCOUNT_CREDENTIAL_FILE)) {
GoogleCredential credential =
GoogleCredential.fromStream(input)
.createScoped(Collections.singleton(OAUTH_SCOPE));
return new AndroidManagement.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName(APP_NAME)
.build();
}
}
private String createEnterprise() throws IOException {
// Initiate signup process.
System.out.println("Creating signup URL...");
SignupUrl signupUrl =
androidManagementClient
.signupUrls()
.create()
.setProjectId(PROJECT_ID)
.setCallbackUrl("https://localhost:9999")
.execute();
System.out.print(
"To sign up for a new enterprise, open this URL in your browser: ");
System.out.println(signupUrl.getUrl());
System.out.println(
"After signup, you will see an error page in the browser.");
System.out.print(
"Paste the enterpriseToken value from the error page URL here: ");
String enterpriseToken =
new BufferedReader(new InputStreamReader(System.in)).readLine();
// Create the enterprise.
System.out.println("Creating enterprise...");
return androidManagementClient
.enterprises()
.create(new Enterprise())
.setProjectId(PROJECT_ID)
.setSignupUrlName(signupUrl.getName())
.setEnterpriseToken(enterpriseToken)
.execute()
.getName();
}
private Policy getCosuPolicy() {
List<String> categories = new ArrayList<>();
categories.add("android.intent.category.HOME");
categories.add("android.intent.category.DEFAULT");
return new Policy()
.setApplications(
Collections.singletonList(
new ApplicationPolicy()
.setPackageName(COSU_APP_PACKAGE_NAME)
.setInstallType("FORCE_INSTALLED")
.setDefaultPermissionPolicy("GRANT")
.setLockTaskAllowed(true)))
.setPersistentPreferredActivities(
Collections.singletonList(
new PersistentPreferredActivity()
.setReceiverActivity(COSU_APP_PACKAGE_NAME)
.setActions(
Collections.singletonList("android.intent.action.MAIN"))
.setCategories(categories)))
.setKeyguardDisabled(true)
.setStatusBarDisabled(true);
}
private void setPolicy(String enterpriseName, String policyId, Policy policy)
throws IOException {
System.out.println("Setting policy...");
String name = enterpriseName + "/policies/" + policyId;
androidManagementClient
.enterprises()
.policies()
.patch(name, policy)
.execute();
}
private String createEnrollmentToken(String enterpriseName, String policyId)
throws IOException {
System.out.println("Creating enrollment token...");
EnrollmentToken token =
new EnrollmentToken().setPolicyName(policyId).setDuration("86400s");
return androidManagementClient
.enterprises()
.enrollmentTokens()
.create(enterpriseName, token)
.execute()
.getValue();
}
private List<Device> listDevices(String enterpriseName) throws IOException {
System.out.println("Listing devices...");
ListDevicesResponse response =
androidManagementClient
.enterprises()
.devices()
.list(enterpriseName)
.execute();
return response.getDevices() ==null
? new ArrayList<Device>() : response.getDevices();
}
private void rebootDevice(Device device) throws IOException {
System.out.println(
"Sending reboot command to " + device.getName() + "...");
Command command = new Command().setType("REBOOT");
androidManagementClient
.enterprises()
.devices()
.issueCommand(device.getName(), command)
.execute();
}
Moreover i m using android management api for the first time and i dont know its proper implementation. Anyone who has experience on this kinllt guide me a little bit. I found a lot about this but i didn't found any userful tutorial
For Android, you have to store the service account file either in the assets folder or raw folder.
This thread provides code on a number of ways to load the json data into an InputStream depending on the location you selected.
In my current java/spring project, I am using the paypal-java-sdk to try implement a payment system to my application. A long time ago, I managed to make this work with a old project I've lost, with a code similar to what I have now, but now, when I run the application and try make a payment using the paypal sdk, I am redirect to the payment method selection page, and, either if I confirm or cancel the payment, I go to my account page instead of return to the application.
I have this code:
in my controller, this method receives the call from the view:
#RequestMapping(value = "/checkout", method=RequestMethod.GET)
public String checkout(#RequestParam("usuario_id") Integer usuario_id, #RequestParam(value="payerId", required=false) String payerId, #RequestParam(value="guid", required=false) String guid) throws com.paypal.base.rest.PayPalRESTException {
return "redirect:"+this.serv.checkout(usuario_id, payerId, guid);
}
in my service class, this 2 methods handles the payment using paypal:
public String checkout(Integer usuario_id, String payerId, String guid) throws com.paypal.base.rest.PayPalRESTException {
Usuario usuario = this.dao.findBy("id", usuario_id);
String clientId = paypalDao.get().getClientId();
String clientSecret = paypalDao.get().getClientSecret();
APIContext apiContext = new APIContext(clientId, clientSecret, "sandbox");
String redirectURL = "";
if(payerId != null) {
if(guid != null) {
Payment payment = new Payment();
payment.setId(map.get(guid));
PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId(payerId);
payment.execute(apiContext, paymentExecution);
//saves the order data in the database and redirect to the order page
}
} else {
Payment createdPayment = createPayment(usuario, apiContext);
Iterator<Links> links = createdPayment.getLinks().iterator();
while (links.hasNext()) {
Links link = links.next();
if (link.getRel().equalsIgnoreCase("approval_url"))
redirectURL = link.getHref();
}
map.put(guid, createdPayment.getId());
}
return redirectURL;
}
public Payment createPayment(Usuario usuario, APIContext apiContext) throws com.paypal.base.rest.PayPalRESTException {
Amount amount = new Amount();
amount.setCurrency("BRL");
amount.setTotal(this.cart_total(usuario.getId()).toString());
String desc = "Lista de produtos comprados\n";
for(Produto produto : usuario.getCesta().getProdutos())
desc = desc + "* " + produto.getNome() + "\n";
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction.setDescription(desc);
java.util.List<Transaction> transactions = new java.util.ArrayList<Transaction>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(request.getContextPath() + "/cancel");
redirectUrls.setReturnUrl(request.getContextPath() + "/checkout?usuario_id="+usuario.getId()+"?guid="+UUID.randomUUID().toString());
payment.setRedirectUrls(redirectUrls);
return payment.create(apiContext);
}
anyone can give me a hint of what I am missing here?
I am making a login/register android app UI with nodejs as the backend language. Whats happening is that whenever I click the register button, it sends the json response before querying the database (select statement to check if username exists) causing the android app to get the wrong response which causes me to click the button twice to register the correct response. For instance lets say their is a username called test in the database and I try to sign up using the username test, it will tell me that the username is already taken and if erase test and enter lets say 'bob' which does not exist in the database it still says the username is already taken even though it is not but when I click the register button again it will register the user. I am assuming this is happening because it is async(it sends the json response while or before querying the database). How can I make this synchronus or is there another way to fix this?
server file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
//connection
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database : "androidtest"
});
//use json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//declare variables to hold values entered by the user
var name;
var username;
var password;
var age;
//boolean array to let frontend know what is going on
var response;
app.post('/', function(req, res) {
//retrieve variables
username = req.body.username;
name = req.body.name;
age = req.body.age;
password = req.body.password;
//query database
//check if username is taken
var select = "SELECT * FROM users WHERE username = ? LIMIT 1";
con.query(select, [username], function (err, results) {
if (err) throw err;
//if username is taken send json string 'exists' to android app
if(results.length) {
response = {"exists" : "true"};
//if username is available send string 'success' and add the user to the database
} else {
var add = "INSERT INTO users (name, username, age, password) VALUES (?, ?, ?, ?)";
response = {"success" : "true"};
con.query(add, [name, username, age, password]);
if (err) throw err;
console.log('row inserted');
}
});
//send json
res.json(response);
//prevents the functions from being executed more than once
res.end('/');
});
//listen on port 3000
app.listen(3000);
android app java:
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = etName.getText().toString();
final String username = etUserName.getText().toString();
final String password = etPassword.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
//Boolean exists = jsonResponse.getBoolean("exists");
String exists = jsonResponse.getString("exists");
if (exists.matches("true")) {
Toast toast = Toast.makeText(getApplicationContext(), "username already exists", Toast.LENGTH_SHORT);
toast.show();
}
} catch(Exception e) {
e.printStackTrace();
}
try {
JSONObject jsonResponse = new JSONObject(response);
//Boolean success = jsonResponse.getBoolean("success");
String success = jsonResponse.getString("success");
if (success.matches("true")) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
You have to put
res.json(...);
res.end('/');
after the closing bracker of the following line (after & outside the else block):
console.log('row inserted');
then it first gets executed when to query has finished.
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();
}