How to create a document without value to MongoDB in Java - java

In a relational database generally, you can define a field first then store data accordingly. In my case, I want to do the same to MongoDB to create a collection and document (fields) without value to test it.
I created a collection and empty document with field name in my Service class, but not sure how to post it to the database.
Here is the service class
public class PlayCardService {
MongoDatabase database = dBUtils.getMongoDB();
public PlayCardService() {
}
public void create(PlayCardService gc) {
// Create or get table
MongoCollection<Document> tcTbl = database.getCollection("PlayCard_tbl");
// create document (field)
Document pcDoc = new Document("PlayCardNumber", null).append("SecurityCode", null).append("Type",
Arrays.asList("bronze", "silver", "gold"));
pcTbl.insertOne(tcDoc);
}
Here is the add play card servlet just to test if it can create a collection in MongDB mlab
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// create new card
PlayCard pc = new PlayCard ();
request.setAttribute("pcNumber", null);
pcService.create(tc);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}

Related

Send more than one attribute for the request.setAttribute ()

I am developing a web page where on the homepage (in my case it is my "Home" servlet) I wish to present information about several tables as well as queries to them. What I have achieved is to obtain the information of my company / brands table and show the last companies added, the detail is that I do not know how to send more than one attribute for the request.setAttribute () since I want to show in my homepage information of my users table and show my featured users as well as my table news show the last post (news from suppliers). I hope and I can help myself since I am super stuck with this.
This is my code for my servlet.
public class InicioController extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd;
//Connection DB
conexion conn = new conexion();
//send objectd Connection to the constructor of myDAO class
HomeDAO fun = new HomeDAO(conn);
List<companies> list1 = new LinkedList<>();
List<users> list2 = new LinkedList<>();
List<postNews> list3 = new LinkedList<>();
// call to the method that gets the information from my companies table
list1=fun.ShowCompanies("");
// call to the method that gets the information from my Users table
list2=fun.LastUsers("");
// call to the method that gets the information from my Posts table
list3=fun.News("");
//disconnect DB
conn.desconectar();
//how to send more than one attribute "request.setAttribute ()"
request.setAttribute("Companies", list1);
rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
Why can't you have an object that will contain all three lists, plus whatever other objects you want to "pass" to your JSP? Your attribute will contain that single object in an attribute and the JSP can sort it out. It's good design also, because that way you have in one class, all the "parameters" that the specific JSP expects.

I can not make a request and the Response to a servlet

I have a servlet. in it I form a line and when I type in the browser link, he told me that rotates the line. everything is fine. Now I want to create an array of strings, and depending on the parameter in the link rotates the particular row. how to do it?
#WebServlet("/goods")
public class GoodsServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("{\"name\":\"Pavel\",\"sname\":\"Petrashov\",\"age\":24,\"params\":{\"heigth\":188, \"weight\":72, \"strong\":100}}");
}
}
and I want to have
List<String> list = new ArrayList<String>();
list.add("{\"name\":\"Pavel\",\"sname\":\"Petrashov\",\"age\":24,\"params\":{\"heigth\":188, \"weight\":72, \"strong\":100}}");
list.add("{\"name\":\"Bill\",\"sname\":\"Gey\",\"age\":99,\"params\":{\"heigth\":188, \"weight\":70, \"strong\":100}}");
list.add("{\"name\":\"Uill\",\"sname\":\"Smitt\",\"age\":12,\"params\":{\"heigth\":188, \"weight\":99, \"strong\":100}}");
and to make sure that my reference http://localhost:666/sg/goodstook some parameter, depending on which will return an array element
Do you mean depending on GET parameters you want to print out one of the strings in the list? If that is what you want then
String myParameter = request.getParameter("param");
will give you the get parameter. Pass the parameter as a query string on the url like http://localhost:666/sg/goods?param=2.
Now use the parameter to get the string from your list
try{
int index = Integer.parseInt(myParameter);
out.println(list.get(index));
} catch(IndexOutOfBoundsException|NumberFormatException ex){
System.err.println("Invalid get parameter");
}

Fetching particular value from entity in GAE DataStore without PersistantManager

