can not find symbol java / android - java

I want to modify a callerid app so it will open a browser window and call a specific URL.
When the call comes in the code below goes out to a URL and returns the caller information. This works well. The problem I am having is that I also want to open the phones default browser with a preformatted url. something like http://www.myurl.com/index.php?action=getCallerInformation&number=phoneNumber.toString()
The code I have is
package com.integralblue.callerid;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import roboguice.inject.InjectResource;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.google.inject.Inject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
public class HttpCallerIDLookup implements CallerIDLookup {
#Inject SharedPreferences sharedPreferences;
#InjectResource(R.string.default_lookup_url) String defaultLookupUrl;
#Inject RestTemplate restTemplate;
#Inject TelephonyManager telephonyManager;
public CallerIDResult lookup(final CharSequence phoneNumber) throws NoResultException {
//use the network's country if it's available (as I figure that's probably the best? I'm just guessing)
//if the network's country isn't available, using the SIM's
//I have no idea how or if this works on CDMA networks
//(Android documentation warns that these function may not work as expected with CDMA)
final String agentCountry = TextUtils.isEmpty(telephonyManager.getNetworkCountryIso())?telephonyManager.getNetworkCountryIso():telephonyManager.getSimCountryIso();
final String beforeSubstitutionLookupUrl = sharedPreferences.getString("lookup_url", defaultLookupUrl);
final String url;
final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.myurl.com/index.php?action=getCallerInformation&number=phoneNumber.toString()"));
startActivity(intent);
if(beforeSubstitutionLookupUrl.contains("{0}")){
// ensure backwards compatibility. The URL used to use {0} and {1}
url = MessageFormat.format(beforeSubstitutionLookupUrl, "{number}", "{agentCountry}");
}else{
url = beforeSubstitutionLookupUrl;
}
final Map<String, String> urlVariables = new HashMap<String, String>();
urlVariables.put("number", phoneNumber.toString());
urlVariables.put("agentCountry", agentCountry);
try{
return restTemplate.getForObject(url, CallerIDResult.class, urlVariables);
}catch(HttpClientErrorException e){
if(HttpStatus.NOT_FOUND.equals(e.getStatusCode())){
throw new NoResultException();
}else{
throw new RuntimeException(e);
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
When I compile it complains about startActivity(intent);
Can not find symbol

I've now read up about roboguice, so it appears you need:
#Inject Activity thisActivity;
Add the above to your declarations, then call the intent using:
thisActivity.startActivity(intent);

Related

JavaEE and Firebase admin sdk - setValueAsync not pushing data to realtime firebase

Am using firebase admin sdk and JavaEE on intellij built on gradle and glassfish server.
am trying to push a value to realtime database, but sadly am unable to do so. I've been searching online for weeks now and gotten nothing. I also followed some solutions in stackoverflow answers like : Firebase Java Admin SDK don't work but nothing works for me.
I've read a lot of reasons why such a problem would occur with firebase admin sdk but i have no solutions.
here's my code:
package sample;
package sample;
import com.google.api.core.ApiFuture;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.UserRecord;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import sample.model.FireBaseAuth;
import sample.model.FireBaseUtils;
import sample.model.Owner;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
#WebServlet("/success")
public class SuccessServlet extends HttpServlet {
public void init() throws ServletException {
super.init();
FireBaseUtils.initilizeFirebase();
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String email = request.getParameter("email");
String password = request.getParameter("pass");
//System.out.println(name);
try{
//a hashmap for the number of shopsOwned
HashMap<String, String> shopsOwned = new HashMap<>();
shopsOwned.put("shopName" , "shopName");
//get the database instance and the database reference
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Business");
DatabaseReference ownersRef = ref.child("Owners"); //further get the reference to the owners node
//create a new owner with the values of the new user, using the Owner class
Owner newOwner = new Owner("userRecord2.getUid()", "userRecord2.getDisplayName()",
"userRecord2.getPhoneNumber()", "userRecord2.getEmail()", shopsOwned);
//create a hashmap of the users, in this case, just one user
Map<String, Owner> users = new HashMap<>();
users.put("userRecord2getPhoneNumber", newOwner); //add the new owner to the hashmap
System.out.println("this is the user :" + newOwner.getFull_name());
//push the new owner hashmap to the database reference
ApiFuture<Void> future = ownersRef.push().setValueAsync(users);
//Object o = future.get(8, TimeUnit.SECONDS);
System.out.println(future.isDone());
//System.out.println(future.isDone());
request.getRequestDispatcher("success.jsp").forward(request, response);
}catch(Exception e){e.printStackTrace();}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request, response);
}
}
any ideas will be appreciated.
Edit : I dont get any errors whatsoever, the webapp runs normally but the realtime db at firebase isn't updated
You need to wait until the future is complete, before the request thread is returned. Otherwise there's no guarantee that the update is completed, and any errors are silently discarded. So try something like the following:
ApiFuture<Void> future = ownersRef.push().setValueAsync(users);
future.get();
request.getRequestDispatcher("success.jsp").forward(request, response);
Writing to Firestore (like interaction with most cloud APIs) happens asynchronously, and on a different thread. When you call future.isDone(), the operation isn't done yet.
You'll want to add a callback that gets called when the operation has completed:
ApiFuture<Void> future = ownersRef.push().setValueAsync(users);
future.addCallback(future, new ApiFutureCallback<String>() {
#Override
public void onSuccess(String result) {
System.out.println("Operation completed with result: " + result);
System.out.println(future.isDone());
request.getRequestDispatcher("success.jsp").forward(request, response);
}
#Override
public void onFailure(Throwable t) {
System.err.println("Operation failed with error: " + t);
}
Also see:
Firebase: Asynchronous Operations with Admin Java SDK

Bitbucket Api with ssh access key as header to get total number of pull requests in java

I want to make a rest call to bitbucket api with ssh private key as header.For example the url is (http://bitbucket.com/rest/api/1.0/repos/testProject/pull-requests?state=OPEN).
Is there a way call this url with spring rest template and how to pass ssl access key as header.
Instead of using SSH keys use Personal Access Tokens:
https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html
(Introduced in Bitbucket 5.5)
Then you could use code like this:
package com.company.bitbucket.tools.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import com.company.bitbucket.tools.HttpRequestInterceptor;
import com.company.bitbucket.tools.ProjectValue;
import com.company.bitbucket.tools.Projects;
import com.company.bitbucket.tools.UserValue;
import com.company.bitbucket.tools.Users;
#Controller
public class ProjectController {
public static String BITBUCKET_URL = "https://bitbucket.company.com/rest/api/latest/";
public static String PROJECTS = "projects";
public static String PERMISSIONS = "permissions/users?permission=PROJECT_ADMIN";
public static String PAT = "<put your generated token in here>";
#RequestMapping(value={"/projects"}, method = RequestMethod.GET)
public ModelAndView listProjects(){
HashMap<String, String> list = getAdmins();
ModelAndView model = new ModelAndView("projects");
model.addObject("adminMap", list);
return model;
}
private HashMap<String, String> getAdmins(){
HashMap<String, String> projectMap = new HashMap<>();
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new HttpRequestInterceptor("Authorization", "Bearer ".concat(PAT)));
restTemplate.setInterceptors(interceptors);
Projects projects = restTemplate.getForObject(BITBUCKET_URL.concat("projects?limit=100"), Projects.class);
for(ProjectValue projectValue: projects.getValues()) {
String projectUrl = String.format("%s/%s/%s/%s", BITBUCKET_URL, PROJECTS, projectValue.getKey(), PERMISSIONS);
Users users = restTemplate.getForObject(projectUrl, Users.class);
List<String> names = new ArrayList<>();
for (UserValue value: users.getValues()) {
names.add(value.getUser().getDisplayName());
}
String commaSeparatedNames = String.join(", ", names);
projectMap.put(projectValue.getName(), commaSeparatedNames);
}
return projectMap;
}
}
This code gets a list of project admins using the rest api, but you could change to make whatever rest request you wish.

/ExampleApplication/IntrusionException] INTRUSION - Mixed encoding (2x) detected in URL

I am retrieving URL from database and it contains special characters like % - = / ? etc. so while I try to populate that in my page JSON is not able to parse that URL and it is giving me some exception when I was debugging I got like this
(Log4JLogger.java:log:449) [SECURITY FAILURE Anonymous:null#unknown -> /ExampleApplication/IntrusionException] INTRUSION - Mixed encoding (2x) detected
I tried from these link here this my offending URL here
but it is not working he mentioned that bug is solved. but for which version version here I am using is 2.1.0 below is my code
package com.ghn.repufact.review.extractor;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.log4j.Logger;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.Validator;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.reference.DefaultValidator;
import org.springframework.stereotype.Component;
#Component
public class ValidateURL {
private static final Logger logger=Logger.getLogger(ValidateResponse.class);
public String parseOrgConsumerLink(String myLink) throws URISyntaxException {
if(myLink==null || "".equalsIgnoreCase(myLink))
return myLink;
Encoder enc=ESAPI.encoder();
URI mixURI=new URI(myLink);
UriBuilder uriBuider=UriBuilder.fromUri(enc.canonicalize(mixURI.getAuthority()+mixURI.getPath()));
uriBuider.path(enc.canonicalize(mixURI.getAuthority() + mixURI.getPath()));
logger.info("Uri after URIbuilder:"+uriBuider.build().toString());
List<NameValuePair> params = URLEncodedUtils.parse(mixURI, "UTF-8");
for (NameValuePair nameValuePair : params)
uriBuider.queryParam(enc.canonicalize(nameValuePair.getName()), enc.canonicalize(nameValuePair.getValue()));
String canonicalizedUrl = uriBuider.build().toString();
logger.info("canonicaliz URI:"+canonicalizedUrl);
return canonicalizedUrl;
}
public boolean isCanonicalizedURI(String myLink) throws EncodingException {
Validator validator=DefaultValidator.getInstance();
//boolean flag=validator.isValidInput("test", myLink, "URI", 200, false);
myLink = ESAPI.encoder().encodeForURL(myLink);
boolean flag = validator.isValidInput("APPNAME", myLink, "URLSTRING", 600, true, false);
logger.info("checking for URI:"+myLink+" isCanonical:"+flag);
return flag;
}
}
please let me know if any work around here. By the way I am using spring MVC

How to create Couchbase bucket via java API?

I am Using Spring data couchbase .
package com.CouchbaseMine.config;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
import com.couchbase.client.CouchbaseClient;
#Configuration
#EnableAutoConfiguration
public class CouchbaseMineCouchBaseConfig extends AbstractCouchbaseConfiguration {
#Value("${couchbase.cluster.bucket}")
private String bucketName;
#Value("${couchbase.cluster.password}")
private String password;
#Value("${couchbase.cluster.ip}")
private String ip;
#Override
protected String getBucketName() {
List<URI> uris=new LinkedList<URI>();
uris.add(URI.create("5x.xx.xxx.xx9"));
CouchbaseClient client=null;
try {
System.err.println("-- > - > i am in ");
client=new CouchbaseClient(uris,"default","");
} catch (IOException e) {
System.err.println("IOException connetion to couchbase:"+e.getMessage() );
System.exit(1);
}
return this.bucketName;
}
#Override
protected String getBucketPassword() {
return this.password;
}
#Override
protected List<String> bootstrapHosts() {
// TODO Auto-generated method stub
//return Collections.singletonList("54.89.127.249");
return Arrays.asList(this.ip);
}
}
This is configuration class used for establish connection
Follow application properties file
server.port=3000
couchbase.cluster.ip 5x.xx.xxx.xx9
couchbase.cluster.bucket DHxxxar
couchbase.cluster.password 1221
Bottom line: I have created the bucket (Dhxxxar) manually in couchbase.But i need to automatically create the bucket(database) while i run my spring boot application.
So give me any suggestion regards the same . Thanks in advance
Try this:
Cluster cluster = CouchbaseCluster.create("127.0.0.1");
ClusterManager clusterManager = cluster.clusterManager("Administrator", "12345");
BucketSettings bucketSettings = new DefaultBucketSettings.Builder()
.type(BucketType.COUCHBASE)
.name("hello")
.quota(120)
.build();
clusterManager.insertBucket(bucketSettings);
More details:
https://developer.couchbase.com/documentation/server/current/sdk/java/managing-clusters.html
IgorekPotworek's answer is great for Couchbase Java SDK version 2.x.
For version 3.x, the code looks a little different:
Cluster cluster = Cluster.connect("localhost", "Administrator", "password");
BucketManager bucketManager = cluster.buckets();
bucketManager.createBucket(
BucketSettings.create("bucketName")
.ramQuotaMB(100));

endpoint query from datastore google app engine

I wrote this code that will pull everything from my entity "ContactInfo" from the app engine datastore and place it into a string.
My question is how do I make specific queries in the android endpoint. I only want to display the items in the entity that are a certain name or zipcode for example. Here is what I have to put the entire entity into a string.
package com.indeeditis;
import java.io.IOException;
import java.util.Date;
import org.json.JSONException;
import android.os.AsyncTask;
import android.content.Context;
import android.content.Intent;
import com.indeeditis.MainActivity.EndpointsTask;
import com.indeeditis.contactinfoendpoint.Contactinfoendpoint;
import com.indeeditis.contactinfoendpoint.model.CollectionResponseContactInfo;
import com.indeeditis.contactinfoendpoint.model.ContactInfo;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.app.Activity;
import android.view.View.OnClickListener;
public class FinderActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finder);
Button start = (Button)findViewById(R.id.button9000);
start.setOnClickListener(this);
}
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
protected Long doInBackground(Context... contexts) {
Contactinfoendpoint.Builder endpointBuilder = new Contactinfoendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Contactinfoendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
String apples = endpoint.listContactInfo().execute().toString();
Log.w("myApp", apples);
} catch (IOException e) {
e.printStackTrace();
}
return (long) 0;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new EndpointsTask().execute(getApplicationContext());
}
}
For applying filters while sending a query request from android through cloud endpoints, you need to add options to set parameters. I will explain with a short example
1, Assume your contactinfo endpoint has 2 properties
name = ndb.StringProperty()
contacttype = ndb.StringProperty() // assume this can have values personal or business
2, Now if you need to query for a particular contacttype, then your app engine code should have a query method that filters based on the property contacttype.
Your endpoint should call this query method by passing on the input parameter from the user.
3, Now to send the required parameter from android , your class Listcontactinfo where you would define the REST Path and method type, should include an option to the set the contacttype parameter
#com.google.api.client.util.Key
private String contacttype;
public String getContacttype() {
return contacttype;
}
public Listcontactinfo setContacttype(String contacttype) {
this.contacttype = contacttype;
return this;
}
4, Finally while calling the endpoint method from your android code, you should pass a value using the setContacttype, which will be something like:
String apples = endpoint.listContactInfo().setContacttype("personal").execute().toString();
This is for an example case where you want to query entities having contacttype with value "personal"

Categories