I have an endpoint in Google appengine in java for letting user send me a message on my website.
The endpoint are generating with google SDK from a class like :
#Entity
public class Message {}
The message is persist with :
EntityManager mgr = getEntityManager();
mgr.persist(message);
How can i sanitize the string before persist it ?
I found this related post :Handling of HTML forms in App Engine (Java)
In advance thanks.
You can sanitize the text string using an existing library like Jsoup (#clean).
The choice of the specific tool depends on your requirements, but writing your own utility to sanitize text is not that simple unless you allow no tags at all.
Related
I am working on a springboot project and I am a total newbie in this. We are told to complete the project within a given time period and the deadline is in 3 days. I have a string which will contain the username. I am said that there will be an external database from where we have to fetch the data of that user and return that to the application. We are working on a web api.
Till now I have somehow extracted the username from the encoded data but now I am unable to proceed further. All the resources available online are related to building a repository and their own data and use that in the program but I have to use it from an external database. I don't know anything about this and is completely stuck.
The external database is a sample and includes an id , username and data. From the username we have to search the database and return all the three details as a JSON format of that user.
Well that was simple in SQL but I don't know how that can be performed from the point where I am now.
Thank You.
There is a special file called application.properties in Spring Boot, where you can define your authorization data to get connection with your remote database.
Usually, you should specify basic data:
spring.datasource.url=jdbc:mysql://url-to-your-external-db/name-of-db
spring.datasource.username=your_username
spring.datasource.password=your_pasword
After that, you could retrieve your data from database using JpaRepository for example. There is plenty of frameworks that will serialize/deserialize your Java objects/entities to JSON (Jackson for example).
Example of fetching users from a database using JpaRepository:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByFirstName(String firstName)
}
where User could be your POJO which represents a table with users in database.
Can you recommend on a framework which enable querying of data via web?
Requirements:
ORM capabilities - I want that the representation of the model at the server & client will not be dependent.
For example: let's say that the server will return to the client layer the following model: transaction (firstName, lastName, description, amount). While in the dal-layer it's being saved like this: Customer(Id, fName, lName, address) , Transaction(id, CustomerId, description, amount)
Option to write my own query provider (For example: HiveQL, SQL & etc).
I have tried to use the following frameworks (but it's seems like it, that the first demand is not supported):
JayData: http://jaydata.org/
breezejs: http://www.breezejs.com/
Thanks in advance.
Breeze does provide this but you will need to write the server side code that translates an OData query into a query that your chosen server implements. We already provide several implementations of this code for different server/database technologies and plan on doing more in the future.
To date we have done this for .NET servers with both Entity Framework and NHibernate ORM's and against Node servers with MongoDB backends. We also have other developers working on a Ruby server implementation. If you want to write your own, you should probably take a look at the Breeeze/MongoDB source to see how this is done.
Alternately, if your chosen server tech already has an OData provider, then Breeze can talk to it.
OData does provide a way to query database via web, such as
GET http://myservice/Products?$filter=Id gt 3 and contains(Name,'abc')
GET http://myservice/Products?$select=Id,Name,Provider&$orderby=ManufactureDate desc
Here are some odata samples https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/. In a controller, you can use what ever framework/provider you like to retrieve data from persistence.
If you want to use Entity Framework please follow this one:https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataActionsSample/.
I've followed through this sample code and tried to implement it with only simple JPA. However, when I tried to sign up with a Google account or login with an existing user account, it gave me this error.
[RuntimeException: No EntityManager bound to this thread. Try to annotate your action method with #play.db.jpa.Transactional]
private static List<User> getAuthUserFind(final AuthUserIdentity identity)
{
-> List<User> query = JPA.em().createQuery(
After googling for a while, many solutions suggest adding the #Transactional annotation to the calling play action, but that action is in the play-authenticate code.
Is there a solution for this issue, or do I have to use it with Ebeans?
I am using Play Framework 2.2.1 and implementing my program in Java.
It's not necessary to use Ebean,
I have used mybatis as persistence provider, but in order to save the user and login without problem you should use the same hashing algorithm.
the hashing algorithm is used to store the password.
to use your custom persistence provider like JPA or whatever you want, you should implement the Authentication Provider interfaces, see UsernamePasswordAuthProvider in the example project for more details.
Focus ,especially, on "signupUser" and "loginUser" methods.
I have modified play-authenticate to support Login/password instead of email/password identityId.
see Modified version of Play-Authenticate.
Cheers.
You could use JPA.withTransaction(callback). This is the better way when you can't put #Transactional in a method or you don't want to.
Cheers,
Alberto
To upload data to the datastore I use this java code :
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Entity entity = new Entity("mydetail");
entity.setProperty("entry", "entry");
ds.put(entity);
For uploading form based data is this the correct method of uploading data, ie using similar code above or is there another API I should be using ?
Yes, this the direct API to the AppEngine Datastore.
You can also use JDO interface which allows for directly storing a Java object without dealing with the Datastore API:
import javax.jdo.annotations.Persistent;
#PersistenceCapable
public class MyDetail {
// ...
#Persistent
private String entry;
// ...
There is also the JPA interface. Both of the interfaces are described on the App Engine website.
The Objectify interface is very easy and for many situations easier. It is not part of the official SDK.
You can use whichever makes more sense for you application.
This might seem like an odd question, but I am trying to get a handle on what the "best practice" is for converting an application that is set up to use something like Roo's or Grails' generation of controllers (which provides basic CRUD functionality) to something that returns a JSON response body instead for use in a JavaScript application.
The ambiguity of technology here is because I haven't actually started the project yet. I am still trying to decide which (Java-based) technology to use, and to see what kind of productivity tools I should learn/use in the process. It will be a web application, and it will use a database persistence layer. All other details are up in the air.
Perhaps the easiest way to accomplish my goal is to develop using some sort of AJAX plugin to start with, but most of the tutorials and descriptions out there say to start with a normal MVC architecture. Roo seems to make conversion of the controllers it generates to JSON-friendly return types difficult, and I'm not familiar enough with Groovy/Grails to know what it takes to do that.
This is mostly a learning experience for me, and I am open to any criticism or advice, but being a Q/A forum, I realize I need to incorporate an objective question of some sort. To fill that need, I ask:
What is the best way to set up an AJAX/RESTful interface for my entities in Roo and/or Grails?
I recently did exactly this with a Grails application and found it surprisingly easy to take the generated controllers and get them to output JSON or XML or the HTML from the view depending on the content negotiation.
The places in the Grails manual to look into are the section(s) on Content Negotiation and, if you need to deal with JSON or XML input, marshaling.
To get JSON and XML output, in the default list() method, changed it to this (I have a Session object, in this case...one of my domain classes):
def list() {
params.max = Math.min(params.max ? params.int('max') : 10, 100)
def response = [sessionInstanceList: Session.list(params), sessionInstanceTotal: Session.count()]
withFormat {
html response
json {render response as JSON}
xml {render response as XML}
}
}
Anywhere you are returning just an object by default, you will want to replace the returned value with the withFormat block.
You also may need to update your Config.groovy file where it deals with mime types. Here's what I have:
grails.mime.file.extensions = true // enables the parsing of file extensions from URLs into the request format
grails.mime.use.accept.header = true
grails.mime.types = [ html: ['text/html','application/xhtml+xml'],
xml: ['text/xml', 'application/xml'],
text: 'text/plain',
js: 'text/javascript',
rss: 'application/rss+xml',
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
all: '*/*',
json: ['application/json','text/json'],
form: 'application/x-www-form-urlencoded',
multipartForm: 'multipart/form-data'
]
As input (to an update() or save() action, for example) JSON and XML payloads will automatically be unmarshaled and will be bound just like a form input would be, but I've found that the unmarshaling process is a bit picky (especially with JSON).
I found that, in order for JSON to be handled correctly in the update() method, the class attribute had to be present and correct on the inbound JSON object. Since the library I was using in my client application didn't make this an easy issue to deal with, I switched to using XML instead.