Cant understand visibility of method via interface - java

Im working with open source library to test facebook api features https://code.google.com/archive/p/facebook-test-java-api/
Now what I'm trying to do is to change my test user name. I dived into code of this library and found the following:
public interface FacebookTestUserAccount
{
// irrelevant methods
/**
* Gives access to change settings for the test user.
* #return An {#code AccountSettingsChanger} responsible for updating the account settings.
*/
AccountSettingsChanger changeAccountSettings();
// irrelevant methods
}
Now my test goes like this:
#Test
public void updateNameOfTestUser(){
List<FacebookTestUserAccount> allTestUsers = store.getAllTestUsers();
FacebookTestUserAccount facebookTestUserAccount = allTestUsers.get(0);
facebookTestUserAccount.// here after dot I cant see method changeAccountSettings()
}
Since my refrence method is the type of the interface, and the method is defined in interface, what Im struggling with:
Why I cant see the method in my test class?
thats the code of getALL();
public List<FacebookTestUserAccount> getAllTestUsers() {
init();
String jsonResponse = get("/%s/accounts/test-users", applicationId);
JSONObject accounts = parseJsonObject(jsonResponse);
LinkedList<FacebookTestUserAccount> result = new LinkedList<FacebookTestUserAccount>();
JSONArray jsonArray = (JSONArray) accounts.get("data");
for (Object element : jsonArray) {
JSONObject jsonUser = (JSONObject) element;
result.add(buildFacebookAccount(jsonUser));
}
log.debug("* Found [{}] accounts on Facebook ", result.size());
return result;
}

I can think of two possible reasons for your problem:
Your IDE failed to load the auto-complete suggestions. To check this, just write changeAccountSettings() after the dot, and try to compile. (I suspect this is your problem, because you phrased your question like "Why can't I see this..?")
You have two different FacebookTestUserAccounts in your codebase, and you have imported the wrong one.

Related

What all unit test cases should I write for following function ? Also, how to provide sample JSONobject as parameter in the function?

Here is the function that I want to unit test. I am writing this in android and since JSONObject is an android class, I can't initiate, I can just mock, But I also want to test for the case where there is sample JSON and it provides correct result or exception (if incorrect sample JSON)
public List<GithubRepositorySchema> parseAndReturnGithubRepositorySearchResponse(JSONObject response) throws Exception {
List<GithubRepositorySchema> githubRepositorySchemas = new ArrayList<>();
if (response.has("items")) {
JSONArray items = response.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
JSONObject repoObj = items.getJSONObject(i);
githubRepositorySchemas.add(new GithubRepositorySchema(
repoObj.getString("name"),
repoObj.getBoolean("private"),
repoObj.getString("description"),
repoObj.getString("language"),
repoObj.getInt("forks_count"),
repoObj.getInt("open_issues"),
repoObj.getInt("watchers")
));
}
} else {
throw new JSONException("Incorrect Json");
}
return githubRepositorySchemas;
}
Your test cases can be:
1. Test with a single item JSON, assert that the object has the same properties
2. Multiple item JSON, check properties of the objects
3. Test without "items" and see that your method throws an Exception
4. Fool around with individual keys of the Object. I notice that you're not using similar has"key" checks for the Object. This is one area where Unit Testing actually can expose a bug in your code.
Edit: You can build JSONObject via the constructor and add Objects to it, just like a Map. Look it up.
I wouldn't recommend writing this code. Plenty of parsers out there (Gson, Moshi, Jackson) which do this for free.

Parsing Json Arrays from an API for an IRC Bot and Creating an initial message

