E/AndroidRuntime FATAL EXCEPTION: main PID: 17633 - javascript

When I try to register a new user in my app, throw mySQL db the application doesn't work and sends this error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.io.biolite6, PID: 17633
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object
reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.(JSONObject.java:156)
at org.json.JSONObject.(JSONObject.java:173)
at com.example.io.biolite6.BackgroundsTask.onPostExecute(BackgroundsTask.java:114)
at com.example.io.biolite6.BackgroundsTask.onPostExecute(BackgroundsTask.java:30)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
I/Process: Sending signal. PID: 17633 SIG: 9
public class BackgroundsTask extends AsyncTask<String,Void,String> {
String register_url = "http://192.168.1.104/loginapp/register.php";
Context ctx;
ProgressDialog progressDialog;
Activity activity;
AlertDialog.Builder builder;
public BackgroundsTask(Context ctx)
{
this.ctx = ctx;
activity = (Activity) ctx;
}
#Override
protected void onPreExecute()
{
builder = new AlertDialog.Builder(activity);
progressDialog = new ProgressDialog(ctx);
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Connecting to server...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("register"))
{
try {
URL url = new URL(register_url);
HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String name = params[1];
String email = params[2];
String password = params[3];
String data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true"))
{
showDialog("Registration Success", message,code);
}
else if (code.equals("reg_false"))
{
showDialog("Registration Failed",message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void showDialog(String title, String message, String code)
{
builder.setTitle(title);
if (code.equals("reg_true")||code.equals("reg_false"))
{
builder.setMessage(message);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
}

Related

Spring WebSocket doesn't replay to subscribers

I'm following this tutorial to understand how webSocket works in Spring.
My controller class:
#Controller
public class TestController {
#MessageMapping("/chat")
#SendTo("/topic/messages")
public String greeting(String message) {
System.out.println("HelloWorld"); // <--- The code is executed
return "HelloWorld";
}
}
My WebSocket class:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("topic");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").setAllowedOriginPatterns("*").withSockJS();
}
}
My js client:
export function connect() {
var socket = new SockJS("http://192.168.1.63:5001/chat");
stompClient = Stomp.over(socket);
//stompClient.debug = null;
stompClient.connect({}, (frame) => {
console.log(frame);
stompClient.subscribe("/topic/messages", messageOutput => {
console.log(messageOutput); // <-- Nothing here!
});
});
}
export function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
export function sendMessage() {
stompClient.send(
"/app/chat",
{},
"this is only a test!"
);
}
what happens in Chrome Inspector: Chrome Inspector
So, it seems as the server side doesn't replay at client though the "greeting" method is invoked.

REST services work from curl, not from application

I have a small web app built using Spring, and the REST services are accessible from curl and postman. If I try to access them using the JavaScript hosted on my web app I get a 405 error. What could cause this?
I realize there are insecurities in the code, this is just a rushed class project so they are not important.
If I copy the JavaScript code and run it in the console of the browser it works.
User class
import org.springframework.data.annotation.Id;
public class User {
#Id
public String id;
private String username;
private String firstName;
private String lastName;
private String password;
private int zipCode;
private int jacketThreshold;
private int coatThreshold;
public User() {}
public User(String username)
{
this.username = username;
}
public User(String firstName, String lastName, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
}
public User(String username, String password, int zipCode) {
this.username = username;
this.password = password;
this.zipCode = zipCode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public int getJacketThreshold() {
return jacketThreshold;
}
public void setJacketThreshold(int jacketThreshold) {
this.jacketThreshold = jacketThreshold;
}
public int getCoatThreshold() {
return coatThreshold;
}
public void setCoatThreshold(int coatThreshold) {
this.coatThreshold = coatThreshold;
}
#Override
public String toString() {
return String.format(
"User[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
UserController class
import org.springframework.web.bind.annotation.*;
#RestController
public class UserController {
private final UserRepository repository;
public UserController(UserRepository repository) {
this.repository = repository;
}
#CrossOrigin
#PostMapping("/newuser")
User newUser(#RequestBody User newUser)
{
return repository.save(newUser);
}
}
UserRepository
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends MongoRepository<User, String> {
public User findByUsername(#Param("username") String username);
}
Application class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class WtwApplication {
public static void main(String[] args) {
SpringApplication.run(WtwApplication.class, args);
}
}
JavaScript calling the REST service
var user = document.getElementById('uname');
var pass = document.getElementById('pass');
var zip = document.getElementById('zip');
const data = { username : user, password : pass};
fetch('http://localhost:8080/newuser', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Error received
2020-12-04 22:52:34.071 WARN 17936 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
Cross origin must include your js hosted server address like
Ex - #CrossOrigin(origins="http://localhost:3000)
and add it after the #RestController
Check your js code.
If you look at your controller, it's declared #PostMapping. Make sure your js code is calling the same POST method.
Check if you are returning a #ResponseBody or a #ResponseStatus
To fix this simply add a #ResponseBody
#RequestMapping(value="/user", method = RequestMethod.POST)
public #ResponseBody String updateUser(#RequestBody User user){
return userService.updateUser(user).getId();
}
or a #ResponseStatus to your method.
#RequestMapping(value="/user", method = RequestMethod.POST)
#ResponseStatus(value=HttpStatus.OK)
public String updateUser(#RequestBody User user){
return userService.updateUser(user).getId();
}

Query Firebase on javascript

I'm creating a quiz app and I want to filter my database questions in order by level and cateogory but I don't know how to do it. I've already implemented the levelRef to get the level and display it on screen.
I also want to fetch the category and filter the questions (e.g: if user taps on sport I'll display only sport questions).
Here's my code
`private void updateQuestion(){
countDownTimer.cancel();
mQuestionRef = new Firebase("https://quizer-f3732.firebaseio.com/Questions/" + mQuestionNumber + "/question");
mQuestionRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String question = dataSnapshot.getValue(String.class);
mQuestion.setText(question);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mChoice1Ref = new Firebase("https://quizer-f3732.firebaseio.com/Questions/" + mQuestionNumber + "/choice1");
mChoice1Ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String choice = dataSnapshot.getValue(String.class);
mButtonChoice1.setText(choice);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mChoice2Ref = new Firebase("https://quizer-f3732.firebaseio.com/Questions/" + mQuestionNumber + "/choice2");
mChoice2Ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String choice = dataSnapshot.getValue(String.class);
mButtonChoice2.setText(choice);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mChoice3Ref = new Firebase("https://quizer-f3732.firebaseio.com/Questions/" + mQuestionNumber + "/choice3");
mChoice3Ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String choice = dataSnapshot.getValue(String.class);
mButtonChoice3.setText(choice);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mChoice4Ref = new Firebase("https://quizer-f3732.firebaseio.com/Questions/" + mQuestionNumber + "/choice4");
mChoice4Ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String choice = dataSnapshot.getValue(String.class);
mButtonChoice4.setText(choice);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mAnswerRef = new Firebase("https://quizer-f3732.firebaseio.com/Questions/" + mQuestionNumber + "/answer");
mAnswerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mAnswer = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mLevelRef = new Firebase("https://quizer-f3732.firebaseio.com/Questions/" + mQuestionNumber + "/level");
mLevelRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.getValue(String.class);
mLevel.setText("Livello " + level);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mProgressQuestion.incrementProgressBy(PROGRESS_INCREMENT);
mQuestionNumber++;
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
}`

Download zip file ajax response in java spring mvc

I'm trying to download multiple files as a zip file, I'm posting an AJAX request with my form data to the server, which compresses the file and returns it for the client to download, with the following code:
function downloadDocs(arrays) {
console.log("Call download");
var text = JSON.stringify(arrays);
$("#selectedList").val(text);
var formData = new FormData($("#formSelectionFiles")[0]);
formData.append("candidateId", $("#candidateId").val());
$.ajax({
type : "POST",
url : "${contextPath}/ajax/candidate/onboarding/multidownload?data=",
contentType: false,
processData: false,
data : formData,
success : function(data) {
var blob = new Blob([data], {type: "application/octet-stream"});
//URL.createObjectURL(blob)
saveAs(blob, "download.zip");
console.log("SUCCESS : " + data);
},
error : function(e) {
console.log("ERROR : ", e);
}
});
}
My Controller to mapping URL:
#RequestMapping(value = "/ajax/candidate/onboarding/multidownload", method = RequestMethod.POST
, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public #ResponseBody byte[] downloadCandidateDoc(HttpServletRequest req, HttpServletResponse res, Long candidateId,
String selectedList) {
System.out.println(selectedList);
if (TextUtils.isEmpty(selectedList)) {
return null;
}
final Type token = (Type) new TypeToken<ArrayList<DownloadItem>>() {
}.getType();
final GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
final List<DownloadItem> fileList = gson.fromJson(selectedList, token);
return candidateService.downloadCandidateDocs(res, String.valueOf(candidateId), fileList);
}
My service:
public byte[] downloadCandidateDocs(HttpServletResponse res, String id, List<DownloadItem> files) {
final String candidateDir = MediaUtil.getAbsolutePath("upload_candidate", id);
List<String> fileList = new ArrayList<>();
if (files != null && !files.isEmpty()) {
for (DownloadItem str : files) {
System.out.println("file name: " + str.getUrl());
fileList.add(new File(candidateDir, str.getUrl()).getAbsolutePath());
}
}
try {
return FileStreamUtil.zipfiles(fileList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
This code is used to generate the zip file:
public static byte[] zipfiles(List<String> files) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[2048];
for (String fileName : files) {
File fileToZip = new File(fileName);
FileInputStream fis = new FileInputStream(fileName);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zos.putNextEntry(zipEntry);
int bytesRead;
while ((bytesRead = fis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
fis.close();
fis.close();
}
zos.close();
return baos.toByteArray();
}
And here's the result I receive in the output stream:

date format error in mvc?

when i click button client side date format is working fine but server side date format is different
how to solve this problem?
[HttpPost]
public ActionResult CheckAvailabilityValue(MainModel check)
{
try
{
Get_Location();
//if (ModelState.IsValid)
//{
locationInformation checking = new locationInformation();
bool suc = checking.CheckAvailability(check);
if (suc == false)
{
return Json(new { success = true, message = "Checked successfully" }, JsonRequestBehavior.AllowGet);
}
else if (suc == true)
{
return Json(new { False = true, message = "Checked successfully" }, JsonRequestBehavior.AllowGet);
}
//}
}
catch
{
return View();
}
return View();
}
MainModel Class:
public class CheckingDetails
{
[Key]
public int BookingID { get; set; }
public int LocationID { get; set; }
public int FacilityID { get; set; }
public int VenueID { get; set; }
public int CapacityID { get; set; }
public DateTime BookedFromDate { get; set; }
public DateTime BookedToDate { get; set; }
public string FromTime { get; set; }
public string ToTime { get; set; }
}
Below i attached screen shot
public bool CheckAvailability(MainModel check)
{
bool flag = false;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["venue"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("spCheckAvailability", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BookedFromDate", Convert.ToDateTime(check.CheckMasters.BookedFromDate));
cmd.Parameters.AddWithValue("#BookedToDate", Convert.ToDateTime(check.CheckMasters.BookedToDate));
cmd.Parameters.AddWithValue("#FromTime", check.CheckMasters.FromTime);
cmd.Parameters.AddWithValue("#ToTime", check.CheckMasters.ToTime);
con.Open();
flag = Convert.ToBoolean(cmd.ExecuteScalar());
return flag;
}
}

Categories