POST between JApplet and Django webServer - java

I'm pretty new to Django and Japplet, this is my first project with them.
The Japplet takes some images from the django static folder, and permits the user to add some lines and markers.
At the end of this, when the button "save" on the JApplet is clicked, it should do some POST call to the Django server, to save the markes and lines.
Actually I'm only testing with markers, and I can't get it done.
Here is the Model of a marker:
class Point(models.Model):
id_edificio = models.ForeignKey(Building)
RFID = models.CharField(max_length=200)
x = models.IntegerField()
y = models.IntegerField()
piano = models.IntegerField()
ingresso = models.BooleanField()
His View:
def point(request, id_edificio, RFID, x, y, piano):
point = csrf_exempt(point)
if request.method == 'POST':
get_object_or_404(Building, pk=id_edificio)
p = Point()
p.id_edificio = id_edificio
p.RFID = RFID
p.x = x
p.y= y
p.piano = piano
p.ingresso = True
p.save()
I haven't implemented a template, because I don't need access to this view with web browser.
Urls:
url(r'^buildings/generate/point', 'buildings.views.point'),
JApplet save method:
private void saveData(MarkerArrayList markers, PathArrayList paths) {
String response;
URL endpoint = null;
try {
endpoint = new URL("http://127.0.0.1:8000/buildings/generate/point");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
for(Marker m: markers) {
Reader data = new StringReader("id_edificio="+id_building+"&"+m.toString());
try {
Post.postData(data, endpoint);
} catch (Exception e) {e.printStackTrace();}
}
}
Marker toString() method:
public String toString() {
return "RFID="+ RFID + "&" +
"x=" +
"y=" + y + "&" +
"piano=" + floor + "&";
}
I assume that my java method Post is correct. If you want to see it, ask me ;)
Error from Django server on POST:
[28/Sep/2012 07:21:46] "POST /buildings/generate/point HTTP/1.1" 403 2294
I don't know wath to try know, I'm in your hands.
Tahnk you

The number of errors was totally incredible.
So this is the new View for markers, for now I will ignore csrf token:
#csrf_exempt
def point(request):
if request.method == 'POST':
p = Point()
building = Building.objects.get(pk = request.POST["id_edificio"])
p.id_edificio = building
p.RFID = request.POST["RFID"]
p.x = request.POST["x"]
p.y= request.POST["y"]
p.piano = request.POST["piano"]
p.ingresso = request.POST["ingresso"]
p.save()
And it works! There was also minor errors in Marker toString() method (as 'X' instead of 'x'), but they were only minor errors.

Related

Speech Assessment in Java never returning insertions and omissions nor detecting speech end