1st Question:
Im creating an IRC Bot in java using Pircbot that implements the OpenWeatherMap API, and I'm having trouble displaying an initial message that is sent from the bot as soon as it connects to the channel. I want this message to display instructions on how to use the APIs. I tried doing this in the constructor, but that didn't work as you need the channel string as seen in the onMessage method. I searched through the methods in the Pircbot website but couldn't find a method for this.
2nd Question:
I'm having problems implementing a certain part of OpenWeatherMap's API. For "weather", it uses a JsonArray and I'm not entirely sure how to parse it. Because it's an API and not a file, the solutions I've found online haven't been working because they use JsonReader while I'm trying to use JsonParser. Here's my code trying to parse this Array. I'm trying to access the "main" key from the "weather" JsonArray.
static String parseJsonWeatherMain(String json)
{
JsonElement jelement = new JsonParser().parse(json);
JsonObject MasterWeatherObject = jelement.getAsJsonObject();
JsonArray weatherArray = MasterWeatherObject.getAsJsonArray("weather");
String main = weatherArray.get(1).getAsString();
return main;
}
For reference, this is how I parsed the other keys that were just from JsonObjects:
static double parseJsonWindGust(String json)
{
JsonElement jelement = new JsonParser().parse(json);
JsonObject MasterWeatherObject = jelement.getAsJsonObject();
JsonObject windObject = MasterWeatherObject.getAsJsonObject("wind");
double gust = windObject.get("gust").getAsDouble();
return gust;
}
so any ideas on how to parse this JsonArray? I want the "main" and "description" keys to be exact.
Well.. I'm not a real Java developer, but i will give it a shot.
Question 1: Publishing message when bot joins a channel
This sounds like a classic onJoin event.
From PircBot documentation
protected void onJoin(String channel,
String sender,
String login,
String hostname)
This method is called whenever someone (possibly us) joins a channel
which we are on.
The implementation of this method in the PircBot
abstract class performs no actions and may be overridden as required.
Parameters:
channel - The channel which somebody joined.
sender - The nick of the user who joined the channel.
login - The login of the user who joined the channel.
hostname - The hostname of the user who joined the channel.
Question2: Extracting main property from JObject which inside a JArray.
You came close to the solution, you only forgot a very basic thing.
weather is an array of objects, thus you should expect weatherArray.get(1) will return an object, an object of which you should then apply .get("main") to extract json object property named "main", which only the you can apply .getAsString() because it's a normal string.
Code (not been tested, but the idea is understandable)
JsonArray weatherArray = MasterWeatherObject.getAsJsonArray("weather");
for (int i = 0; i < weatherArray.size(); i++) {
String main = weatherArray.get("main").getAsString();
System.out.println(main);
}

Playframework Result how check is working

