hi i have requirement to capture the data for validations. i am able to fetch the data using RPCRequest and RPCManager by using setActionUrl to the controller class.from there creating the service class and dao classes .i am able to fetch the data into controller class.but i am unable get the data back into my grid.i want the data to be fetched into a variable.i am not using asynchronus service.i used async method in grid i am able to fetch into onSuccess() method.but without using how i can fetch.the data into grid.
with regards
subodh
Here example in our ServiceImpl class to retrive datas from DB
public final String getDatas(final HashMap<String, String> param) {
List<ShippingBean> result = null;
JSONObject obj = new JSONObject();
try {
// retrieve data from DB
data = dao.selectAll();
}
catch (BusinessException e) {
throw new InvocationException("BusinessException occurs ...", e);
}
obj = JSONObject.fromObject(result);
return obj.toString();
}
We use net.sf.json to serialize as DOM and return this to presenter call as AsyncCallBack method. And then , retrieve data as like that..
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("Error!");
}
public void onSuccess(final String result) {
HTML html = new HTML(result.replace(" ", "-"));
JSONValue value = JSONParser.parseLenient(html.getText());
JSONWrapper json = new JSONWrapper(value);
System.out.println(json.get(0).get("variableName").stringValue());
}
};
I have done something similar within a project with retrieve data and posting it to GWT from database. My database setup was Microsoft SQL 2012 and Hibernate framework to retrieve it. However I created a custom try/catch block and if/else bocks for validation on client side.
I used this tutorial from Hibernate to GWT to set up the transactions between the web application and the database for both saving and retrieving. Their source code provides the web page modules for setting up the displaying which I mimicked to fit to my needs since I was not storing "records" or "users".
GWT does have a validation setup but I spent a 10 hours trying to figure out the client side validation and gave up for something much simpler such as try/catch on the data being submitted since I had no concern for the format of the numbers.
Google "GWT Validation" and you should have some documentation about it but their isn't that much to choose from since everything seems to be a copy of Google's documentation.
Link - Hibernate to GWT
Hope this helps or points you in the right direction towards your answer.
Related
Is there any way in Kentico to have a user submit a form and then email the response but not actually save the answer to the related table?
As mentioned the emails from Kentico rely on the record being written to the DB before they trigger. Furthermore (unless I'm just unlucky) the only values you have access to are those stored in the table. I had thought that maybe you could mark the offending fields as Field without database representation, but sadly, the fields you may want will all be null - so best not to go down that route.
I took a slightly different approach to #trevor-j-fayas in that I used the BizFormItemEvents.Insert.Before event so that there is no trace of any log. It's a short hop from there to make use of an email template to make things look good. So my code looked as follows:
using CMS;
using CMS.DataEngine;
using CMS.EmailEngine;
using System;
[assembly: RegisterModule(typeof(FormGlobalEvents))]
public class FormGlobalEvents : Module
{
public FormGlobalEvents() : base("FormGlobalEvents")
{
}
protected override void OnInit()
{
CMS.OnlineForms.BizFormItemEvents.Insert.Before += Insert_Before;
}
private void Insert_Before(object sender, CMS.OnlineForms.BizFormItemEventArgs e)
{
var email = new EmailMessage();
email.From = e.Item.GetStringValue("ContactEmail", "null#foo.com");
email.Recipients = "no-reply#foo.com";
email.Subject = "Test from event handler (before save)";
email.PlainTextBody = "test" + DateTime.Now.ToLongTimeString();
EmailSender.SendEmail(email);
e.Cancel();
}
}
To me, it seems cleaner to not insert the record in the first place than delete it, but obviously that autoresponder etc. will only kick in automatically if you do save the record, so the choice is yours and ultimately depends on your preference.
Well, there's a couple different options, but the easiest is to simply delete the record after it's inserted. Use the Global Event Hooks to capture the BizFormItemEvent insert after, if it's your form, then delete it. Below is for Kentico 10:
using CMS;
using CMS.DataEngine;
using CMS.Forums;
using CMS.Helpers;
using CMS.IO;
using System.Net;
using System.Web;
// Registers the custom module into the system
[assembly: RegisterModule(typeof(CustomLoaderModule))]
public class CustomLoaderModule : Module
{
// Module class constructor, the system registers the module under the name "CustomForums"
public CustomLoaderModule()
: base("CustomLoaderModule")
{
}
// Contains initialization code that is executed when the application starts
protected override void OnInit()
{
base.OnInit();
CMS.OnlineForms.BizFormItemEvents.Insert.After += BizFormItem_Insert_After;
}
private void BizFormItem_Insert_After(object sender, CMS.OnlineForms.BizFormItemEventArgs e)
{
switch(e.Item.BizFormInfo.FormName)
{
case "YourFormNameHere":
e.Item.Delete();
break;
}
}
}
The other option would be to clone and modify the Online Form Web part to take the information, manually call the email and cancel the insert, but that's a lot of work when this is quicker.
Yes and no. The record is stored before the email notifications and autoresponders are sent out. Your best bet for this is to create a custom global event handler for the form submission(s) using the BizFormItemEvents.Insert.Before. This will call the event before the actual record is stored in the database. You can then cancel out of the event (which will not store the record) and send your email manually.
Handling global events
BizFormItemEvents Events
I am new to couchdb and I want to learn about how to connect the couchdb in our gwt server side program. till now, I tried to work on its gui to create database add documents and add fields to it.but i am not able to use it in program. what exactly the way to do it..
I tried some code but didn't got it.
In your GWT you should have something like this in your server. Besides it you should have your DAO for your Entities (erktorp takes place here) and your mechanism for connecting GWT's client with the server (for example RequestFactory).
//Object of your own related with couch db management
CouchDbAccess couchDbAccess = null;
#Inject
public CouchDbManagement(String ddbbUrl, String ddbbName) throws IOException {
HttpClient httpClient;
Builder b;
try {
b = new StdHttpClient.Builder().url(ddbbUrl);
} catch (Exception e) {
e.printStackTrace();
ddbbUrl = "http://admin:sa#localhost:5984";
b = new StdHttpClient.Builder();
}
b.socketTimeout(60000);
String user = getUserFrom(ddbbUrl);
String pass = getPassFrom(ddbbUrl);
b.username(user).password(pass);
httpClient = b.build();
CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
if (initialize && dbInstance.getAllDatabases().contains(ddbbName)) {
dbInstance.deleteDatabase(ddbbName);
dbInstance = new StdCouchDbInstance(httpClient);
}
//If you want Lucene, here is the place
db.createDatabaseIfNotExists();
new IndexUploader().updateSearchFunctionIfNecessary(db, ...);
new IndexUploader().updateSearchFunctionIfNecessary(db, ...);
URI dbURI = URI.prototype(DbPath.fromString(ddbbName).getPath());
RestTemplate restTemplate = new RestTemplate(dbInstance.getConnection());
couchDbAccess = new CouchDbAccess(db, dbURI, restTemplate);
}
Couchdb has a restful interface to it's api. Everything is available via url's like
http://localhost:5984/db_name/doc_name
In fact the entire http api is documented in the wiki. Now I am not familiar with gwt but every framework has http libraries and you can use those libraries to make calls to couchdb http endpoints.
A quick google search gave me this resource which may guide you on how to create http requests through gwt.
I am using Jena API to get RDF data from Allegrograph Server. I have written a REST webservice using Jersey jar to get this data.
My java code for the webservice is as shown below:
#GET
#Path("/JENA")
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String getData() throws RepositoryException {
AGGraphMaker maker = new AGGraphMaker(conn);
AGGraph graph = maker.getGraph();
AGModel model = new AGModel(graph);
AGQuery agQuery = AGQueryFactory.create(query);
QueryExecution qe = AGQueryExecutionFactory.create(agQuery, model);
String result = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
ResultSet rs = qe.execSelect();
While(rs.hasNext()){
byteArrayOutputStream = new ByteArrayOutputStream();
if("JSON".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsJSON(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
System.out.println("Result is "+result);
} else if("XML".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsXML(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
}else if("CSV".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsCSV(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
I get no results for the SPARQL query when I deploy this web service on Tomcat server and test it using REST client app on Chrome and firefox.
But the same code(absolutely no difference in webservice code and this main method code) if I write in a plain java class and run its main method, i am getting 36 results. I am not sure what the issue is.
Please help me in this regard.
You need to separate the concerns:
Move the service logic - the bit that actually queries Allegro graph - to a separate class so that it's properly encapsulated. The API for the class should reflect its responsibilities in your application, not the way that it happens to be working at the moment.
Write JUnit tests for the service class. This is important - it gives you confidence that your service is performing its job correctly, and keeps on doing so as you develop your application.
Write your Jersey method to invoke any service object that conforms to the API of your service class.
Write one or more HTTPUnit (or similar) tests to invoke your REST API. Ideally, you'll use a mock or test double instead of the actual service. What you want to test is whether the HTTP request reaches the right method, and that method delegates to the service object with the right arguments. You're then testing (and debugging!) a smaller number of concerns.
It's much better to work with small units of functionality with a clear idea of what their responsibilities are. And you should definitely learn to work with tests - it's a big win in the medium term, even if it means a bit more learning up front!
I am building a SOAP webservice. I am using JAX-WS to create this service and deploying it on a Glassfish 3.1.2 server.
I have no problem having this service return a String build with the XML representation of what I want. I can also get it to return a specific object. What I am having issues with is streaming this resource.
This is what I have so far :
Interface :
#MTOM
#WebService
#XmlRootElement(name="root.element.class.location")
#SOAPBinding(style = Style.RPC, use=Use.LITERAL)
public interface ResultsServer {
#WebMethod
#XmlMimeType("text/xml")
public Test getResultDataAsXML(#WebParam(name="Id") Integer id) throws Exception;
}
Implementation :
---- Edit ----
This is where I would like to stream my resource. Let's say I need my results object becomes extremely large, I don't want to hold this is memory and would like to start sending it without holding it. (commented this in code)
#WebService(endpointInterface = "my.endpoint.class")
#StreamingAttachment(parseEagerly=true, memoryThreshold=4000000L)
public class ResultsServerImpl implements ResultsServer {
#Override
public Test getResultDataAsXML(Integer id) throws Exception {
Test results = new Test();
for(int i=0; i<[very large number]; i++) {
results.getResults().add("here : " + i);
/**at one point, this is too large to hold in memory
I would like to be able to start returning the object here
so it is not taking up all available memory */
}
return results; //or close the stream
}
}
---- End Edit ----
And my Test class is a simple class looking like this :
public class Test {
private ArrayList<String> results;
public Test() {
results = new ArrayList<String>();
}
public ArrayList<String> getResults() {
return results;
}
public void setResults(ArrayList<String> results) {
this.results = results;
}
}
Let's assume that this Test object becomes very big (and more complexe). I need to be able to stream this object. How would I go to proceed in streaming this.
Ideally, I would like to keep the structure of this object.
From what I have read so far, I would need to convert this object in some sort of DataHandler and return this object.
Any help is welcome! Thank you.
The JAX-WS implementation will leverage a JAXB implementation to marshal the object (most likely to a StAX XMLStreamWriter) so the output will be streamed (there won't be an XML document created in memory).
#BlaiseDoughan I think you've worded this the way I was looking for.
Yes that would be to prevent the instance of Test of fully being saved
in memory. Is there a way to do this?
If you want the data to appear in the messages as XML (as opposed to a SOAP attachment), the you could leverage JAXB's marshal events. In the beforeMarshal event you could load data into an object and then clear it in the afterUnmarshal method. Ultimately all the data will be pulled in, but it won't all be referenced at the same time.
http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.html#unmarshalEventCallback
I would recommend using the xstream (http://x-stream.github.io/) library from thoughtworks for your streaming as it is bindable on both sides of your service and is compatible with SOAP envelops. In fact there is even an integration with ActiveSOAP.
An example of a SOAP envelope wrapped xstream object can be seen at http://jira.codehaus.org/secure/attachment/19097/SoapEnvelopeTestCase.java. A full usage from jboss can be seen at https://issues.jboss.org/secure/attachment/12325534/SOAPClient.java?_sscc=t.
XStream has been used for some very large streaming processes (I've used it for some large 100+ MB text objects without issue).
I want to use IoC / the dependency resolver of the web api framework for decoupling.
The XmlFormatter cant serialize interfaces,... Ok. But what would be the purpose of IoC and the DependencyResolver if I cant return xml?
I cant even do this:
(Method in my ApiController)
public HttpResponseMessage Get()
{
IEnumerable<Project> projects = new List<IProject>() { new Project(), new Project() }.Select(p => p as Project);
HttpResponseMessage response = Request.CreateResponse<IEnumerable<Project>>(HttpStatusCode.OK, projects);
return response;
}
I create a list of IProjects and cast them to 'Project'. But while creating the response I get this:
The configured formatter
'System.Web.Http.Tracing.Tracers.XmlMediaTypeFormatterTracer' cannot
write an object of type 'WhereSelectListIterator`2'.
That is a XmlMediaTypeFormatterTracer? I dont want tracing that throws errors while serialization. (BTW: I replaced the standard XMLformatter with my own one. However "XmlMediaTypeFormatterTracer" throws the exception...
Info: I get the same error while using the standard formatter)
Why is this XmlMediaTypeFormatterTracer called even if I implement my own xmlformatter?
my problem solved with
config.Formatters.XmlFormatter.UseXmlSerializer = false;
Have you enabled Tracing in your application? If yes, the Tracing logic wraps formatters into its a wrapper tracer formatters.