I made a download page in Wicket. As you can see, it's a DataView where you can download a file, depending on the id column and the DropDownChoice 'version'.
So clicking 'Download' on id 160 with version 3 should download file160ver3.txt, while on id 159 with version 2 it should download file159ver2.txt. Unfortunately updating the DropDownChoice doesn't get reflected in the model. So clicking on the Download button always downloads the file in the same version. As I have defaulted to Version 2 in my DropDownChoice, it always downloads this version.
Here's my code:
DropDownChoice<Integer> choice = new DropDownChoice<>("version", new Model<Integer>(2), List.of(1, 2, 3));
choice.add(new AjaxEventBehavior("change") {
#Override
protected void onEvent(AjaxRequestTarget target) {
target.add();
System.out.println(choice.getModelObject()); // doesn't change
}
});
item.add(choice);
// The value of choice.getModelObject() doesn't change
DownloadLink download = new DownloadLink("download", getFile(p.getId(), choice.getModelObject()));
download.setOutputMarkupId(true);
item.add(download);
What is it that I'm missing? How do I update the DropDownChoice?
Update and solution (changed according to Svens suggestion):
choice.add(new AjaxFormComponentUpdatingBehavior("change") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
System.out.println(choice.getModelObject());
}
});
item.add(choice);
DownloadLink download = new DownloadLink("download", () -> {
return getFile(p.getId(), choice.getModelObject());
});
// ...
private File getFile(int id, DropDownChoice<Integer> choice) throws FileNotFoundException, IOException {
Integer version = choice.getModelObject();
Thanks.
...
And here's the complete code (Java and HTML below):
public DownloadPage(PageParameters params) {
List<PrefKey> prefKeys = db.getPrefKeys();
DataView<PrefKey> dataView = getDataView(prefKeys);
Form<Void> form = new Form<>("form");
add(form);
form.add(dataView);
}
private DataView<PrefKey> getDataView(List<PrefKey> prefKeys) {
IDataProvider<PrefKey> provider = new ListDataProvider<>(prefKeys);
DataView<PrefKey> dataView = new DataView<>("dbAsDataView", provider, 10) {
private static final long serialVersionUID = 12345L;
#Override
protected void populateItem(Item<PrefKey> item) {
PrefKey p = item.getModelObject();
item.add(new Label("tdId", p.getId()));
item.add(new Label("tdKey", p.getKey()));
try {
DropDownChoice<Integer> choice = new DropDownChoice<>("version", new Model<Integer>(2), List.of(1, 2, 3));
choice.add(new AjaxEventBehavior("change") {
#Override
protected void onEvent(AjaxRequestTarget target) {
target.add();
System.out.println(choice.getModelObject()); // doesn't change
}
});
item.add(choice);
DownloadLink download;
// The value of choice.getModelObject() doesn't change
download = new DownloadLink("download", getFile(p.getId(), choice.getModelObject()));
download.setOutputMarkupId(true);
item.add(download);
} catch (IOException e) {
e.printStackTrace();
}
}
};
return dataView;
}
<h1>Wicket Download</h1>
<form wicket:id="form" action="">
<table id="tblDataView" class="table table-striped table-hover">
<thead>
<tr>
<th>Id</th>
<th>Key</th>
<th>Version</th>
<th>Download</th>
</tr>
</thead>
<tbody>
<tr wicket:id="dbAsDataView">
<td wicket:id="tdId"></td>
<td wicket:id="tdKey"></td>
<td><select wicket:id="version"></select></td>
<td><input type="button" wicket:id="download" value="Download"></input></td>
</tr>
</tbody>
</table>
</form>
You have to use a AjaxFormComponentUpdatingBehavior to transfer the newly selected item to the Java component (and its model):
choice.add(new AjaxFormComponentUpdatingBehavior("change") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
}
});
https://ci.apache.org/projects/wicket/guide/8.x/single.html#_ajaxformcomponentupdatingbehavior
And then your downloadLink has dynamically adjust to the current selection too:
download = new DownloadLink("download", () -> {
return getFile(p.getId(), choice.getModelObject()
});
Related
I tried to send HTML form data to a Java Vertx Verticle but I get null as value.
Here is my code:
public void start(Future<Void> startFuture) throws Exception {
Router router = Router.router(vertx);
router.route("/html/*").handler(StaticHandler.create().setWebRoot("html/"));
router.route("/html/*").handler(StaticHandler.create().setWebRoot("web/html"));
router.route("/js/*").handler(StaticHandler.create().setWebRoot("web/js"));
router.route("/css/*").handler(StaticHandler.create().setWebRoot("web/css"));
router.route("/fonts/*").handler(StaticHandler.create().setWebRoot("web/fonts"));
Route route = router.route(HttpMethod.POST, "/crypt/testForm/");
route.handler(routingContext -> {
String productType = routingContext.request().getParam("test");
System.out.println(productType);
});
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(8085, "localhost", res -> {
if (res.succeeded()) {
startFuture.complete();
} else {
startFuture.fail(res.cause());
}
});
}
And for my html file:
<form action="/crypt/testForm" method="post">
<input type ="text" id="test" name ="test"/>
<input type="submit"/>
</form>
Regards.
Here is my solution, maybe it help,
public void start() throws Exception {
Router router = Router.router(vertx);
router.route("/html/*").handler(StaticHandler.create().setWebRoot("html/"));
router.route("/html/*").handler(StaticHandler.create().setWebRoot("web/html"));
router.route("/js/*").handler(StaticHandler.create().setWebRoot("web/js"));
router.route("/css/*").handler(StaticHandler.create().setWebRoot("web/css"));
router.route("/fonts/*").handler(StaticHandler.create().setWebRoot("web/fonts"));
router.route("/crypt/test").handler(BodyHandler.create());
router.post("/crypt/test").handler(ctx -> {
ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
JsonArray js = new JsonArray();
js.add(1);
js.add(5);
js.add(3);
ctx.response().end(js.toString());
});
vertx.createHttpServer().requestHandler(router::accept).listen(8085);
}
Sorry for my too long question. I am totally a newbie on GWT and I have still less experiences.I would like to create simple chat application using GWT.
I found for a link simple java chat application using java+servlet+jsp from this. I refrenced it and converted to GWT compactable codes. (I deployed it on http://gwt-chatting-test.appspot.com using GAE). I believe my codes may have plenty of weak points and security holes but I have less experience to handle them .(If you found , pls correct me kindfully).
I would like to describe full of my codes. I used servlet 2.4 , GWT 2.5 ,UI Binder and other required libs.
1) . For Login page
Index.ui.xml
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:d="urn:import:com.google.gwt.dom.client">
<ui:style>
.important {
font-weight: bold;
}
.lblUserName {
margin-right: 3px;
}
</ui:style>
<g:HTMLPanel>
<center>
<g:HorizontalPanel>
<g:Label ui:field="lblUserName" text="User Name : " styleName="{style.lblUserName}"/><g:TextBox height="15px" ui:field="txtUserName"/>
<g:Button styleName="{style.important}" text="Login" ui:field="btnLogin" />
</g:HorizontalPanel>
</center>
</g:HTMLPanel>
Index.java
public class Index extends Composite {
interface IndexUiBinder extends UiBinder<Widget, Index> {}
private static IndexUiBinder uiBinder = GWT.create(IndexUiBinder.class);
#UiField Button btnLogin;
#UiField TextBox txtUserName;
private ChatServiceAsync chatService = GWT.create(ChatService.class);
public Index() {
initWidget(uiBinder.createAndBindUi(this));
}
#UiHandler("btnLogin")
void onClick(ClickEvent e) {
login();
}
#UiHandler("txtUserName")
void onKeyDown(KeyDownEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
if (txtUserName.getText().trim().length() == 0) {
Window.alert("Enter your name for chat-room !");
}
else {
login();
}
}
}
private void login() {
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
RootPanel.get().clear();
RootPanel.get().add(new Chat());
}
#Override
public void onFailure(Throwable caught) {
System.err.println(caught.getMessage());
}
};
chatService.login(txtUserName.getText(), callback);
}
}
2) . For Chatting Page
Chat.ui.xml
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<ui:style>
.main {
height: 420px;
border: 1px solid silver;
padding: 2px;
width: 620px;
margin-bottom: 5px;
}
.txtInputMsg {
margin-right: 3px;
width : 560px;
height :25px;
}
</ui:style>
<g:HTMLPanel>
<center>
<g:VerticalPanel>
<g:ScrollPanel styleName="{style.main}" height="420px" width="620px" ui:field="pnlMain">
<g:VerticalPanel ui:field="pnlMessage"/>
</g:ScrollPanel>
<g:HorizontalPanel ><g:TextBox styleName="{style.txtInputMsg}" ui:field="txtInputMsg"/><g:Button ui:field="btnLogout" text="Logout"/></g:HorizontalPanel>
</g:VerticalPanel>
</center>
</g:HTMLPanel>
Chat.java
public class Chat extends Composite {
public interface MessageTemlate extends SafeHtmlTemplates {
#Template("<div class =\"{2}\"><div class = \"msgTitle\"> {0}</div><div class=\"msgDescription\">{1}</div></div>")
SafeHtml getFormattedMessage(String name, SafeHtml message, String backgroundColor);
#Template("<div class =\"loginInform\"><span class=\"userName\">{0}</span> has been joined to this conversation !</div>")
SafeHtml notifyLoginUser(String userName);
#Template("<div class =\"logoutInform\"><span class=\"userName\">{0}</span> has been left from this conversation !</div>")
SafeHtml notifyLogoutUser(String userName);
}
private static ChatUiBinder uiBinder = GWT.create(ChatUiBinder.class);
#UiField TextBox txtInputMsg;
#UiField ScrollPanel pnlMain;
#UiField VerticalPanel pnlMessage;
#UiField Button btnLogout;
private static final XMLHttpRequest request = XMLHttpRequest.create();
private static final MessageTemlate TEMPLATES = GWT.create(MessageTemlate.class);
private ChatServiceAsync chatService = GWT.create(ChatService.class);
private String loginUser;
private Timer timer;
interface ChatUiBinder extends UiBinder<Widget, Chat> {}
public Chat() {
initWidget(uiBinder.createAndBindUi(this));
pnlMessage.getElement().setAttribute("style", "width:100%");
initLoginUserName();
request.open("post", URL.encode(GWT.getModuleBaseURL()
+ "chat.do?action=login&time='" + new Date().getTime() + ""));
request.send(null);
}
#UiHandler("txtInputMsg")
void sendMessage(KeyDownEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
if (txtInputMsg.getText().trim().length() > 0) {
SafeHtml message = SafeHtmlUtils.fromTrustedString(txtInputMsg.getText());
request.open("post", URL.encode(GWT.getModuleBaseURL()
+ "chat.do?action=send&msg=" + message.asString() + "&time='" + new Date().getTime() + ""));
txtInputMsg.setText("");
pnlMessage.add(new HTML(TEMPLATES.getFormattedMessage(loginUser, message, "myMessage")));
pnlMain.scrollToBottom();
txtInputMsg.setFocus(true);
request.send(null);
}
}
}
#UiHandler("btnLogout")
void logout(ClickEvent e) {
boolean confirm = Window.confirm("Are you sure you want to logout now ?");
if (confirm) {
timer.cancel();
request.open("post", URL.encode(GWT.getModuleBaseURL()
+ "chat.do?action=logout&time='" + new Date().getTime() + ""));
request.send(null);
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
RootPanel.get().clear();
RootPanel.get().add(new Index());
}
#Override
public void onFailure(Throwable caught) {
System.err.println(caught.getMessage());
}
};
chatService.logOut(loginUser, callback);
}
}
private void initChatListener() {
timer = new Timer() {
#Override
public void run() {
request.open("post", URL.encode(GWT.getModuleBaseURL()
+ "chat.do?action=get&time='"
+ new Date().getTime() + ""));
request.send(null);
request.setOnReadyStateChange(new ReadyStateChangeHandler() {
#Override
public void onReadyStateChange(XMLHttpRequest xhr) {
if (xhr.getReadyState() == 4) {
if (xhr.getStatus() == 200 && xhr.getResponseText().trim().length() > 1) {
HTML html = new HTML(xhr.getResponseText().trim());
JSONValue value = JSONParser.parseLenient(html.getText());
JSONWrapper json = new JSONWrapper(value);
for (int i = 0; i < json.getValue().isArray().size(); i++) {
String[] chatData = json.get(i).getValue().toString()
.replaceAll("\"", "").split(":");
if (chatData.length >= 3) {
if (chatData[2].equals("login")) {
pnlMessage.add(new HTML(TEMPLATES.notifyLoginUser(chatData[0])));
}
else {
pnlMessage.add(new HTML(TEMPLATES.notifyLogoutUser(chatData[0])));
}
}
else {
pnlMessage.add(new HTML(TEMPLATES.getFormattedMessage(chatData[0],
SafeHtmlUtils.fromTrustedString(chatData[1]), "receivedMessage")
.asString()));
}
pnlMain.scrollToBottom();
}
}
}
}
});
}
};
timer.scheduleRepeating(1000);
}
private void initLoginUserName() {
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
loginUser = result;
if (loginUser == null) {
Window.alert("You need to login !");
RootPanel.get().clear();
RootPanel.get().add(new Index());
}
else {
initChatListener();
}
}
#Override
public void onFailure(Throwable caught) {
System.err.println(caught.getMessage());
}
};
chatService.getUsername(callback);
}
}
3) . Service and ServiceAsync for RPC
ChatService.java
#RemoteServiceRelativePath("chatService")
public interface ChatService extends RemoteService {
String login(String userName);
String getUsername();
String logOut(String username);
}
ChatServiceAsync.java
public interface ChatServiceAsync {
void login(String userName, AsyncCallback<String> callback);
void getUsername(AsyncCallback<String> callback);
void logOut(String username, AsyncCallback<String> callback);
}
4) . Server side control
ChatServiceImpl.java
#SuppressWarnings("serial")
public class ChatServiceImpl extends RemoteServiceServlet implements ChatService {
public String login(final String userName) {
String newUserName = userName;
HttpSession httpSession = getThreadLocalRequest().getSession();
Map<String, List<String>> chat = ChatSupport.getChattingUsers();
synchronized (chat) {
// prevent userName conflict
int i = 1;
while (chat.containsKey(newUserName)) {
++i;
newUserName = userName + "(" + i + ")";
}
chat.put(newUserName, new ArrayList<String>());
}
httpSession.setAttribute("UID", newUserName);
return "LOGIN_SUCCESS";
}
public String logOut(String username) {
// remove the mapping of user name
ChatSupport.getChattingUsers().remove(username);
getThreadLocalRequest().getSession().invalidate();
return "LOGOUT_SUCCESS";
}
public String getUsername() {
// check if there is a HTTP session setup.
HttpSession httpSession = getThreadLocalRequest().getSession(false);
if (httpSession == null) {
return null;
}
// return the user name
return (String) httpSession.getAttribute("UID");
}
}
ChatSupport.java
#SuppressWarnings("serial")
public class ChatSupport extends HttpServlet {
// message map, mapping user UID with a message list
private static Map<String, List<String>> users = new HashMap<String, List<String>>();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String action = req.getParameter("action");
if ("login".equals(action)) {
String userName = (String) req.getSession().getAttribute("UID");
for (String key : users.keySet()) {
if (!key.equals(userName)) {
synchronized (users.get(key)) {
users.get(key).add(userName + "::login");
}
}
}
}
else if ("logout".equals(action)) {
String userName = (String) req.getSession().getAttribute("UID");
for (String key : users.keySet()) {
if (!key.equals(userName)) {
synchronized (users.get(key)) {
users.get(key).add(userName + "::logout");
}
}
}
}
// send message
else if ("send".equals(action)) {
// get param with UTF-8 enconding
String msg = new String(req.getParameter("msg").getBytes("ISO-8859-1"), "UTF-8");
String userName = (String) req.getSession().getAttribute("UID");
for (String key : users.keySet()) {
if (!key.equals(userName)) {
synchronized (users.get(key)) {
// put message to any other user's msg list
users.get(key).add(userName + ":" + msg);
}
}
}
}
else if ("get".equals(action)) { // get message
String userName = (String) req.getSession().getAttribute("UID");
if (userName == null) resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
List<String> messages = users.get(userName);
synchronized (messages) {
if (messages.size() > 0) {
// for UTF-8 chars
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
JSONArray result = new JSONArray();
// add all msg to json array and clear list
while (messages.size() > 0) {
result.add(messages.remove(0));
}
out.println(result);
out.close();
}
}
}
}
public static Map<String, List<String>> getChattingUsers() {
return users;
}
}
5) . My gwt.xml
....
<module rename-to='testing'>
<inherits name='com.google.gwt.user.User'/>
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<inherits name="com.google.gwt.http.HTTP" />
<inherits name="com.google.gwt.json.JSON" />
<inherits name="com.pathf.gwt.util.json.jsonwrapper" />
<entry-point class='test.client.TestingEntry'/>
<source path='client'/><source path='shared'/>
</module>
6) . Servlet configurations at web.xml
<servlet>
<servlet-name>chatServlet</servlet-name>
<servlet-class>test.server.ChatServiceImpl</servlet-class>
</servlet>
<servlet>
<servlet-name>ChatServlet</servlet-name>
<servlet-class>test.server.ChatSupport</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ChatServlet</servlet-name>
<url-pattern>/testing/chat.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>chatServlet</servlet-name>
<url-pattern>/testing/chatService</url-pattern>
My program was run properly on multiple browsers but can't work on same broswer. I can't run this program by using same brower with multi-tabs. I think I am using same session and I need to create new session for every login. But I have no idea how to create it. From How to get multiple session in single browser , that may causes security problems and I shouldn't. But currently I forgot about securtiy issues.
So , How can I do for multiple-tab browser supports ?
UPDATED:
I'm using a Detailsview Insert Control and I am trying to create a new row in the database from a checkbox in a CheckBoxList. I'm getting the "The INSERT statement conflicted with the FOREIGN KEY constraint"
Here is my cs:
protected void AddPrincipleStaffDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
CheckBoxList PrincipleStaffTitle = (CheckBoxList)FindControl("PrincipleStaffTitle");
if (PrincipleStaffTitle != null)
{
foreach (ListItem item in PrincipleStaffTitle.Items)
{
if (item.Selected)
{
string stringSession = Session["ProductionID"].ToString();
int intProductionID = Int32.Parse(stringSession);
var ID = item.Value;
using (var context = new FactoryTheaterModelFirstContainer())
{
PrincipleStaff principlestaff = new PrincipleStaff();
principlestaff.PrincipleStaffTitle = ID;
principlestaff.Production_proProductionID = intProductionID;
context.PrincipleStaffs.Add(principlestaff);
context.SaveChanges();
}
}
}
}
here is the aspx:
<asp:EntityDataSource ID="PrincipleStaffSource" runat="server" ConnectionString="name=FactoryTheaterModelFirstContainer" DefaultContainerName="FactoryTheaterModelFirstContainer" EnableFlattening="False" EntitySetName="PrincipleStaffs" EntityTypeFilter="PrincipleStaff" EnableInsert="True"></asp:EntityDataSource>
<asp:DetailsView ID="AddPrincipleStaffDetailsView" runat="server" AutoGenerateRows="False" DataKeyNames="PrincipleStaffID" DataSourceID="PrincipleStaffSource" Height="50px" Width="730px" DefaultMode="Insert" OnItemInserting="AddPrincipleStaffDetailsView_ItemInserting" OnItemInserted="AddPrincipleStaffDetailsView_ItemInserted">
<Fields>
<asp:TemplateField HeaderText="Add Principle Staff Role:" SortExpression="PrincipleStaffTitle">
<InsertItemTemplate>
<asp:CheckBoxList ID="PrincipleStaffTitle" runat="server" SelectedValue='<%# Bind("PrincipleStaffTitle") %>'>
<asp:ListItem Value="Director">Director(s)</asp:ListItem>
<asp:ListItem Value="Assistant Director">Assistant Director(s)</asp:ListItem>
<asp:ListItem Value="Written By">Written By(s)</asp:ListItem>
<asp:ListItem Value="Executive Producer">Executive Producer(s)</asp:ListItem>
<asp:ListItem Value="Producer">Producer(s)</asp:ListItem>
<asp:ListItem Value="Techincal Director">Technical Director(s)</asp:ListItem>
</asp:CheckBoxList>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PrincipleStaffTitle") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
The Production.proProductionID is the foreign key that I'm trying to get into the PrincipleStaff Production_proProductionid column. I can't seem to create the FK relationship.
Thanks for any help that can be provided!
The Below code works. I've since moved my context.savechanges(); outside the loop. My issue was happening on my ItemInserted command.
protected void AddPrincipleStaffDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
CheckBoxList PrincipleStaffCheckBox = (CheckBoxList)AddPrincipleStaffDetailsView.FindControl("PrincipleStaffTitleCheckBoxList");
if (PrincipleStaffCheckBox.Items.Count > 0)
{
foreach (ListItem item in PrincipleStaffCheckBox.Items)
{
if (item.Selected)
{
string stringSession = Session["ProductionID"].ToString();
int intProductionID = 0;
intProductionID = Int32.Parse(stringSession);
var principlestafftitle = item.Value;
try
{
using (var context = new FactoryTheaterModelFirstContainer())
{
Production proid = context.Productions.Single(i => i.proProductionID == intProductionID);
PrincipleStaff principlestaff = new PrincipleStaff()
{
PrincipleStaffTitle = principlestafftitle,
Production_proProductionID = intProductionID
};
proid.PrincipleStaffs.Add(principlestaff);
context.SaveChanges();
}
}
catch (Exception f)
{
Console.WriteLine(f); // or log to file, etc.
throw; // re-throw the exception if you want it to continue up the stack
}
}
}
}
}
I got stuck with an issue in iOS application using PhoneGap framework. I have a web services URL. I need to get JSON response from the web services URL. I had build up some code, but it is not working.
Here is my code:
<div data-role="content" data-theme="a" style="background: Black">
<div data-theme="a">
<span style="font-size: x-large; color: Orange;">Secure Log In</span></div>
<div data-theme="a">
<div data-theme="a">
<input type="password" placeholder="PASSWORD" id="txtPassword" style="background-color: gray;" /></div>
<div data-theme="a" align="right">
<a href="#" data-role="button" onclick="callWebService()" data-corners="false"
data-theme="a" id="clcik" cursor="pointer" style="width: 150px; border-radius: 5px 5px 5px 5px"
data-clickload="show" data-transition="slidefade"><span style="color: Green">Log In</span>
</a>
</div>
function callWebService(){
var query = 'Ocean';
var url = 'http://66.171.142.16/Accountservice/Security/ValidateAccess?accesscode=abcd&type=1';
alert(url);
$.getJSON(url,function(response){
alert('Here!');
});
};
How can I get the JSON response from the url?
I used .Net web Service to access Web Service, Also I have created a Plugin to call .Net web Service. in Java script I used to call web service method as described below.
in script.js
$(".CategoryNavbar").click(function(e){
e.preventDefault();
window.plugins.webservice.GetFlights("service",function(r){printResult(r)},function(e){console.log(e)});
return false;
});
function printResult(fileInfo){
var innerHtmlText=getHtml(fileInfo);
$.mobile.changePage('#CategoryPage',{transition:'slide'});
$('#CategoryPageContent').html(innerHtmlText);
$("#CategoryList").listview();
$("#CategoryList").listview('refresh');
}
function getHtml(fileInfo){
var htmlText='<ul data-role="listview" id="CategoryList" data-theme="c" data-filter="true" data-filter-placeholder="Search">';
for(var index=0;index<fileInfo.Flights.length;index++){
htmlText=htmlText+'<li> '+ fileInfo.Flights[index] +'</li>';
}
htmlText=htmlText+"</ul>";
return htmlText;
}
in Plugin File
/**
* Constructor
*/
function WebService() {
}
/**
* #param methodn The method name for which we want the webService
* #param successCallback The callback which will be called when directory listing is successful
* #param failureCallback The callback which will be called when directory listing encouters an error
*/
WebService.prototype.GetFlights = function(args, successCallback,
failureCallback) {
return cordova.exec(successCallback, failureCallback, 'WebService',
'GetFlights', [ args ]);
};
if (!window.plugins) {
window.plugins = {};
}
if (!window.plugins.webservice) {
window.plugins.webservice = new WebService();
}
Hi Sudheer please check the below code to get the response from web service using Ksoap
public class AndroidWebService extends Activity {
private final String NAMESPACE = "http://www.webserviceX.NET/";
private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
private final String METHOD_NAME = "ConvertWeight";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String weight = "3700";
String fromUnit = "Grams";
String toUnit = "Kilograms";
PropertyInfo weightProp =new PropertyInfo();
weightProp.setName("Weight");
weightProp.setValue(weight);
weightProp.setType(double.class);
request.addProperty(weightProp);
PropertyInfo fromProp =new PropertyInfo();
fromProp.setName("FromUnit");
fromProp.setValue(fromUnit);
fromProp.setType(String.class);
request.addProperty(fromProp);
PropertyInfo toProp =new PropertyInfo();
toProp.setName("ToUnit");
toProp.setValue(toUnit);
toProp.setType(String.class);
request.addProperty(toProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
Log.i("myApp", response.toString());
TextView tv = new TextView(this);
tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here is an sample code for getting response using JSON in jquery mobile check the code below
$.ajax({
cache: false,
url: wcfServiceUrl + "Authenticate?CompanyID=" + escape(comp) + "&UserName=" + user + "&Password=" + escape(pass) + "&Auth=" + ipaddress+"",
data: "{}",
type: "GET",
contentType: "application/javascript",
dataType: "jsonp",
beforeSend: function (XMLHttpRequest) {
$.mobile.loadingMessageTextVisible = true;
$.mobile.loadingMessage = "Loading Please Wait";
$.mobile.showPageLoadingMsg();
},
complete: function (XMLHttpRequest, textStatus) {
$.mobile.hidePageLoadingMsg();
},
error: function (xmlHttpRequest, status, err) {
$.mobile.loadingMessageTextVisible = true;
$.mobile.loadingMessage = "Web service is not responding. Try again";
$.mobile.showPageLoadingMsg();
var wait = setTimeout(function(){
$.mobile.hidePageLoadingMsg();
},400);
},
error: function () {
jAlert("list failed!",alertmessage);
},
success: function (list) {
var rar = list.split(";");
if(rar[0]=="Error")
{
jAlert(rar[1],alertmessage);
}
else if(rar[0]=="Success")
{
localStorage.setItem( "CompanyID", comp);
localStorage.setItem( "Username", user);
localStorage.setItem( "UserID", rar[1]);
$.mobile.changePage( '#home', { transition: "pop", reverse: false } );
}
else if(rar[0]=="FirstLogin")
{
localStorage.setItem( "CompanyID", comp);
localStorage.setItem( "Username", user);
localStorage.setItem( "UserID", rar[1]);
$.mobile.changePage( '#change-pass', { transition: "slide", reverse: false } );
}
}
});
Is there anyway to have the autocomplete for a combo box to start from anywhere in the text, let me give you an example. If I have someone named john smith in the combobox if I start with the letter 'j' it pulls up john smith but less say I want to start with the letter 's' to search for his last name, is that possible, if so does anyone have code or a link to code that does this.
Have you looked at SuggestBox? The MultiWordSuggestOracle that feeds the data to the suggest box seems to do exactly what you want - see the javadocs for usage and examples.
Update: Here's a rather nice example of customizing GWT's SuggestBox to look like the one on Facebook: http://raibledesigns.com/rd/entry/creating_a_facebook_style_autocomplete Be sure to follow all the links in that tutorial, as they contain a lot of info about using the SuggestBox.
I been have any problems with AdvancedComboBoxExample sencha
http://www.sencha.com/examples/#ExamplePlace:advancedcombobox
I found in this link http://www.sencha.com/forum/showthread.php?222543-CRTL-C-triggers-a-reload-of-data-in-Combobox the response for my problem.
I had to make some adjustments to my code. Below is the code for those who need it.
ComboBox ajax without paging:
import com.extjs.gxt.ui.client.data.*;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.List;
import java.util.Map;
public class AjaxComboBox<T extends ModelData> extends ComboBox<T> {
public AjaxComboBox() {
}
public interface GetDataCallback<T> {
void getData(String query, AsyncCallback<List<T>> dataCallback);
}
public AjaxComboBox(final String displayField, final int minChars, final GetDataCallback<T> getDataCallback) {
final RpcProxy<ListLoadResult<T>> proxy = new RpcProxy<ListLoadResult<T>>() {
#Override
protected void load(final Object loadConfig, final AsyncCallback<ListLoadResult<T>> callback) {
ListLoadConfig load = (ListLoadConfig) loadConfig;
final Map<String, Object> properties = load.getProperties();
getDataCallback.getData((String) properties.get("query"), new AsyncCallback<List<T>>() {
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
public void onSuccess(List<T> result) {
callback.onSuccess(new BaseListLoadResult<T>(result));
}
});
}
};
final BaseListLoader<ListLoadResult<T>> loader = new BaseListLoader<ListLoadResult<T>>(proxy);
final ListStore<T> store = new ListStore<T>(loader);
setFieldLabel(displayField);
setStore(store);
setHideTrigger(true);
setMinChars(minChars);
setWidth(300);
}
}
ComboBox lazy with paging
import com.extjs.gxt.ui.client.data.*;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.Map;
public class ComboBoxLazy<T extends ModelData> extends ComboBox<T> {
public interface GetPagingDataCallback<T> {
void getData(String query, PagingLoadConfig loadConfig,
AsyncCallback<PagingLoadResult<T>> dataCallback);
}
public ComboBoxLazy(final String displayField, final int minChars,
final GetPagingDataCallback<T> getDataCallback) {
final RpcProxy<PagingLoadResult<T>> proxy = new RpcProxy<PagingLoadResult<T>>() {
#Override
protected void load(Object loadConfig,
final AsyncCallback<PagingLoadResult<T>> callback) {
final Map<String, Object> properties = ((PagingLoadConfig) loadConfig).getProperties();
getDataCallback.getData((String) properties.get("query"),
((PagingLoadConfig) loadConfig),
new AsyncCallback<PagingLoadResult<T>>() {
#Override
public void onSuccess(
final PagingLoadResult<T> result) {
callback.onSuccess(result);
}
#Override
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
});
}
};
ModelReader reader = new ModelReader();
final BasePagingLoader<PagingLoadResult<T>> loader = new BasePagingLoader<PagingLoadResult<T>>(
proxy, reader);
loader.addListener(Loader.BeforeLoad, new Listener<LoadEvent>() {
public void handleEvent(LoadEvent be) {
be.<ModelData>getConfig().set("start",
be.<ModelData>getConfig().get("offset"));
}
});
setFieldLabel(displayField);
final ListStore<T> store = new ListStore<T>(loader);
setStore(store);
setHideTrigger(true);
setMinChars(minChars);
setPageSize(10);
setWidth(300);
}
}
Class Test
import br.ueg.escala.client.view.ConversorBeanModel;
import com.extjs.gxt.ui.client.data.*;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.List;
public class ComboBoxTest extends LayoutContainer {
#Override
protected void onRender(Element parent, int index) {
super.onRender(parent, index);
criarComboBox();
criarComboBoxLazy();
}
private void criarComboBox() {
final AjaxComboBox<BeanModel> combo = new AjaxComboBox<BeanModel>("name", 3, new AjaxComboBox.GetDataCallback<BeanModel>() {
public void getData(String query, final AsyncCallback<List<BeanModel>> dataCallback) {
servico.loadLike(query, new AsyncCallback<List<Person>>() {
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
public void onSuccess(List<Person> result) {
List<BeanModel> dados = ConversorBeanModel.getListBeanModel(result);
dataCallback.onSuccess(dados);
}
});
}
});
combo.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
#Override
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
BeanModel bm = combo.getView().getSelectionModel().getSelectedItem();
Person p = bm.getBean();
combo.setValue(bm);
try {
combo.setValue(bm);
combo.setRawValue(p.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
});
combo.setItemSelector("div.search-item");
combo.setTemplate(getTemplate());
addText("Any text");
add(combo);
}
private void criarComboBoxLazy() {
String field = "name";
final ComboBoxLazy<BeanModel> comboLazy = new ComboBoxLazy<BeanModel>(field, 3, new ComboBoxLazy.GetPagingDataCallback<BeanModel>() {
public void getData(String query, PagingLoadConfig loadConfig, final AsyncCallback<PagingLoadResult<BeanModel>> dataCallback) {
final PagingLoadConfig load = (PagingLoadConfig) loadConfig;
servico.loadLike(load, new Person(), "name", query, new AsyncCallback<List>() {
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
public void onSuccess(List result) {
PagingLoadResult<BeanModel> dados = ConversorBeanModel.getPagingLoadResultBeanModel(result, load);
dataCallback.onSuccess(dados);
}
});
}
});
comboLazy.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
#Override
public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
BeanModel bm = comboLazy.getView().getSelectionModel().getSelectedItem();
Person p = bm.getBean();
comboLazy.setValue(bm);
try {
comboLazy.setValue(bm);
comboLazy.setRawValue(p.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
});
comboLazy.setItemSelector("div.search-item");
comboLazy.setTemplate(getTemplate());
VerticalPanel vp2 = new VerticalPanel();
vp2.setSpacing(10);
vp2.addText("<span class='text'><b>Combo lazy</span>");
vp2.add(comboLazy);
add(vp2);
}
private native String getTemplate() /*-{
return [ '<tpl for="."><div class="search-item">',
' <h3> <span> Name:</span> <span style="font-weight:normal;">{name}</span> ',
' <span> - Last name:</span> <span style="font-weight: normal">{lastName}</span></h3>', '</div></tpl>'].join("");
}-*/;
}
Application.css:
.searchItem {
font: normal 11px tahoma, arial, helvetica, sans-serif;
padding: 3px 10px 3px 10px;
white-space: normal;
color: #555;
}
.searchItem h3 {
display: block;
font: inherit;
font-weight: bold;
color: #222;
}
.searchItem h3 span {
float: right;
font-weight: normal;
margin: 0 0 5px 5px;
width: 100px;
display: block;
clear: none;
}
Code server
public List loadLike(PagingLoadConfig config, Person classe, String field, String query) {
List<Person> list = null;
try {
List listEntity = genericoBC.loadLike(config.getOffset(), config.getLimit(), field, query, classe.getClass());
list = clone(listEntity);
final int totalCount = genericoBC.contarRegistros(classe.getClass());
config.setLimit(totalCount);
} catch (Exception e) {
tratarExcecao("", e);
}
return list;
}
public List<Person> loadLike(String query) {
List<Person> list = null;
try {
List<Person> listEntity = genericoBC.loadLike(query);
list = clone(listEntity);
} catch (Exception e) {
tratarExcecao("Error:genericoBC.loadLike(query)", e);
}
return list;
}
Override the method boolean isFiltered(ModelData record, String property) of the ListStore of the combobox.The method body will be following:
if (filterBeginsWith != null && property != null) {
Object o = record.get(property);
if (o != null) {
if (!o.toString().toLowerCase().contains(filterBeginsWith.toLowerCase())) {
return true;
}
}
}
if (filters != null) {
for (StoreFilter filter : filters) {
boolean result = filter.select(this, record, record, property);
if (!result) {
return true;
}
}
}
return false;
This is for GXT 3.0.
First, create an instance of the overridden ListStore class like this:
public static class MyListStore extends ListStore<Course>{
private String userText="";
public MyListStore(ModelKeyProvider<Course> k){
super(k);
}
#Override
protected boolean isFilteredOut(Course item) {
boolean result = false;
if(item.getTitle()!=null &&
!item.getTitle().toUpperCase().contains(userText.toUpperCase())){
result = true;
}
return result;
}
public void setUserText(String t){ userText = t; }
}
In this case, I had a Course model class that had the course title (a string) as the label provider for the combobox. So in your overridden class, do similar: use your specific model (the type of this instance of the combobox) in place of 'Course' in the code above.
Next, create an instance of this store for use by the combobox:
private MyListStore courses ;
Next, make sure you initialize the combobox appropriately with this. In my case, I used uibinder, so my initializer is this:
#UiFactory
ListStore<Course> createListStore() {
courses = new MyListStore(courseProps.key());
return courses;
}
The relevant uibinder snippets:
<ui:with type="com.sencha.gxt.data.shared.LabelProvider" field="titles"/>
<ui:with type="com.sencha.gxt.data.shared.ListStore" field="courses"/>
...
<form:ComboBox ui:field="classTitle" store="{courses}" labelProvider="{titles}"
allowBlank="false" forceSelection="true" triggerAction="ALL" width="200" />
Of course, the linkage into your bound java class:
#UiField ComboBox<Course> classTitle;
And, finally, make sure you handle the keyup event from the combobox input:
classTitle.addKeyUpHandler(new KeyUpHandler(){
#Override
public void onKeyUp(KeyUpEvent event) {
courses.setUserText(classTitle.getText());
}
});
This worked perfectly (first time!).