i want use spring mvc convert json to one object like
#RequestMapping(value = "searchPolygonArea/", method = RequestMethod.GET,params = {"region != null"})
public #ResponseBody ResultBean <List <Spot>> searchPolygonArea(#ModelAttribute (value="regionModel") Region regions,#RequestParam(value="region") Region region){
return new ResultBean <List<Spot>> ();
}
#InitBinder(value="regionModel")
public void initBinder(WebDataBinder dataBinder,#RequestParam(value="region") final String regionParams){//,
dataBinder.registerCustomEditor (Region.class, new PropertyEditorSupport (){
Region value ;
#Override
public Object getValue () {
return new Region ();
}
#Override
public void setAsText (String text) throws IllegalArgumentException {
System.out.println (text);
try {
value = JSONUtils.json2Obj (text, Region.class);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
but setAsText and getValue not executed , i don't know why.
Related
I have the following controller logic. However, if I navigate to a non-existing page (e.g. /random-page), I end up with a TemplateInputException. How can I catch this and go to the 404 page?
#RequestMapping(value = { "{path:(?!resources|error).*$}", "{path:(?!resources|error).*$}/**" }, headers = "Accept=text/html")
public String index(final HttpServletRequest request) {
try {
String path = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
return path.split("/")[1];
} catch (Exception e) {
log.error("Failed to render the page. {}",e);
return "error/general";
}
}
Thymeleaf seems to be ignoring the ExceptionHandler:
#ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception ex) {
ModelAndView model = new ModelAndView("error/generic_error");
model.addObject("errMsg", "this is Exception.class");
return model;
}
My workaround this problem for spring-boot (exception is view with message param):
#Controller
public class ErrorController implements org.springframework.boot.autoconfigure.web.ErrorController {
private static final String ERROR_PATH = "/error";
#Autowired
private ErrorAttributes errorAttributes;
#Override
public String getErrorPath() {
return ERROR_PATH;
}
#RequestMapping(ERROR_PATH)
public String error(HttpServletRequest request, Model model) {
Map<String, Object> errorMap = errorAttributes.getErrorAttributes(new ServletRequestAttributes(request), false);
String exception = (String) errorMap.get("exception");
if (exception != null && exception.contains("TemplateInputException")) {
errorMap.put("message", "Неверный запрос");
}
model.addAllAttributes(errorMap);
return "exception";
}
}
On selection of Tableview row, it display the data in the combobox,
i try to display the value in the comboxbox from tableview using this code.
private void showInputDetails(InputConfigurationModel ipmodel) {
if (ipmodel != null) {
cmbfiletype.setValue(ipmodel.getFiletype().toString());
}
My Inputconfiguartion Model class:
public class InputConfigurationModel {
public StringProperty filetype = new SimpleStringProperty();
public InputConfigurationModel(String filetype) {
this.filetype = new SimpleStringProperty(filetype);
}
public InputConfigurationModel() {
}
public String getFiletype() {
return filetype.get();
}
public void setFiletype(String value) {
filetype.set(value);
}
public StringProperty filetypeProperty()
{
return filetype;
}
// #Override
// public String toString() {
// return filetype.toString(); //To change body of generated methods, choose Tools | Templates.
// }
}
but if i try change the value of combobox for update it display error as
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.String cannot be cast to Clover.Converter.Model.ExtensionModel
i am trying to change the value in the combobox from this code
Loading the combobox value from this Loadfile method
public void LoadFile() {
try {
String sql = "select * from EXTENSION";
PreparedStatement ps = conn.prepareStatement(sql);
rs = ps.executeQuery(sql);
while (rs.next()) {
ExtensionModel extModel = new ExtensionModel();
filetypelstupdate_ip = FXCollections.observableArrayList(extModel);
String ext_type = rs.getString("EXT_TYPE");
String ext_name = rs.getString("EXT_NAME");
int ext_id=Integer.parseInt(rs.getString("EXT_ID"));
extModel.setExttype(ext_type);
extModel.setExtname(ext_name);
extModel.setExtid(ext_id);
cmbfiletype.getItems().addAll(filetypelstupdate_ip);
cmbfiletype.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ExtensionModel>() {
#Override
public void changed(ObservableValue<? extends ExtensionModel> observable, ExtensionModel oldValue, ExtensionModel newValue) {
aaa(newValue);
}
});
catch (Exception ex) {
ex.printStackTrace();
}
}
public void aaa(ExtensionModel exm){
if(cmbfiletype!=null)
{
txtextid.setText(exm.getExtid().toString());
System.out.println("txtextid"+txtextid);
}
}
i dont how to solve this error? tried everything but still coming class cast exception
my error is coming in LoadFile Method in this code first line
**cmbfiletype.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ExtensionModel>() {**
#Override
public void changed(ObservableValue<? extends ExtensionModel> observable, ExtensionModel oldValue, ExtensionModel newValue) {
aaa(newValue);
});
}
} catch (Exception e) {
e.printStackTrace();
}
First it display the value in the comboxbox from the tableview which is a string in INPUTCONFIGURATION model class and thn i tried to change the the combobox value which comes from LoadFile method, hence it comes as class cast exception. kindly help me how to solve this class cast exception error.
I am new in android using fragments in my Project. first time my fragment is creating then api called and get data load in fragment. here when i clicked at any item i replaced fragment by another fragment there also another api called and load data to fragment.
now here problem situation generated for me.
from here i back Button pressed.
fragment reloading same as first time creating but it should be show data as i left before going to next fragment.
so please provide me solution how i can get same data as i left means savedInstanceState data.
im my first fragment getCategory method call Api and get Data first time when i choose any category i replace fragment with another fragment but when i m returning same getCategory method recall perform same process as it first time.
fragment should not call api method again on backpressed it should show same category on this i clicked before.
my first fragment where calling api......
public class LandingFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GridLayoutManager gridLayoutManager;
private static RecyclerView category_Grid;
private Fragment myFragment = null;
ProgressBar mProgressView;
View mLoginFormView;
private Category category;
private CategoryAdapter categoryAdapter;
private List<CategoryObject> rowListItem;
private String productId;
private OnFragmentInteractionListener mListener;
public LandingFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LandingFragment.
*/
// TODO: Rename and change types and number of parameters
public static LandingFragment newInstance(String param1, String param2) {
LandingFragment fragment = new LandingFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_landing, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
RecyclerViewListeners();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void initViews(final View v) {
mLoginFormView = (View)v.findViewById(R.id.mainView);
mProgressView = (ProgressBar)v.findViewById(R.id.login_progress);
category_Grid = (RecyclerView)v.findViewById(R.id.cat_grid);
category_Grid.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 3);
category_Grid.setLayoutManager(gridLayoutManager);
}
private void RecyclerViewListeners(){
category_Grid.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), category_Grid, new ItemClickListener(){
#Override
public void onClick(View view, int position) {
String entityId = rowListItem.get(position).getCategoryId();
String catName = rowListItem.get(position).getName();
Integer ishave = rowListItem.get(position).getIshaveSubcategories();
if(ishave==1) {
myFragment = SubcategoryFragment.newInstance(""+catName, "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}else{
myFragment = ProductListFragment.newInstance("", "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void getCategory() {
showProgress(true);
String URL = getResources().getString(R.string.category_api);
StringRequest req = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
Gson gson = new GsonBuilder().serializeNulls().create();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals(getResources().getString(R.string.response_success))){
category = gson.fromJson(response, Category.class);
rowListItem = category.getCategory();
if(navigationUpdated){
someEventListener.someEvent(rowListItem);
navigationUpdated = false;
}
Log.d("CATEGORYID::::::::",""+rowListItem.get(1).getCategoryId());
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
return;
}
else if (jsonObject.getString("status").equals(getResources().getString(R.string.login_Er_respose))){
Log.e("","ERRORRRRRR");
return;
}
} catch (JSONException e) {
showProgress(false);
Log.e("My App", "Could not parse malformed JSON: \"" + response + "\"");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showProgress(false);
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance().addToRequestQueue(req);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
You can check your rowListItem.size(), if it's size is 0 then call getCategory() service, otherwise load your data from your rowListItem. Here is sample code which I am using to load data from arraylist if it is not empty:
if (mArrayArticle.size() == 0) {
isDataLoading = true;
mRecyclerList.setVisibility(View.INVISIBLE);
getCategory();
} else {
mHomeItemAdapter = new HomeItemAdapter(getActivity(), mArrayArticle, this);
mRecyclerList.setAdapter(mHomeItemAdapter);
}
Here mArrayArticle is my ArrayList, Hope it will help you.
for more clarification i want to tell..
how i implement the #Bhvk_AndroidBee solution
fragment backpressed call onActivityCreated Method so first overridethis method in fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//here you can check null condition for rowListItem
}
}
inside onActivityCreated method I checked the condition like that
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(rowListItem!=null){
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
}else {
//call the method for first time creating your view
getCategory();
}
}
hope this would be helpfull for more strugglers like me...
I have written code to get async data from Couchbase views:
This is the Implementation Class
AsyncViewResult viewResult =
offerCouchDao.findViewResultAsync(DDN, VIEWNAME).toBlocking().single();
if (viewResult.success()) {
Observable<JsonArray> JAoffer =
offerCouchDao.getAsyncJsonObject(viewResult.rows());
Object response = offerCouchDao.getData(JAoffer);
System.out.println("Data is "+response);
return new OfferResponse(true,"Offer Data",response).toJson();
}
This is OfferCouchDao:
public Observable<AsyncViewResult> findViewResultAsync(String ddn, String viewname) {
ViewQuery allResult = ViewQuery.from(ddn, viewname);
return couchbaseManager.getMobikwikBucket().async().query(allResult);
}
public Observable<JsonArray> getAsyncJsonObject(Observable<AsyncViewRow> viewResult) {
return viewResult.
//extract the document from the row and carve a result object using its content and id
flatMap(new Func1<AsyncViewRow, Observable<JsonObject>>() {
#Override
public Observable<JsonObject> call(AsyncViewRow row) {
return row.document().map(new Func1<JsonDocument, JsonObject>() {
#Override
public JsonObject call(JsonDocument jsonDocument) {
return JsonObject.create()
.put("id", jsonDocument.id())
;
}
})
;
}
}).filter(new Func1<JsonObject, Boolean>() {
#Override
public Boolean call(JsonObject jsonObject) {
String name = jsonObject.getString("name");
return name != null ;
}
})
.collect(new Func0<JsonArray>() { //this creates the array (once)
#Override
public JsonArray call() {
return JsonArray.empty();
}
}, new Action2<JsonArray, JsonObject>() { //this populates the array (each item)
#Override
public void call(JsonArray objects, JsonObject jsonObject) {
objects.add(jsonObject);
}
});
}
public Object getData(Observable<JsonArray> jsonArraay) {
return jsonArraay
.map(new Func1<JsonArray, JsonArray>() {
#Override
public JsonArray call(JsonArray objects) {
return objects;
}
})
.onErrorReturn(new Func1<Throwable, JsonArray>() {
#Override
public JsonArray call(Throwable throwable) {
return null;
}
})
.toBlocking().single();
}
The issue I have is Data returned is null
Here are the logs:
Data is []
Data is null
Also when doing via sync call which is:
else {
JsonArray keys = JsonArray.create();
Iterator<ViewRow> iter = viewResult.rows();
while (iter.hasNext()) {
ViewRow row = iter.next();
JsonObject beer = JsonObject.create();
beer.put("name", row.key());
beer.put("id", row.id());
keys.add(beer);
}
}
I am getting the expected response.
Can Someone help me?
I have built a custom component button, but somehow the action is not invoked. When debugging the getAction-Method within the component and invoking the supplied MethodeExpression the Bean-Method is called as expected. But due to some reason, the Expression is not invoked when pressing the button in the browser.
Is there some kind of additional Interface necessary to pass the action to the embedded button-component?
Any help is very appreciated since I am stuck at this issue for some days now
MyClass:
public class MyClass extends UIPanel implements SystemEventListener
{
private UIForm form;
private HtmlCommandButton buttonOk;
public MyClass()
{
FacesContext context = getFacesContext();
UIViewRoot root = context.getViewRoot();
root.subscribeToViewEvent(PostAddToViewEvent.class, this);
}
#Override
public void processEvent(SystemEvent event)
{
this.form = new UIForm();
this.buttonOk = new HtmlCommandButton();
this.buttonOk.setId("okButtonId");
this.buttonOk.setActionExpression(getAction());
this.buttonOk.setValue("OK");
this.form.getChildren().add(this.buttonOk);
getChildren().add(this.form);
}
private enum PropertyKeys
{
action, text, titel
}
public MethodExpression getAction()
{
return (MethodExpression) getStateHelper().eval(PropertyKeys.action);
}
public void setAction(MethodExpression actionExpression)
{
getStateHelper().put(PropertyKeys.action, actionExpression);
}
public String getText()
{
return (String) getStateHelper().eval(PropertyKeys.text);
}
public void setText(String text)
{
getStateHelper().put(PropertyKeys.text, text);
}
public String getTitel()
{
return (String) getStateHelper().eval(PropertyKeys.titel);
}
public void setTitel(String titel)
{
getStateHelper().put(PropertyKeys.titel, titel);
}
#Override
public void encodeAll(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
writer.startElement(HTML.DIV_ELEM, this);
writer.writeText(getText(), null);
this.form.encodeAll(context);
writer.endElement(HTML.DIV_ELEM);
}
#Override
public void encodeChildren(FacesContext context) throws IOException
{
}
#Override
public boolean isListenerForSource(Object source)
{
return (source instanceof MyClass);
}
}
MyClassHandler:
public class MyClassHandler extends ComponentHandler
{
public MyClassHandler(ComponentConfig config)
{
super(config);
}
#SuppressWarnings("rawtypes")
#Override
protected MetaRuleset createMetaRuleset(Class type)
{
return super.createMetaRuleset(type).addRule(new MethodRule("action", String.class, new Class[] { ActionEvent.class }));
}
}
myView Method:
...
public String myMethod()
{
System.err.println("myMethod");
return "/some/path/yadayada.xhtml";
}
...
MyView.xhtml
<myTag action="#{myView.myMethod}" id="id1" titel="bla" text="bleh" />
Exdending UICommand is enough, since you only want one action to be executed.
You have to provide two additional MethodExpressions via the tag-attributes and within the decode-method you can check which button has been pressed and redirect the particular MethodExpression to the standard-action provided by UICommand. This way, you dont have to worry about the legacy-interface ActionSource, or how Events are broadcasted.
public void decode(FacesContext contex)
{
Map<String,String> map = context.getExternalContext.getRequestParameterMap();
// your rendered buttons need a name you check for
final boolean okPressed = map.containsKey( getClientId + ":ok" );
final boolean cancelPressed = map.containsKey( getClientId + ":cancel" );
if(okPressed || cancelPressed)
{
MethodExpression exp = null;
if(okPressed)
{
exp = getActionOk();
}
else
{
exp = getActionCancel();
}
// redirect to standard action
setActionExpression(exp);
queueEvent(new ActionEvent(this));
}
}
In order to make use of of this you need two attributes (actionOk and actionCancel) which use Method Expressions (setter and getter). Those have to be configured by a ComponentHandler as you did for the action-attribute.