Managed bean property becomes null in a different request - jsf

I am facing a problem when initializing a List with new ArrayList<E>(). This is my class:-
#ManagedBean(name = "clientBean")
#SessionScoped
public class ClientBean {
public String msg = "", input, pendingMsg = "", user = "";
public GossipClient client;
public boolean inputDisabled = true, sendBtnDisabled = true, startBtnDisabled = false;
String key = null;
public List<ClientBeanDto> dtos;
ClientBeanDto dto;
String style;
public List<OnlineList> onlineList;
OnlineList userInfo;
OnlineList newUser = null;
public void start() throws UnknownHostException, IOException {
client = new GossipClient(this);
if (user != null && user != "" && client.connect()) {
try {
BufferedReader reader = new BufferedReader(new FileReader("D://key.txt"));
key = reader.readLine();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
client.start();
inputDisabled = sendBtnDisabled = false;
startBtnDisabled = true;
msg = pendingMsg = "";
pendingMsg = user + ", you are connected!";
client.sendNick(key + user);
onlineList = new ArrayList<OnlineList>();
dtos = new ArrayList<ClientBeanDto>();
}
.
.
.
}
The problem is with public List<OnlineList> onlineList. In start() method when the line onlineList = new ArrayList<OnlineList>(); is executed, in debugging mode I find its value null whereas a similar object dtos in the very next line gets initialized and assigned a id successfully.
I can't seem to find any reason for this behavior and I am not getting any error/exception. Any wisdom will be appreciated.
UPDATE: Found out that the list is becoming null whenever a button of xhtml (which the bean is backing) is clicked. I cannot find the reason though. The bean is SessionScoped and the other list(dtos) object is retained.

Related

How to show nearby locations from current location android studio?

I have been trying to display nearby locations from my current location. But when i run it and click the button to view the nearby locations nothing appears. The first time i ran it, it displayed but when i backed out and came back in, it didnt display anything. i tried cleaning the project and other methods.
this is the method in my main class:
public void findRestaurants(View v){
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
stringBuilder.append("location="+latLngCurrent.latitude + "," +latLngCurrent.longitude);
stringBuilder.append("&radius="+5000);
stringBuilder.append("&keyword="+"restaurant");
stringBuilder.append("&key="+getResources().getString(R.string.google_map_keyy));
String url = stringBuilder.toString();
Object dataTransfer[] = new Object[2];
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
}
public class getNearbyPlaces extends AsyncTask<Object,String,String> {
GoogleMap mMap;
String url;
InputStream is;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String data;
#Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
try {
URL myurl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) myurl.openConnection();
httpURLConnection.connect();
is = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
stringBuilder = new StringBuilder();
while((line = bufferedReader.readLine() ) != null){
stringBuilder.append(line);
}
data = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject parentObject = new JSONObject(s);
JSONArray resultsArray = parentObject.getJSONArray("results");
for (int i = 0; i<resultsArray.length(); i++){
JSONObject jsonObject = resultsArray.getJSONObject(i);
JSONObject locationObj = jsonObject.getJSONObject("geometry").getJSONObject("location");
String latitude = locationObj.getString("lat");
String longitude = locationObj.getString("lng");
JSONObject nameObject = resultsArray.getJSONObject(i);
String name_restaurant = nameObject.getString("name");
String vicinity = nameObject.getString("vicinity");
LatLng latLng = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
MarkerOptions markeroptions = new MarkerOptions();
markeroptions.title(vicinity);
markeroptions.position(latLng);
mMap.addMarker(markeroptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
it worked the first time when i lunched it. Did i do something wrong?
hope you are doing fine. Can you replace the lines
new getNearbyPlaces().execute(dataTransfer);
instead of these 2 lines
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
I am not sure whether this is going to impact much, but this is the way AsyncTask class should be called.
If this is not working, can you share the entire code of this java page, so we can look at how findRestaurant() method is called.

Micronaut + Thymeleaf Form Validation and Error Handling

Question: This doesn't seem to work.
#Post("/register")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#View("register")
#Error(exception = ConstraintViolationException.class)
def register(HttpRequest<?> request, ConstraintViolationException constraintViolationException) {
Optional<RegisterFormData> registerFormDataOptional = request.getBody(RegisterFormData.class)
Map<String, Object> map = new HashMap<>()
if(registerFormDataOptional.isPresent()){
RegisterRequest registerRequest = new RegisterRequest(registerFormDataOptional.get().properties)
registerRequest.returnSecureToken = true
try {
def registerResponse = firebaseClient.register(registerRequest, this.firebaseApiKey).blockingSingle()
SendEmailVerificationRequest sendEmailVerificationRequest = new SendEmailVerificationRequest()
sendEmailVerificationRequest.requestType = 'VERIFY_EMAIL'
sendEmailVerificationRequest.idToken = registerResponse.idToken
firebaseClient.sendEmailVerification(sendEmailVerificationRequest, this.firebaseApiKey)
HttpResponse.redirect(URI.create('/register-success'))
}catch(HttpClientResponseException ex){
map.put('errors', [ex.message])
return map
}
}else{
map.put('errors', violationMessageSource.violationsMessages(constraintViolationException.constraintViolations))
return map
}
}
gives me a
{"message":"Required argument [ConstraintViolationException constraintViolationException] not specified","path":"/constraintViolationException","_links":{"self":{"href":"/auth/register","templated":false}}}
Currently using Micronaut and Thymeleaf. Anyone know what else am I missing? I was following the examples from https://guides.micronaut.io/micronaut-error-handling/guide/index.html
The whole point here is to pass some error messages from the controller back to the UI when constraint violations happen. The default one that uses annotations #Body and #Valid don't work since it returns json errors without any views.
#Inject
Validator validator
#Inject
ViolationMessageSource violationMessageSource
#Post("/register")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
def register(HttpRequest<?> request, #Body RegisterFormData registerFormData) {
//validate registerformdata object
Map<String, Object> map = new HashMap<>()
Set<ConstraintViolation<RegisterFormData>> violations = validator.validate(registerFormData)
if (violations.size() > 0) {
map.put('registerFormData', registerFormData)
map.put('errors', violationMessageSource.violationsMessages(violations))
HttpResponse.redirect(URI.create('/register')).body(map)
} else {
RegisterRequest registerRequest = new RegisterRequest(registerFormData.properties)
registerRequest.returnSecureToken = true
try {
def registerResponse = firebaseClient.register(registerRequest, this.firebaseApiKey).blockingSingle()
SendEmailVerificationRequest sendEmailVerificationRequest = new SendEmailVerificationRequest()
sendEmailVerificationRequest.requestType = 'VERIFY_EMAIL'
sendEmailVerificationRequest.idToken = registerResponse.idToken
firebaseClient.sendEmailVerification(sendEmailVerificationRequest, this.firebaseApiKey)
HttpResponse.redirect(URI.create('/register-success'))
} catch (HttpClientResponseException ex) {
map.put('errors', [ex.message])
HttpResponse.redirect(URI.create('/register')).body(map)
}
}
}
where I have injected a validator bean in Micronaut like so
#Factory
class ValidatorConfig {
Validator validator
#PostConstruct
void initialize(){
ValidatorFactory factory = Validation.buildDefaultValidatorFactory()
validator = factory.getValidator()
}
#Bean
Validator getValidator(){
return validator
}
}
and my message source like so
#Singleton
public class ViolationMessageSource {
public List<String> violationsMessages(Set<ConstraintViolation<?>> violations) {
return violations.stream()
.map(ViolationMessageSource::violationMessage)
.collect(Collectors.toList());
}
private static String violationMessage(ConstraintViolation violation) {
StringBuilder sb = new StringBuilder();
Path.Node lastNode = lastNode(violation.getPropertyPath());
if (lastNode != null) {
sb.append(lastNode.getName());
sb.append(" ");
}
sb.append(violation.getMessage());
return sb.toString();
}
private static Path.Node lastNode(Path path) {
Path.Node lastNode = null;
for (final Path.Node node : path) {
lastNode = node;
}
return lastNode;
}
}
The answers are based on the fundamentals on javax validation https://www.baeldung.com/javax-validation and error handling in micronaut https://guides.micronaut.io/micronaut-error-handling/guide/index.html

AndroidStudio about HttpURLConnection

This is my method!
private String logInActivity() {
String userID = idText.getText().toString();
String userPW = pwText.getText().toString();
final String SERVER = "http://115.145.241.151:8080/AndroidCommunication/LoginActivity.jsp";
if (userID != null && userPW != null) {
final String QUERY = "?id=" + userID + "&pw=" + userPW;
HttpURLConnection connection = null;
URL url = null;
try {
url = new URL(SERVER+QUERY);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
return line;
} catch (Exception e) {
e.printStackTrace();
return "3";
}
} else {
Toast.makeText(GetReview.this, "Type all required info", Toast.LENGTH_SHORT).show();
return "2";
}
}
I'm just practicing HttpURLConnection( by GET METHOD). I know i shouldn't send passwords or ids like this way but i'm just practicing my exercise. But I just don't get why this goes to an Exception. Please help!
I didn't type my addresses or anything wrong because I tried it, and server was on. I debugged it and the connection.connect(); doesn't seems to work.
my onCreate goes:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_review);
pwText = findViewById(R.id.pwText);
idText = findViewById(R.id.idText);
resultText = findViewById(R.id.resultText);
findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAsyncTask().execute(logInActivity());
}
});
}
The problem is that issuing HTTP requests on the main thread is not allowed by android. That's why you are receiving a NetworkOnMainThreadException exception. To resolve this, you can use an IntentService to do that job for you and then broadcast the results back to the receiver (your activity).
If you don't know much about android Services, then have a read in the documentation, you'll find yourself using them time and time again...
https://developer.android.com/guide/components/services#CreatingAService