for a project I am trying to use azure's speech assessment in java to assess how the user pronounces the words and if they announce it well. Currently I am using a approach that uses the listeners:
System.out.println("Starting recording with " + this.prompt);
PronunciationAssessmentConfig pronunciationAssessmentConfig = new PronunciationAssessmentConfig(this.getPrompt(),
PronunciationAssessmentGradingSystem.HundredMark, PronunciationAssessmentGranularity.Phoneme, true);
// PronunciationAssessmentConfig pronunciationAssessmentConfig = PronunciationAssessmentConfig.fromJson("{\"referenceText\":\"" + getPrompt() + "\",\"gradingSystem\":\"HundredMark\",\"granularity\":\"Phoneme\", \"miscue\":true}");
AudioConfig audioConfig = AudioConfig.fromDefaultMicrophoneInput();
SpeechUtil.SPEECH_CONFIG.setOutputFormat(OutputFormat.Detailed);
SpeechRecognizer speechRecognizer = new SpeechRecognizer(
SpeechUtil.SPEECH_CONFIG,
audioConfig);
pronunciationAssessmentConfig.applyTo(speechRecognizer);
speechRecognizer.startContinuousRecognitionAsync();
speechRecognizer.recognizing.addEventListener((o, speechRecognitionResultEventArgs) -> {
try {
final int words = speechRecognitionResultEventArgs.getResult().getText().split(" ").length;
System.out.println("Recognizing: " + speechRecognitionResultEventArgs.getResult().getText());
Platform.runLater(() -> this.controller.setSpoken(0, wordsReadToIndex(words)));
System.out.println(words);
System.out.println(pronunciationAssessmentConfig.getReferenceText());
System.out.println(speechRecognitionResultEventArgs.getResult().getProperties().getProperty(PropertyId.SpeechServiceResponse_JsonResult));
if (words >= pronunciationAssessmentConfig.getReferenceText().split(" ").length)
speechRecognizer.stopContinuousRecognitionAsync();
} catch (Throwable e) {
e.printStackTrace();
}
});
speechRecognizer.recognized.addEventListener((o, speechRecognitionEventArgs) -> {
System.out.println("Recognized!");
try {
PronunciationAssessmentResult pronunciationAssessmentResult =
PronunciationAssessmentResult.fromResult(speechRecognitionEventArgs.getResult());
if (pronunciationAssessmentResult == null) return;
System.out.println(pronunciationAssessmentResult.getAccuracyScore());
String jsonString = speechRecognitionEventArgs.getResult().getProperties().getProperty(PropertyId.SpeechServiceResponse_JsonResult);
System.out.println(jsonString);
Platform.runLater(() -> this.complete(new Score(pronunciationAssessmentResult.getAccuracyScore().intValue(), JsonParser.parseString(jsonString))));
speechRecognizer.stopContinuousRecognitionAsync();
} catch (Throwable e) {
e.printStackTrace();
}
});
//
speechRecognizer.speechEndDetected.addEventListener((o, speechRecognitionEventArgs) -> {
System.out.println("Speech end detected!");
});
however it does not detect any omissions or insertions even though it is turned on in the assessment settings. Neither does it ever detect a speech end.
*Result of saying 'Hello, could I buy one these books you are selling' with reference 'Hello, could I buy one of these books you are selling' *
https://pastebin.com/tvAVw4s3
I have tried the following example as well:
https://github.com/Azure-Samples/cognitive-services-speech-sdk/blob/master/samples/java/jre/console/src/com/microsoft/cognitiveservices/speech/samples/console/SpeechRecognitionSamples.java#L985 (The pronunciationAssessmentWithMicrophoneAsync() function)
but even this example adapted from the microsoft azure github repo never returns anything useful and when it does it is:
CANCELED: ErrorCode=ServiceTimeout
CANCELED: ErrorDetails=Timeout: no recognition result received SessionId: 09f1a5492851429e81e4672c90144a37
CANCELED: Did you update the subscription info?```
**EDIT:**
Ì have found out that it happens because of a noisy environment and pronunciationassessment, though it does return with the exact same code and environment without the pronunciationassessment.

How to get response from http and unsecured https site from Codename one's ConnectionRequest ? issue in http and https in Android 10 (In Google Pixel)

I am new to Codenameone , I am having strange issue in Codenameone's ConnectionRequest API while fetching response from https site in google pixel device in which anroid 10 is installed.
fetching from https site is working fine.
However in the simulator it is fine and also with the other device that has android less than version 10.
what could be the solution for this OR am i doing somthing worng?
Here is my code and error i am getting in device
First Tried :
TextArea resultTextArea = new TextArea();
Button download = new Button("RUN");
download.addActionListener((e) -> {
ConnectionRequest cr = new ConnectionRequest(url, false);
SliderBridge.bindProgress(cr, progress);
NetworkManager.getInstance().addToQueueAndWait(cr);
if (cr.getResponseCode() == 200) {
String resultString = "";
try {
byte[] initialArray = cr.getResponseData();
resultString = new String(initialArray);
resultTextArea.setText(resultString);
} catch (Exception eee) {
resultString = "Error => " + resultString + eee.getMessage();
}
System.out.println(resultString);
}
});
Second Try: where url = http://192.168.2.100:8084/semms-webservice/rest/device/test/users
public void testURLConnectionResponse(String url) {
ConnectionRequest request = new ConnectionRequest();
request.setContentType("application/json");
request.setUrl(url);
request.setHttpMethod("GET");
TextArea resultTextArea = new TextArea();
String result = "";
result = "RESPONSE CODE :- " + request.getResponseCode() + " --- ";
Response<String> resultx = Rest.put(url).getAsString();
result += resultx.getResponseData();
resultTextArea.setText(result);
Form hi = new Form("Test Connection Response", new BoxLayout(BoxLayout.Y_AXIS));
Button mainFormButton = new Button("Back To Main Form");
mainFormButton.addActionListener((e) -> mainForm());
mainFormButton.setRippleEffect(true);
hi.add(mainFormButton);
hi.show();
// request will be handled asynchronously
NetworkManager.getInstance().addToQueue(request);
}
enter code here
I'm assuming this works in the simulator and fails on the device?
There are multiple reasons this can happen but in this case it looks like a subnet IP address. You're trying to connect to an internal company URL from a device which is probably on the operator network. Try connecting to the URL via the browser and see if it's reachable by the device.
As a workaround you can connect to the company internal wifi and see if the server is reachable.

onPostExecute is called twice and showing double result

I am trying to download some files in background, for that I used download manager and I made this method:
/*** media download ***/
public long mediaDownload(ArrayList<DownloadedFile> arrayList, String foldPathName) {
long downloadReference = 0;
// Create request for android download manager
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
for (int i = 0; i < arrayList.size();i++){
DownloadManager.Request request = new DownloadManager.Request(arrayList.get(i).getUri());
request.setTitle("Data Download");
request.setDescription("New media");
//Set the local destination for the downloaded file to a path
//within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/" + folder_main + "/" + foldPathName, arrayList.get(i).getName());
File f = new File(Environment.DIRECTORY_DOWNLOADS + "/" + folder_main + "/" + foldPathName + "/" + arrayList.get(i).getName());
Log.e("File:",f.toString());
//Enqueue download and save into referenceId
downloadReference = downloadManager.enqueue(request);
}
return downloadReference;
}
I have a picture and a Video to download for test, and when checking downloaded file in Explorer I find 2 videos and 2 picture, debug that I found that onPostExecute method is called twice and I can't figure out why.
Here is my onPostExecute method:
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray region = null;
region = jsonObject.getJSONArray("regions");
Log.e("Regions:", String.valueOf(region.length()));
for (int i = 0; i < region.length(); i++) {
try {
JSONObject json_data = region.getJSONObject(i);
int height_view = Integer.parseInt(json_data.getString("height"));
int width_view = Integer.parseInt(json_data.getString("width"));
int left_view = Integer.parseInt(json_data.getString("left"));
int top_view = Integer.parseInt(json_data.getString("top"));
int right_view = Integer.parseInt(json_data.getString("right"));
int bottom_view = Integer.parseInt(json_data.getString("bottom"));
/**** Media in region ***/
JSONObject media = json_data.getJSONObject("media");
String type_media = media.getString("type");
url = media.getString("url");
name = media.getString("name");
uri = Uri.parse(url);
} catch (JSONException e) {
e.printStackTrace();
}
downloadedFiles.add(new DownloadedFile(name, uri));
}
Toast.makeText(MainActivity.this, "Layout Created with" + height + "x" + width, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("Downloaded Files:",downloadedFiles.toString());
mediaDownload(downloadedFiles, folderName); // region media's download
}
On my logcat I see that my arrayList has 2 elements, but displayed twice, which means files are downloaded twice so the onPostExecute method called 2 times, thanks for help.
I figured out after passing my time debugging all the code, when the activity is created it changes the screen orientation and so it creates a second instance, so my AsyncTask is called twice and thats why i thought onPosteExecute is called twice, thanks for everyone who tried to help.

Java - Variable number of variables

I wrote a code to find all URLs within a PDF file and replace the one(s) that matches the parameters that was passed from a PHP script.
It is working fine when a single URL is passed. But I don't know how to handle more than one URL, I'm guessing I would need a loop that reads the array length, and call the changeURL method passing the correct parameters.
I actually made it work with if Statements (if myarray.lenght < 4 do this, if it is < 6, do that, if < 8.....), but I am guessing this is not the optimal way. So I removed it and want to try something else.
Parameters passed from PHP (in this order):
args[0] - Location of original PDF
args[1] - Location of new PDF
args[2] - URL 1 (URL to be changed)
args[3] - URL 1a (URL that will replace URL 1)
args[4] - URL 2 (URL to be changed)
args[5] - URL 2a - (URL that will replace URL 2)
args...
and so on... up to maybe around 16 args, depending on how many URLs the PDF file contains.
Here's the code:
Main.java
public class Main {
public static void main(String[] args) {
if (args.length >= 4) {
URLReplacer.changeURL(args);
} else {
System.out.println("PARAMETER MISSING FROM PHP");
}
}
}
URLReplacer.java
public class URLReplacer {
public static void changeURL(String... a) {
try (PDDocument doc = PDDocument.load(a[0])) {
List<?> allPages = doc.getDocumentCatalog().getAllPages();
for (int i = 0; i < allPages.size(); i++) {
PDPage page = (PDPage) allPages.get(i);
List annotations = page.getAnnotations();
for (int j = 0; j < annotations.size(); j++) {
PDAnnotation annot = (PDAnnotation) annotations.get(j);
if (annot instanceof PDAnnotationLink) {
PDAnnotationLink link = (PDAnnotationLink) annot;
PDAction action = link.getAction();
if (action instanceof PDActionURI) {
PDActionURI uri = (PDActionURI) action;
String oldURL = uri.getURI();
if (a[2].equals(oldURL)) {
//System.out.println("Page " + (i + 1) + ": Replacing " + oldURL + " with " + a[3]);
uri.setURI(a[3]);
}
}
}
}
}
doc.save(a[1]);
} catch (IOException | COSVisitorException e) {
e.printStackTrace();
}
}
}
I have tried all sort of loops, but with my limited Java skills, did not achieve any success.
Also, if you notice any dodgy code, kindly let me know so I can learn the best practices from more experienced programmers.
Your main problem - as I understand -, is the "variable number of variables". And you have to send from PHP to JAVA.
1 you can transmit one by one as your example
2 or, in a structure.
there are several structures.
JSON is rather simple at PHP: multiple examples here:
encode json using php?
and for java you have: Decoding JSON String in Java.
or others (like XML , which seems too complex for this).
I'd structure your method to accept specific parameters. I used map to accept URLs, a custom object would be another option.
Also notice the way loops are changed, might give you a hint on some Java skills.
public static void changeURL(String originalPdf, String targetPdf, Map<String, String> urls ) {
try (PDDocument doc = PDDocument.load(originalPdf)) {
List<PDPage> allPages = doc.getDocumentCatalog().getAllPages();
for(PDPage page: allPages){
List annotations = page.getAnnotations();
for(PDAnnotation annot : page.getAnnotations()){
if (annot instanceof PDAnnotationLink) {
PDAnnotationLink link = (PDAnnotationLink) annot;
PDAction action = link.getAction();
if (action instanceof PDActionURI) {
PDActionURI uri = (PDActionURI) action;
String oldURL = uri.getURI();
for (Map.Entry<String, String> url : urls.entrySet()){
if (url.getKey().equals(oldURL)) {
uri.setURI(url.getValue());
}
}
}
}
}
}
doc.save(targetPdf);
} catch (IOException | COSVisitorException e) {
e.printStackTrace();
}
}
If you have to get the URL and PDF locations from command line, then call the changeURL function like this:
public static void main(String[] args) {
if (args.length >= 4) {
String originalPdf = args[0];
String targetPdf = args[1];
Map<String, String> urls = new HashMap<String, String>();
for(int i = 2; i< args.length; i+=2){
urls.put(args[i], args[i+1]);
}
URLReplacer.changeURL(originalPdf, targetPdf, urls);
} else {
System.out.println("PARAMETER MISSING FROM PHP");
}
}
Of the top of my head, you could do something like this
public static void main(String[] args) {
if (args.length >= 4 && args.length % 2 == 0) {
for(int i = 2; i < args.length; i += 2) {
URLReplacer.changeURL(args[0], args[1], args[i], args[i+1]);
args[0] = args[1];
}
} else {
System.out.println("PARAMETER MISSING FROM PHP");
}
}

JSONObject.toString() returns OutOfMemoryError

I have an Android app.
First, the app do sync process. In this process, the server sends to the device an JSON object as String by which it can build the available questionnaires.
GetQuestionnairesResponse.java:
public class GetQuestionnairesResponse extends ResponseHandler
{
public GetQuestionnairesResponse(String result, AsyncRequest request)
{
super(result, request);
}
#Override
public void handleResponse()
{
DataSyncActivity caller = (DataSyncActivity) request.getCaller();
BackgroundManager bckMng = BackgroundManager.getInstance(caller);
PreferencesManager preference = PreferencesManager.getInstance(null);
boolean status = true;
int numOfWrongJsonVer = 0;
int totalNumOfQuestionnaires = 0;
// Handle data from server
// Creating JSON Parser instance
try
{
QuestionnaireDataSource questionnaireDS = new QuestionnaireDataSource(caller);
questionnaireDS.open();
JSONArray jArr = new JSONArray(result);
JSONObject j = null;
totalNumOfQuestionnaires = jArr.length();
for (int i = 0; i < jArr.length(); i++)
{
j = jArr.getJSONObject(i);
long questId = j.getLong("questionnaireId");
long surveyId = j.getLong("surveyId");
String questName = j.getString("name");
String desc = j.getString("description");
int version = j.getInt("questionnaireVersion");
int jsonVersion = j.getInt("jsonVersion");
if (jsonVersion == PreferencesManager.jsonVersion)
{
// Save the pages part
String filename = questId + "_" + version + "_" + jsonVersion + ".json";
HelpFunctions.writeJSON(filename, j.toString());
Questionnaire quest = questionnaireDS.createQuestionnaire(questId, questName, desc, surveyId, version, jsonVersion, filename);
if (quest == null)
throw new RuntimeException("Cant save the questionnaire: " + questName);
}
else
{
numOfWrongJsonVer ++;
}
}
questionnaireDS.close();
}
catch (Exception e)
{
status = false;
if (e.getMessage() != null)
Log.e(TAG, e.getMessage());
}
caller.setInSync(false);
...
}
The result i get from the server i parse it to Json array.
The result in some cases can bee 3 megabytes.
The solution I found was to add an attribute in manifest.xml:
android:largeHeap="true"
It solved the problem. I don't know why but the problem returned again in the last day.
I will be happy to get suggestions how to solve the problem.
The problem is that the json object not parsed as expected so it
If the JSON was originally 3 MB and you call toString() on the JSONObject parsed from it, the JSONObject is still taking up memory, plus it's going to need to do a 3 MB allocation to hold the String. You may not have that much memory available.
But the thing about OutOfMemoryError is that the allocation that uses up the last bit of RAM isn't necessarily to blame for there being so little RAM available. Big allocations are just more likely to be the thing that pushes it over the edge. It's likely that you have a memory leak somewhere else in your app, and you'll need to use a tool like Eclipse MAT to find it.

Categories

Resources