I'm trying to register a user and allow him to login with userName and Password. My dataStore entity "Racer" contains Name, UserName, Password, Age, BikeModel, City. Key is generated by the application.
I want to validate user. I used query with addFilter() to get the entire details of a particular user. I am struck with getting a particular property of a particular user from the entity in dataStore, say, Password and UserName of a particular user from "Racer".
Over the web, whichever example i got, it was using PersistentManager. I don't want to use it. I don't find any query to fetch details other than Filter and Sort. Please suggest me how to proceed.
Servlet:
public class StoreInDataStore extends HttpServlet {
#SuppressWarnings("deprecation")
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
//Getting SignUp form values
String name=req.getParameter("name1");
String uname=req.getParameter("uname1");
String pswd=req.getParameter("pswd1");
String age=req.getParameter("age");
String city=req.getParameter("city");
String bike=req.getParameter("bike");
//Getting login form values
String lname=req.getParameter("name");
String lpswd=req.getParameter("pswd");
//Creating dataStore
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
//Creating entity
Entity e=new Entity("Racer");
//Entering details in racer
e.setProperty("Name", name);
e.setProperty("UserName", uname);
e.setProperty("Password", pswd);
e.setProperty("Age", age);
e.setProperty("City", city);
e.setProperty("Bike Model", bike);
//Storing in DataStore
ds.put(e);
//Getting entire details
Query q=new Query("Racer");
q.setFilter(FilterOperator.EQUAL.of("UserName", uname));/* UserName takes only the currently entered value(uname). Doesnot fetch from dataStore */
PreparedQuery pq=ds.prepare(q);
List<Entity> result = ds.prepare(q).asList(FetchOptions.Builder.withDefaults());
System.out.println(result);
}
Instead of
List<Entity> result = ds.prepare(q).asList(FetchOptions.Builder.withDefaults());
use
Entity result = ds.prepare(q).asSingleEntity();
String password = result.getProperty("Password");

PayPal: alternative to ConfigManager.getInstance().load()

I'm trying to create an IPN listener by following this example:
public class IPNListenerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ConfigManager.getInstance().load(this.getClass().getResourceAsStream("/sdk_config.properties"));
IPNMessage ipnlistener = new IPNMessage(request);
boolean isIpnVerified = ipnlistener.validate();
String transactionType = ipnlistener.getTransactionType();
Map<String,String> map = ipnlistener.getIpnMap();
LoggingManager.info(IPNListenerServlet.class, "******* IPN (name:value) pair : "+ map + " " +
"######### TransactionType : "+transactionType+" ======== IPN verified : "+ isIpnVerified);
}
}
However ConfigManager.getInstance().load() is deprecated and, in my project, the config file is not in the default location so, what is the right way to load the configuration file?
Possible solution:
Provide an empty sdk_config.properties in the default location;
Load the property file manually, get the related map and pass it to the IPNMessage constructor;
More info here.

Use an Ajax response in JSP