JSF <protected-views> token inconsistency

I'm currently having trouble regarding the token generated by <protected-views> of JSF.
I added the page I want to protect in faces-config.xml
<protected-views>
<url-pattern>/restricted/account-management/users.xhtml</url-pattern>
<url-pattern>/restricted/account-management/users.jsf</url-pattern>
</protected-views>
Then for example when I go the users page using an <h:link>
<h:link outcome="users" title="View">
<f:param name="user" value="#{e.id}" />
</h:link>
the token generated in the URL is this
/restricted/account-management/users.jsf?javax.faces.Token=OW5KkkfJZrrfmZSXwA%253D%253D&user=4
The page returns a ProtectedViewException
Then I found out that the correct token is actually:
/restricted/account-management/users.jsf?javax.faces.Token=OW5KkkfJZrrfmZSXwA%3D%3D
The token was encoded in the URL, where % became %25. When I copy-paste the correct token into the URL, I get into the users page successfully.
Any help would be appreciated.
This is a problem with the versions 2.2.11 and above of Mojarra JSF Implementation, you can see the details about issue in https://github.com/javaee/javaserverfaces-spec/issues/1161 and here https://github.com/javaserverfaces/mojarra/issues/4139
One of the alternatives to handle the problem is to create a CustomExternalContext to handle the double encoding.
First you need declare in faces-config.xml a CustomExternalContextFactory:
<factory>
<external-context-factory>com.proitc.config.CustomExternalContextFactory</external-context-factory>
</factory>
In the ExternalContextFactory you define the CustomExternalContext:
public class CustomExternalContextFactory extends ExternalContextFactory {
private ExternalContextFactory externalContextFactory;
public CustomExternalContextFactory() {}
public CustomExternalContextFactory(ExternalContextFactory externalContextFactory) {
this.externalContextFactory = externalContextFactory;
}
#Override
public ExternalContext getExternalContext(Object context, Object request, Object response)
throws FacesException {
ExternalContext handler = new CustomExternalContext((ServletContext) context,
(HttpServletRequest) request, (HttpServletResponse) response);
return handler;
}
}
The CustomExternalContext override the methods encodeBookmarkableURL and encodeRedirectURL:
public class CustomExternalContext extends ExternalContextImpl {
public CustomExternalContext(ServletContext sc, ServletRequest request,
ServletResponse response) {
super(sc, request, response);
}
#Override
public String encodeBookmarkableURL(String baseUrl, Map<String, List<String>> parameters) {
FacesContext context = FacesContext.getCurrentInstance();
String encodingFromContext =
(String) context.getAttributes().get(RIConstants.FACELETS_ENCODING_KEY);
if (null == encodingFromContext) {
encodingFromContext =
(String) context.getViewRoot().getAttributes().get(RIConstants.FACELETS_ENCODING_KEY);
}
String currentResponseEncoding =
(null != encodingFromContext) ? encodingFromContext : getResponseCharacterEncoding();
UrlBuilder builder = new UrlBuilder(baseUrl, currentResponseEncoding);
builder.addParameters(parameters);
String secureUrl = builder.createUrl();
//Handle double encoding
if (parameters.size() > 0 && baseUrl.contains("javax.faces.Token")) {
try {
int beginToken = secureUrl.indexOf("javax.faces.Token");
int endToken = secureUrl.indexOf("&") - 1;
String doubleEncodeToken = secureUrl.substring(beginToken, endToken);
String encodeToken = URLDecoder.decode(doubleEncodeToken, currentResponseEncoding);
secureUrl = secureUrl.replace(doubleEncodeToken, encodeToken);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return secureUrl;
}
#Override
public String encodeRedirectURL(String baseUrl, Map<String, List<String>> parameters) {
FacesContext context = FacesContext.getCurrentInstance();
String encodingFromContext =
(String) context.getAttributes().get(RIConstants.FACELETS_ENCODING_KEY);
if (null == encodingFromContext) {
encodingFromContext =
(String) context.getViewRoot().getAttributes().get(RIConstants.FACELETS_ENCODING_KEY);
}
String currentResponseEncoding =
(null != encodingFromContext) ? encodingFromContext : getResponseCharacterEncoding();
UrlBuilder builder = new UrlBuilder(baseUrl, currentResponseEncoding);
builder.addParameters(parameters);
String secureUrl = builder.createUrl();
//Handle double encoding
if (parameters.size() > 0 && baseUrl.contains("javax.faces.Token")) {
try {
int beginToken = secureUrl.indexOf("javax.faces.Token");
int endToken = secureUrl.indexOf("&") - 1;
String doubleEncodeToken = secureUrl.substring(beginToken, endToken);
String encodeToken = URLDecoder.decode(doubleEncodeToken, currentResponseEncoding);
secureUrl = secureUrl.replace(doubleEncodeToken, encodeToken);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return secureUrl;
}
}
You can find a working example in https://github.com/earth001/jsf-protected-view

Getting error while calling library jar file in j2me

I have created a login page with webservice in j2me. But while running I am getting error. Can anyone please help? My code is:
public class Login extends MIDlet implements CommandListener {
//the main form
Form mainForm = null;
//the text-boxes for the input
TextField txtBoxA = null;
TextField txtBoxB = null;
//the result label
//the Exit command
Command cmdExit = null;
Command cmdAdd = null;
//the Display reference
Display display = null;
public Login() {
{
//construct the main form
mainForm = new Form("kSOAP Example");
//construct the controls
txtBoxA = new TextField("UserName:", null, 50, TextField.ANY);
txtBoxB = new TextField("Password:", null, 50, TextField.ANY);
// result = new StringItem("Result:", null);
//add controls to the form
mainForm.append(txtBoxA);
mainForm.append(txtBoxB);
// mainForm.append(result);
//construct commands
cmdExit = new Command("Exit", Command.EXIT, 1);
cmdAdd = new Command("Add", Command.SCREEN, 1);
//add commands
mainForm.addCommand(cmdAdd);
mainForm.addCommand(cmdExit);
}
}
public void startApp() {
if (display == null) {
display = Display.getDisplay(this);
}
//display the main form
display.setCurrent(mainForm);
//register the command listener
mainForm.setCommandListener(this);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
this.destroyApp(false);
this.notifyDestroyed();
} else if (c == cmdAdd) {
//callWebServiceMethod();
Library lib=new Library();
lib.init();
}
}
my jar file coding is library.jar
public class Library {
String METHOD_NAME = "ValidateLogin_M";
String SOAP_ACTION ="http://64.244.69.235:81/MobileApp/ValidateLogin_M";
String NAMESPACE ="http://64.244.69.235:81/MobileApp/";
String URL ="http://64.244.69.235:81/MobileApp/service1.asmx";
public Library() {
// TODO Auto-generated constructor stub
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Library lib=new Library();
lib.init();
}
public void init()
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String user= "gsrtestnew#gmail.com";
String password= "123456";
request.addProperty("UserID",user);
request.addProperty("Password",password);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransport j2meHttpTransport = new HttpTransport(URL);
try {
j2meHttpTransport.call(SOAP_ACTION, envelope);
SoapObject content = (SoapObject) envelope.bodyIn;
String sum = content.getProperty(0).toString();
// result.setText(sum);
System.out.println("##########"+sum);
JSONArray jsonobj = new JSONArray(sum.toString());
System.out.println("Json obj length:: " + jsonobj.length());
if(jsonobj.length() == 0)
{
}
for(int i=0; i<jsonobj.length(); i++)
{
JSONObject jobj = jsonobj.getJSONObject(i);
String CustID = jobj.getString("CustID");
System.out.println("CustID is :: "+CustID);
String Email = jobj.getString("Email");
System.out.println("Email is :: "+Email);
String FirstName = jobj.getString("FirstName");
System.out.println("FirstName is :: "+FirstName);
String LastName = jobj.getString("LastName");
System.out.println("LastName is :: "+LastName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have imported the jar file and called as Library class. But still I am getting error.
My error is
Starting emulator in execution mode
Installing suite from: http://127.0.0.1:49412/WebApplication.jad
TRACE: <at java.lang.Error: ClassFormatError: 56>, Exception caught in Display class
java.lang.Error: ClassFormatError: 56
at com.web.application.Login.commandAction(Login.java:95)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.commandSelected(), bci=11
at com.sun.midp.chameleon.layers.MenuLayer.pointerInput(), bci=170
at com.sun.midp.chameleon.CWindow.pointerInput(), bci=76
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handlePointerEvent(), bci=19
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=296
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)
This has already been answered - jvm cannot load a class due to difference in version - cf - ClassFormatError: 56 while using hessian in j2me
Recompile with
javac -target 1.4 ...

Resources