Hello I have got small problem I'm learning play 2.2.1 framework and I was making controllers like
public static Result Name(){
List<Account> names = Account.find.all();
List name = new ArrayList();
for(Account a: names)
{
name.add(a.getName());
}
return ok(Json.toJson(name));
}
And in routes I added line
GET /api/name controllers.AccController.Name()
And this function gives me all names from database now I wanted to make function where i can choose what column from database name/surname/country I want to get I made something like this:
public static Result typewhat(String what) {
String[] type = what.split(" ");
then I made if type[1] == name and same like upper but I dont know how to test now thats working or not in Routes I add line:
PUT /api/findwhat controllers.AccController.typewhat(what: String)
Im using Open HttpRequester and for localhost:9000/api/name it is working
but I totally dont know how to make it for this functiong typewhat
I will be very thankful for every help.
PUT /api/findwhat controllers.AccController.typewhat(what: String)
for above path try
localhost:9000/api/name?what=this is that
dont know java well but in scala it works fine
def typewhat(what:String) = Action { implicit request =>
println("gs",what)
val strAr = what.split(" ")
println(strAr)
Ok(strAr(0))
}

how to display the information inside an object

we are assigned to implement the inside of a code block wherein it is associated with a given class (EmployeeProjectDetail) which is declared as a arraylist.
my code follows below.
public List<EmployeeProjectDetail> getEmployeeProjectHistory(long employeeID, long projectID) {
List<EmployeeProjectDetail> detailList = new ArrayList<EmployeeProjectDetail>();
return detailList;
}
I tried inputting the statements.
detailList.contains(projectDAO.getEmployeeProjects(employeeID));
detailList.contains(projectDAO.getEmployeeProjectRoles(employeeID, projectID));
the code then doesn't return any value but the invovled sql queries in projectDAO class are thoroughly handled. any help will be appreciated.
contains checks whether an item is in a list what your are looking for is add.
You should add the line
detailList.add(projectDAO.getEmployeeProjects(employeeID));
Update (I'm guessing on the method and class names)
Based on the ClassCastException it appears that getEmployeeProjects(employeeID) returns an ArrayList. If the objects in this ArrayList are EmployeeProjectDetail's you can just replace the method body with return projectDAO.getEmployeeProjects(employeeID);. If they are a different object representing a project, say EmployeeProject, you would need to replace the method body with the following code:
List<Project> projects = projectDAO.getEmployeeProjects(employeeID);
ArrayList<EmployeeProjectDetail> projectDetails = new ArrayList<EmployeeProjectDetail>();
for (Project project : projects) {
if(project.getProjectID == projectID){
projectDetails.add(project.getProjectDetail());
}
}

problems with RequestForFile() class that is using User class in Java

Okay I'll try to be direct.
I am working on a file sharing application that is based on a common Client/Serer architecture. I also have HandleClient class but that is not particularly important here.
What I wanna do is to allow users to search for a particular file that can be stored in shared folders of other users. For example, 3 users are connected with server and they all have their respective shared folders. One of them wants to do a search for a file named "Madonna" and the application should list all files containing that name and next to that file name there should be an information about user(s) that have/has a wanted file. That information can be either username or IPAddress. Here is the User class, the way it needs to be written (that's how my superiors wanted it):
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class User {
public static String username;
public static String ipAddress;
public User(String username, String ipAddress) {
username = username.toLowerCase();
System.out.println(username + " " + ipAddress);
}
public static void fileList() {
Scanner userTyping = new Scanner(System.in);
String fileLocation = userTyping.nextLine();
File folder = new File(fileLocation);
File[] files = folder.listFiles();
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
list.add(i, files[i].toString().substring(fileLocation.length()));
System.out.println(list.get(i));
}
}
public static void main(String args[]) {
System.out.println("Insert the URL of your shared folder");
User.fileList();
}
}
This class stores attributes of a particular user (username, IPAddress) and also creates the list of files from the shared folder of that particular user. the list type is ArrayList, that's how it has to be, again, my superiors told me to.
On the other hand I need another class that is called RequestForFile(String fileName) whose purpose is to look for a certain file within ArrayLists of files from all users that are logged in at the moment of search.
This is how it should look, and this is where I especially need your help cause I get an error and I can't complete the class.
import java.util.ArrayList;
public class RequestForFile {
public RequestForFile(String fileName) {
User user = new User("Slavisha", "84.82.0.1");
ArrayList<User> listOfUsers = new ArrayList();
listOfUsers.add(user);
for (User someUser : listOfUsers) {
for (String request : User.fileList()) {
if (request.equals(fileName))
System.out.println(someUser + "has that file");
}
}
}
}
The idea is for user to look among the lists of other users and return the user(s) with a location of a wanted file.
GUI aside for now, I will get to it when I fix this problem.
Any help appreciated.
Thanks
I'm here to answer anything regarding this matter.
There are lots of problems here such as:
I don't think that this code can compile:
for (String request : User.fileList())
Because fileList() does not return anything. Then there's the question of why fileList() is static. That means that all User objects are sharing the same list. I guess that you have this becuase you are trying to test your user object from main().
I think instead you should have coded:
myUser = new User(...);
myUser.fileList()
and so fileList could not be static.
You have now explained your overall problem more clearly, but that reveals some deeper problems.
Let's start at the very top. Your request object: I think it represents one request for one user with one file definition. But it needs to go looking in the folders of many users. You add the the requesting user to a list, but what about the others. I think that this means that you need another class responsible for holding all the users.
Anyway lets have a class called UserManager.
UserMananger{
ArrayList<User> allTheUsers;
public UserManager() {
}
// methods here for adding and removing users from the list
// plus a method for doing the search
public ArrayList<FileDefinitions> findFile(request) [
// build the result
}
}
in the "line 14: for (String request : User.fileList()) {" I get this error: "void type not allowed here" and also "foreach not applicable to expression type"
You need to let User.fileList() return a List<String> and not void.
Thus, replace
public static void fileList() {
// ...
}
by
public static List<String> fileList() {
// ...
return list;
}
To learn more about basic Java programming, I can strongly recommend the Sun tutorials available in Trials Covering the Basics chapter here.
It looks like you're getting that error because the fileList() method needs to returns something that can be iterated through - which does not include void, which is what that method returns. As written, fileList is returning information to the console, which is great for your own debugging purposes, but it means that other methods can't get any of the information fileList sends to the console.
On a broader note, why is RequestForFile a separate class? If it just contains one method, you can just write it as a static method, or as a method in the class that's going to call it. Also, how will it get lists of other users? It looks like there's no way to do so as is, as you've hard-coded one user.
And looking at the answers, I'd strongly second djna's suggestion of having some class that acts as the controller/observer of all the Users.

Categories