I have a JSP page which has nothing but a normal HTML table with five rows and five columns.
Now I am making an Ajax call and get a response back. Now once I have the response back, I need the data to be filled in appropriate cells of the table.
So my question is;
Should I use JSON for building the response?
How do I handle the data back at the JSP level. That is, once I have the response from the server?
Just as additional information, I am using DWR which is nothing but calling a Java method (which builds the response) from inside JavaScript code.
Let's consider this Java class.
class Employee
{
int id;
String eName;
// Setters and getters
}
In JavaScript, the JSON object:
var employee = {
id : null,
name : null
};
This is the call to a Java method from a JavaScript function:
EmployeeUtil.getRow(employee,dwrData);
In getRow() of the EmployeeUtil class, the return type of method will be Employee:
Employee getRow();
So using the setters of Employee set the data. dwrData is the callback function.
function dwrData(data) {
employee=data;
}
The data returned, which is an Employee bean, will be in the callback function.
Just initialize this in the JavaScript JSON object.
Use a JSON object accordingly to populate the table.
EDIT :
You can use List getRow() instead of Employee getRow(), returning a list of rows as a List instead of a Bean.
Now the response contains list as data.
Refer to Populate rows using DWR.
Check these examples to populate data in table:
DWR + Dojo Demo
Dynamically Editing a Table
Should I use JSON for building the response?
No need to pass JSON in response. Instead return a Bean of a class as mentioned above.
A list can be passed as a response, also as mentioned above.
How do I handle the data back at the JSP level. That is, once I have the response from the server.
Check the explanation above and the examples of the given links to handle the response in JSP and display the response data in a table.
DWR basics on YouTube
JSP pages are dynamically generated servlets. Once a user hits a JSP page, they receive dynamically generated HTML that no longer talks to the JSP page that generated it unless they complete an action such as hitting "refresh" or submitting a form. Check out the JSP Page at Oracle for more info and Wikipedia for a decent high level explanation of JSP technology.
To handle the AJAX, you're going to need to define a new network endpoint capable of processing the XML requests coming up from the Javascript. See this example, this library, or this JSON Example.
What I do quite frequently is setup two servlets for this situation:
MyServlet
MyAJAXServlet
MyServlet handles the normal HTTP requests and (usually) ends up using a RequestDispatcher to forward the request to a JSP.
Example:
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = -5630346476575695999L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
private final void doGetAndPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
/*
* Handle the response here, manipulate the 'MODEL'
*/
/*
* Forward to the 'VIEW' (No Baba Wawa jokes please)
*/
RequestDispatcher rdis = req.getRequestDispatcher("Path/To/My/JSP");
rdis.forward(req, res);
}
}
Where as the AJAX servlet checks the request's parameter list for presence of a 'command':
public class MyAJAXServlet extends HttpServlet {
private static final long serialVersionUID = -5630346476575695915L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
private final void doGetAndPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
String cmd = req.getParameter("cmd");
if (cmd == null || cmd.length() < 1) {
/* Custom fail mode here, perhaps toss back failure HTML */
return;
}
/* Easily implement command pattern here, but for simplicity, we will use an if tree */
if (cmd.equalsIgnoreCase("getSomeData")) {
String out = "<tr><td>ExampleCell in ExampleRow</td></tr>";
res.getWriter().append(out);
return;
} else if (cmd.equalsIgnoreCase("someOtherCommand")) {
/* Do something else */
}
}
}
If you format your JSP to allow for bulk replacement of html elements like so:
<table id="pleaseReplaceMyContentsTABLE">
<tr><td> </td></tr>
</table>
Then it becomes very easy to dynamically modify a web pages content (I use JQuery for this example):
var url = "http://mydomain.whatever/myapp/MyAJAXServletMappedURL?cmd=getSomeData";
$.post(url, function(data) {
//Message data a bit & display
$("#pleaseReplaceMyContentsTABLE").html(data);
});
Some limitations with sending back preformatted HTML from the AJAX Servlet:
If you are sending back a moderate to large amount of data, then your webserver will easily become overloaded when the number of clients starts to rise. Aka, it won't scale well.
Java code that is formatting HTML to send to a client can get ugly and hard to read. Quickly.
If you use DWR you don't need to use JSON, it uses internally.
Use javascript , the jsp code is out-of-scope. The page has been generated so you only can modify the DOM using javascrip
There are lot of examples doing what you need in DWR tutorials. I suppose you need just do something as:
dwrobject.funtionAjax(param,returnFunction);
...
function returnFunction(data) {
// use javascript to change the dom
}
Ajax part: We return a list of objects:
public List<IdTexto> getPaisesStartingBy(String texto,String locale){
List<IdTexto> res = new ArrayList<IdTexto>();
// Fill the array
return res;
}
The IdTexto is a simple bean with geters and setters:
public class IdTexto {
private int id;
private String texto;
private String texto2;
// getters and setters
}
And it is defined in the dwr.xml as bean:
<convert converter="bean" match="com.me.company.beans.IdTexto"/>
And the class containing the java function is defined as creator:
<create creator="new" javascript="shopdb">
<param name="class" value="com.me.company.ajax.ShopAjax"/>
</create>
In the jsp, we define a function javascript to retrieve the List of starting by some text object in this way:
shopdb.getPaisesStartingBy(req.term,'<s:text name="locale.language"/>', writePaises);
And the corresponding function to write down the texts:
function writePaides (data) {
var result="<table>";
for (i=0; i<data.length;i++) {
id = data[i].id;
texto=data[i].texto;
texto2=data[i].txto2;
// now we write inside some object in the dom
result+="<tr><td>"+id+"</td><td>"+texto+"</td><td>"+texto2+"</td></tr>";
}
result+="</table>";
$("tabla").innerHTML=result;
}
If you, instead of a bean have some other object you'll access the properties in the same way.

Categories

Resources