Playframework Result how check is working - java

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))
}

Related

Why Architecture rule Violation exception is coming if I change the passing parameter of the method?

I am having very weird situation here , In my project we have Architecture Rules Test. but this below method did not throw any error msg , but when I just change a method passing meter from String to Query and change the first line of the method then it is throwing
Architecture Violation [Priority: MEDIUM] - Rule exception, (the rule is set to check if we are importing any third party library class in our specific class which for biddable and we have written IT for the same so no one should use third part library lets say classes from com.google.* here since I am using here ArrayListMultimap from com.google.common.. so this is failing , but the real question here is why it is happening when I am changing the parameter and why it was working fine earlier , this rule is breaking after I made changes in just parameter I did not add the class in ArrayListMultimap in this map and error is coming like I am using ArrayListMultimap .create() method ehich is breaking the rule )
Because the package this method is present(let's package P) is not supposed to depend on the classes present in packages ['com.google.common..', 'com.google.thirdparty..']'.
And ArrayListMultimap<String, Integer> xAndYMap = ArrayListMultimap.create(); this from google package. Here my doubt is why it is working if I dont change the method passing parameter type (first it was String then I changed from String -> Query).
I am not able to resolve it. What am I supposed to do here , is this happening because I changed function def by changing passing parameter? or if it is so why it was working and building the project successfully.
Could anyone please help here to understand the situation ?
Thanks in advance:)
the Method is given below:
private Map<CONSTANT_X, List<Integer>> getAllOfCaseCountGroupMap(final Query query) {
List<Object[]> results = this.getQueryResultsAsList(query);
Map<CONSTANT_X, List<Integer>> result = new HashMap<>();
ArrayListMultimap<String, Integer> xAndYMap = ArrayListMultimap.create();
for (Object[] objs : results) {
CONSTANT_X x = CONSTANT_X.valueOf(objs[0].toString());
Integer caseId = (Integer) objs[1];
xAndYMap.put(x.toString(), caseId);
}
for (String key : xAndYMap.keys()) {
CONSTANT_X x = CONSTANT_X.valueOf(key);
List<Integer> y = xAndYMap.get(key);
result.put(x, y);
}
return result;
}`enter code here`

Using Selenium with Java to Automate, how to I make an object oriented part of a script "actionable?"

I have automated a new customer form for work, but there are a lot of options and based on how questions are answered , different fields need to be filled out. Rather than just make a copy of the code and make a different script for each option, I'd like to do this by passing values to a class that determines what options are chosen based on what is passed in. I'm trying to figure most of this out myself and I'm somewhat of a n00b, but if someone can get me past the first hurdle, I'd like to tackle the rest of the hurdles myself.
So I want to start by just doing one line of the script this way, and eventually I will do more. Up front, it is going to seem like a lot of code just to do this, but here is the line:
driver.findElement(By.id("OrganizationName")).sendKeys("The Rolling Stones");
Here is what I have so far:
ncformPage1 skifootz = new ncformPage1("Rolling Stones");
skifootz.getOrgname();
That is the part that is in the script. Here is the class I wrote:
public class ncformPage1 {
private String orgName;
public ncformPage1(String on) {
orgName = on;
}
public String getOrgname() { return "driver.findElement(By.id(\"OrganizationName\")).sendKeys(\""
+ orgName + "\");";
}
}
So when I run this, it goes right past that organizationName element and leaves it blank, does all the other elements, and then fails because organization name is a required field. So I added this bit of code here to see what it prints out to the console:
System.out.println( skifootz.getOrgname());
Sure enough, it prints out
driver.findElement(By.id("OrganizationName")).sendKeys("Rolling Stones");
Which is exactly what I want returned. (I think the last semicolon is extraneous in this case, but at least it returned what I wanted!) But it doesn't execute that. I've tried all kinds of stuff to get it to execute, such as removing driver from what is returned and appending it here instead:
driver.skifootz.getOrgname();
but that gives me skifootz cannot be resolved or is not a field. I tried this:
String a = skifootz.getOrgname();
driver.a();
But that just made a get underlined in red saying method a() is undefined for the type Webdriver. So then I changed String a to Webdriver a:
WebDriver a = skifootz.getOrgname();
driver.a();
But now skifootz.getOrgname(); is underlined saying "type mismatch: cannot convert from String to WebDriver." I've been messing around with it for a few days now, and I haven't gotten any closer. Maybe this is an easy solution, but if I can just get this part working then perhaps I can move on to the next phase? This n00b thanks everyone in advance for any help anyone can give.
The method is returning a String type and you expect it to act like a driver object. That part is incorrect.
I think you can write methods to be more like
public WebElement getOrgname(WebDriver driver, String OrganizationName) {
return driver.findElement(By.id(OrganizationName));
}
WebElement a = skifootz.getOrgname(driver);
a.sendKeys("Rolling Stones");
OR
public void TypeText(WebDriver driver, String OrganizationName, String TextToType) {
driver.findElement(By.id(OrganizationName)).sendKeys(TextToType);;
}
in your context this should probably work.
ncformPage1 skifootz = new ncformPage1();
skifootz.getOrgname(skifootz.driver, "OrganizationName");
skifootz.sendKeys("Rolling Stones");
public class ncformPage1 {
private String orgName;
public WebDriver driver = new ChromeDriver(); // I'm assuming this part.
public ncformPage1(String on) {
orgName = on;
}
public WebElement getOrgname(WebDriver driver, String OrganizationName) {
return driver.findElement(By.id(OrganizationName));
}
}

Cant understand visibility of method via interface

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.

Java play routing pass complex objects [Play framework 2.0]

I've been experimenting with the Java Play Framework 2.0 for a few weeks now, but I am now struggling with the following:
How can I pass Java object from one Play template to another?
I can pass simple objects about no problem:
GET /Login/:email controllers.Application.login(email:String)
With the following code in my controller:
public static Result login(String email) {
//Do some stuff
return ok("");
}
But what I need to be able to is something like this:
GET /Test/:user controllers.Application.test(user:User)
With the following code in my controller:
public static Result test(User user) {
//Do some stuff
return ok("");
}
When I try compiling, I get the following error:
not found: type User
Does anybody know what I need to do to get this working? Is it even possible? Appreciate any help!
Using basic (don't want to write 'ordinary') types as routes params is clean approach which will not cause a headache. For an example instead trying to send whole object it's better to send its id - most probably some kind of numeric type or unique String for an example if your user model has id of Long type you can just do it as easy as:
GET /Test/:userId controllers.Application.test(userId: Long)
controller
public static Result test(Long userId) {
User user = User.find.byId(userId);
return ok("Now you're watching user: " + user.name);
}
Other useful sample are booleans which, instead passing it it's just easier use 0/1 Int/int types (with default value set as false):
GET /set-admin/:userId controllers.App.setAdmin(userId: Long, setTo: Int ?= 0)
or true
GET /set-admin/:userId controllers.App.setAdmin(userId: Long, setTo: Int ?= 1)
controller
public static Result setAdmin(Long userId, int setTo) {
User user = User.find.byId(userId);
user.isAdmin = (setTo == 1); // of course isAdmin field of User model is type of Boolean
user.update(id);
return ok("User " + user.name + " is " + user.isAdmin);
}
so in template you can just make a link:
<a href='#routes.App.setAdmin(user.id, 1)'>Set as admin</a>
<a href='#routes.App.setAdmin(user.id, 0)'>Set as common user</a>

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