Calling a java jar method via mid server probe designed in javascript - javascript

I'm setting up an environment where I pass 4 parameters (Encrypted file, Key File, Pass Phase and Default File name) to a .Jar and it decrypts the file.
I have achieved it via Bouncycastle API and it works fine on the eclipse IDE.
Now I have to set this up in my servicenow mid-server.
So the javascript probe should call this jar file and pass the parameters as strings and the encrypted file (which resides on the mid-server) gets decrypted.
I have tried creating a mid-server script include in servicenow and a probe but it returns with an error that the method is not found (which is actually there)
CLASS INSIDE .JAR
package pgpDecrypt;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Iterator;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.CompressionAlgorithmTags;
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory;
import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator;
import org.bouncycastle.util.io.Streams;
public class PGPDecryption {
public static void decryptFile(String inputFileName, String keyFileName, char[] passwd, String defaultFileName)
throws IOException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
decryptFiles(in, keyIn, passwd, defaultFileName);
System.out.print("Default File Name : "+ defaultFileName);
keyIn.close();
in.close();
}
/**
* decrypt the passed in message stream
*/
public static void decryptFiles(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName)
throws IOException, NoSuchProviderException {
in = PGPUtil.getDecoderStream(in);
try {
JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
new JcaKeyFingerprintCalculator());
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = PGPUtilE.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
}
if (sKey == null) {
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear = pbe
.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData) plainFact.nextObject();
InputStream compressedStream = new BufferedInputStream(cData.getDataStream());
JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(compressedStream);
Object message = pgpFact.nextObject();
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
String outFileName = ld.getFileName();
if (outFileName.length() == 0) {
outFileName = defaultFileName;
}
InputStream unc = ld.getInputStream();
OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName));
Streams.pipeAll(unc, fOut);
fOut.close();
} else if (message instanceof PGPOnePassSignatureList) {
throw new PGPException("encrypted message contains a signed message - not literal data.");
} else {
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected()) {
if (!pbe.verify()) {
System.err.println("message failed integrity check");
} else {
System.err.println("message integrity check passed");
}
} else {
System.err.println("no message integrity check");
}
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
}
}
private static void encryptFile(String outputFileName, String inputFileName, String encKeyFileName, boolean armor,
boolean withIntegrityCheck) throws IOException, NoSuchProviderException, PGPException {
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName));
PGPPublicKey encKey = PGPUtilE.readPublicKey(encKeyFileName);
encryptFile(out, inputFileName, encKey, armor, withIntegrityCheck);
out.close();
}
private static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor,
boolean withIntegrityCheck) throws IOException, NoSuchProviderException {
if (armor) {
out = new ArmoredOutputStream(out);
}
try {
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5).setWithIntegrityPacket(withIntegrityCheck)
.setSecureRandom(new SecureRandom()).setProvider("BC"));
cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));
OutputStream cOut = cPk.open(out, new byte[1 << 16]);
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(cOut), PGPLiteralData.BINARY, new File(fileName),
new byte[1 << 16]);
comData.close();
cOut.close();
if (armor) {
out.close();
}
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
if (args.length == 0) {
System.err.println(
"usage: PGPDecryption -d file [secretKeyFile passPhrase|pubKeyFile]");
return;
}
if (args[0].equals("-e")) {
if (args[1].equals("-a") || args[1].equals("-ai") || args[1].equals("-ia")) {
encryptFile(args[2] + ".asc", args[2], args[3], true, (args[1].indexOf('i') > 0));
} else if (args[1].equals("-i")) {
encryptFile(args[2] + ".bpg", args[2], args[3], false, true);
} else {
encryptFile(args[1] + ".bpg", args[1], args[2], false, false);
}
} else if (args[0].equals("-d")) {
decryptFile(args[1], args[2], args[3].toCharArray(), new File(args[1]).getName() + ".out");
} else {
System.err.println(
"usage: PGPDecryption -d|-e [-a|ai] file [secretKeyFile passPhrase|pubKeyFile]");
}
}
}
SCRIPT INCLUDE :
var ProcessPGP = Class.create();
ProcessPGP.prototype = {
initialize: function() {
this.Pgp = Packages.pgpDecrypt.PGPDecryption.decryptFile;
this.inputFile = probe.getParameter("inputFile");
this.secretFile = probe.getParameter("secretFile");
this.passPhase = probe.getParameter("passPhase");
this.defaultName = probe.getParameter("defaultName");
},
execute: function() {
var pgpObj = new this.Pgp(this.inputFile, this.secretFile, this.passPhase, this.defaultName);
},
type: ProcessPGP
};
PROBE :
var jspr = new JavascriptProbe('ANIRUDGU-68LCS_Dev1');
jspr.setName('TestPGPDemo5');
jspr.setJavascript('var pdf = new ProcessPGP(); res = pdf.execute();');
jspr.addParameter("inputFile", "C:\Users\anirudgu\Desktop\PGPTestKey\TestRun2.pgp");
jspr.addParameter("secretFile", "C:\Users\anirudgu\Desktop\PGPTestKey\anirudguciscocomprivate.asc");
jspr.addParameter("passPhase", "Hello");
jspr.addParameter("defaultName", "FilefromProbe");
jspr.create();
But I am facing the below mentioned error :
08/22/19 23:21:58 (097) Worker-Standard:JavascriptProbe-ce4567ebdb9b330045bb9b81ca961910 WARNING *** WARNING *** org.mozilla.javascript.EvaluatorException: Can't find method pgpDecrypt.PGPDecryption.decryptFile(java.lang.String,java.lang.String,java.lang.String,java.lang.String). (script_include:ProcessPGP; line 32)
EvaluatorException(var pdf = new ProcessPGP(); res = pdf.execute();)

The method decryptFile is static. The new keyword can only be used to create instances.
Therefore, try:
var pgpObj = this.Pgp(this.inputFile, this.secretFile, this.passPhase, this.defaultName);

Try to remove "new" from:
jspr.setJavascript('var pdf = new ProcessPGP(); res =
pdf.execute();');

Related

Redirect in AJAX in Android WebClient

I found that window.location = '/Mobile/Main'; does not work in WebChromeClient. I mean it does not redirect to the page but it work fine under any PC internet browser.
I have tried
history.pushState(null, '', '#Url.Action("Main", "Mobile")');
window.open('#Url.Action("Main", "Mobile")');
And it does not redirect as it works normally.
How to fix it?
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (data) {
if (data.success === true) {
// It does not redirect in Android WebClient
window.location = '/Mobile/Main';
}
else {
$('#msgModalBody').html(data.msg);
$('#msgModal').modal({
keyboard: false
});
}
},
error: function (jqXHR, exception) {
}
}).done(function (data) {
// It does not redirect in Android WebClient
window.location = '/Mobile/Main';
});
Java
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.GeolocationPermissions;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ValueCallback<Uri[]> mUploadMessage;
private String mCameraPhotoPath;
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private WebSettings webSettings;
private long size = 0;
// Storage Permissions variables
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
try {
String file_path = mCameraPhotoPath.replace("file:","");
File file = new File(file_path);
size = file.length();
}catch (Exception e){
Log.e("Error!", "Error while opening image file" + e.getLocalizedMessage());
}
if (data != null || mCameraPhotoPath != null) {
Integer count = 0; //fix fby https://github.com/nnian
ClipData images = null;
try {
images = data.getClipData();
}catch (Exception e) {
Log.e("Error!", e.getLocalizedMessage());
}
if (images == null && data != null && data.getDataString() != null) {
count = data.getDataString().length();
} else if (images != null) {
count = images.getItemCount();
}
Uri[] results = new Uri[count];
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (size != 0) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else if (data.getClipData() == null) {
results = new Uri[]{Uri.parse(data.getDataString())};
} else {
for (int i = 0; i < images.getItemCount(); i++) {
results[i] = images.getItemAt(i).getUri();
}
}
}
mUploadMessage.onReceiveValue(results);
mUploadMessage = null;
}
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have read or write permission
int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
int cameraPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title
getSupportActionBar().hide(); //hide the title bar
setContentView(R.layout.activity_main);
verifyStoragePermissions(this);
webView = (WebView)findViewById(R.id.website);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webSettings = webView.getSettings();
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowFileAccess(true);
// Очищать весь кэш https://stackoverflow.com/questions/2465432/android-webview-completely-clear-the-cache
webSettings.setSaveFormData(false);
webSettings.setCacheMode(webSettings.LOAD_NO_CACHE);
webView.clearHistory();
webView.clearFormData();
webView.clearCache(true);
// Javascript inabled on webview
//webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
//webView.getSettings().setLoadWithOverviewMode(true);
//Other webview settings
//webView.getSettings().setGeolocationEnabled(true);
//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
//webView.setScrollbarFadingEnabled(false);
//webView.getSettings().setBuiltInZoomControls(true);
//webView.getSettings().setAllowFileAccess(true);
//webView.getSettings().setSupportZoom(true);
//webView.getSettings().setLoadWithOverviewMode(true);
//webView.getSettings().setUseWideViewPort(true);
//webView.getSettings().setAllowContentAccess(true);
//webView.getSettings().setAllowFileAccessFromFileURLs(true);
//webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
//webView.getSettings().setDomStorageEnabled(true);
//webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//webView.getSettings().setAppCacheEnabled(true);
// webView.setWebViewClient(new WebViewClient());
webView.setWebViewClient(new Client());
webView.setWebChromeClient(new ChromeClient());
//if SDK version is greater of 19 then activate hardware acceleration otherwise activate software acceleration
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
/* context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");*/
//Load url in webview
webView.loadUrl("http://172.16.10.3:7777");
}
//helper method for clearCache() , recursive
//returns number of deleted files
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir!= null && dir.isDirectory()) {
try {
for (File child:dir.listFiles()) {
//first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
//then delete the files and subdirectories in this dir
//only empty directories can be deleted, so subdirs have been done first
if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
}
catch(Exception e) {
Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
}
}
return deletedFiles;
}
/*
* Delete the files older than numDays days from the application cache
* 0 means all files.
*/
public static void clearCache(final Context context, final int numDays) {
Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days", numDays));
int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
public class ChromeClient extends WebChromeClient {
// For Android 5.0+
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = filePath;
Log.e("FileCooserParams => ", filePath.toString());
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[2];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(Intent.createChooser(chooserIntent, "Select images"), 1);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
public class Client extends WebViewClient {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// If url contains mailto link then open Mail Intent
if (url.contains("mailto:")) {
// Could be cleverer and use a regex
//Open links in new browser
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// Here we can open new activity
return true;
}else {
// Stay within this webview and load url
view.loadUrl(url);
return true;
}
}
//Show loader on url load
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Then show progress Dialog
// in standard case YourActivity.this
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Загружается...");
progressDialog.show();
}
}
// Called when all page resources loaded
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:(function(){ " +
"document.getElementById('android-app').style.display='none';})()");
try {
// Close progressDialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
Huh! :)
Mega solution I just have found.
We have to simulate to post an empty form.
HTML
<form id="myForm" action='#Url.Action("Details","Main")'></form>
JS
document.getElementById("myForm").submit();
instead of
window.location = '/Mobile/Main';
That does the trick!

ERR_INCOMPLETE_CHUNKED_ENCODING on angularjs - rest service returns an infinite json file using Advanced REST Client but error in postman

I have a very strange problem. In angular (app built with ionic v1) I call some REST call built in java, but something goes wrong and chrome advise me with this error:
The code interesting is this, a REST service in angular js:
bankaccountsbyuser: function(_getbauser, _error){
var currentToken = _GetToken();
if(currentToken!=null){
var Headers = {
token: currentToken.tokenUser,
};
}
_timerTokenControl(currentToken, _error);
if (setupTime == null) {
console.log("token scaduto");
//modificare
//$window.location.href="login.html";
}
if (currentToken !== null) {
$http({
method : 'GET',
headers: Headers,
url : REST_URL+'bankaccount'
}).then(function successCallback(response) {
console.log(response)
_getbauser(response)
}, function errorCallback(response) {
console.log(response.statusText);
});
} else {
var alertPopup = $ionicPopup.alert({
title: 'Accesso negato!',
template: 'Devi essere un utente registrato, non sei loggato!'
});
console.log("NON SEI LOGGATO!!!");
}
},
debug:
How you can see, the get REST service returns an error, thus, let's see this REST service built in java:
package it.jack.fdd.services;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import it.jack.fdd.dao.FactoryDao;
import it.jack.fdd.dao.impl.BankAccountDaoImpl;
import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.User;
import it.jack.fdd.dto.TokenUserDto;
import it.jack.fdd.dto.UserDto;
import it.jack.fdd.util.ConverterDTO;
#Path("/bankaccount")
public class BankAccountServices {
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<BankAccount> getBankAccountOfUser() {
BankAccountDao baDao = new BankAccountDaoImpl();
List<BankAccount> balist = baDao.getBAByUserId(1);
return balist;
}
I tryed to pass the number "1" in the method, just to simplify. The method is implemented below:
package it.jack.fdd.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.Staff;
import it.jack.fdd.domain.User;
import it.jack.fdd.util.HibernateUtilLezione;
public class BankAccountDaoImpl extends BaseDaoImpl<BankAccount> implements BankAccountDao{
public List<BankAccount> getBAByUserId(int id) {
try{
Session session = HibernateUtilLezione.openSession();
Transaction tx = session.beginTransaction();
#SuppressWarnings("unchecked")
List<BankAccount> accounts = session.createQuery("from BankAccount b "
+ "where b.user= "+id).list();
tx.commit();
session.close();
return accounts;
}
catch(HibernateException e){
e.printStackTrace();
return null;
}
}
}
As you can see, the method ask for an id, and I put id 1 just to check, because in the database there is a field with that id. Trying in java, it returns me a list
[it.jack.fdd.domain.BankAccount#4f8d86e4]
And I checked also that the list has dimension 1 (thus, only one record, like in the database, only 1 record with that iduser)
Thus, trying to open this REST call using postman, the result is this:
The strange thing is that postman show me the same result to another REST call, that it worked before. But for this last REST call is not a problem, because strangely it works on my application, it doesn't work only in postman.
Thus, trying with Advanced REST Client I have a strange different result:
A strange, very big list that repeat every time the same field!! It is like a loop!
What happens? How I can solve?
Solved. The problem was in java's domain classes: when a domain class has a one-to-many relationship it's mandatory to put the tag #JsonIgnore to avoid these recurrent records in json file
Entity class:
package it.jack.fdd.domain;
// Generated 30-nov-2016 0.17.09 by Hibernate Tools 4.3.1.Final
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* BankAccount generated by hbm2java
*/
#Entity
#Table(name = "bank_account", catalog = "fdd_dbproducts")
public class BankAccount implements java.io.Serializable {
private Integer idbankAccount;
private User user;
private String iban;
private String pin;
private String society;
private Date expiration;
public BankAccount() {
}
public BankAccount(User user, String iban, String pin, String society) {
this.user = user;
this.iban = iban;
this.pin = pin;
this.society = society;
}
public BankAccount(User user, String iban, String pin, String society, Date expiration) {
this.user = user;
this.iban = iban;
this.pin = pin;
this.society = society;
this.expiration = expiration;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "idbank_account", unique = true, nullable = false)
public Integer getIdbankAccount() {
return this.idbankAccount;
}
public void setIdbankAccount(Integer idbankAccount) {
this.idbankAccount = idbankAccount;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "fkuser_baccount", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
#Column(name = "iban", nullable = false, length = 45)
public String getIban() {
return this.iban;
}
public void setIban(String iban) {
this.iban = iban;
}
#Column(name = "pin", nullable = false, length = 45)
public String getPin() {
return this.pin;
}
public void setPin(String pin) {
this.pin = pin;
}
#Column(name = "society", nullable = false, length = 45)
public String getSociety() {
return this.society;
}
public void setSociety(String society) {
this.society = society;
}
#Temporal(TemporalType.DATE)
#Column(name = "expiration", length = 10)
public Date getExpiration() {
return this.expiration;
}
public void setExpiration(Date expiration) {
this.expiration = expiration;
}
}

Cordova custom plugin with third party native android library not working

In my cordova project, I need to use native code that scan via scan device on PDA, not by camera. I have working native android project and I changed it to android library project. Then I copied res, src, project.properties and AndroidManifest.xml files into myCordovaPlugin-> src-> android-> LibraryProject. When I build my cordova app in Ripple, there is no error. But when I build in device, I'm getting this error message. "Error 102 cmd: Command failed with exit code 8". I tried some solutions that I found online. But still the error is there.
Please help me. I'm very new to cordova and this is my first applicaton. I'm very appreciate any help. Thank you.
Here is Scanner.java.
package com.customplugin.barcodescanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import android.util.Log;
public class Scanner extends CordovaPlugin {
public static final int REQUEST_CODE = 1;
private static final String SCAN_INTENT = com.adlink.sample.SDK.SCAN;
private CallbackContext callbackContext;
public Scanner() {
}
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
this.callbackContext = callbackContext;
if (action.equals(SCAN)) {
scan(args);
} else {
return false;
}
return true;
}
}
public void scan(JSONArray args) {
Intent intentScan = new Intent(SCAN_INTENT);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// add config as intent extras
if(args.length() > 0) {
JSONObject obj;
JSONArray names;
String key;
Object value;
for(int i=0; i<args.length(); i++) {
try {
obj = args.getJSONObject(i);
} catch(JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
continue;
}
names = obj.names();
for(int j=0; j<names.length(); j++) {
try {
key = names.getString(j);
value = obj.get(key);
if(value instanceof Integer) {
intentScan.putExtra(key, (Integer)value);
} else if(value instanceof String) {
intentScan.putExtra(key, (String)value);
}
} catch(JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
continue;
}
}
}
}
// avoid calling other phonegap apps
intentScan.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName());
this.cordova.startActivityForResult((CordovaPlugin) this, intentScan, REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, intent.getStringExtra("SCAN_RESULT"));
obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT"));
obj.put(CANCELLED, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "This should never happen");
}
//this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
this.callbackContext.success(obj);
} else if (resultCode == Activity.RESULT_CANCELED) {
JSONObject obj = new JSONObject();
try {
obj.put(TEXT, "");
obj.put(FORMAT, "");
obj.put(CANCELLED, true);
} catch (JSONException e) {
Log.d(LOG_TAG, "This should never happen");
}
//this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
this.callbackContext.success(obj);
} else {
//this.error(new PluginResult(PluginResult.Status.ERROR), this.callback);
this.callbackContext.error("Unexpected error");
}
}
}
/**
* Initiates a barcode encode.
*
* #param type Endoiding type.
* #param data The data to encode in the bar code.
*/
public void encode(String type, String data) {
Intent intentEncode = new Intent(ENCODE_INTENT);
intentEncode.putExtra(ENCODE_TYPE, type);
intentEncode.putExtra(ENCODE_DATA, data);
// avoid calling other phonegap apps
intentEncode.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName());
this.cordova.getActivity().startActivity(intentEncode);
}
}
And here is Scanner.js.
cordova.define('cordova/plugin/Scanner', function(require, exports, module) {
var exec = require("cordova/exec");
/**
* Empty constructor
*/
var customScanner = function() {
};
customScanner.prototype.scan=
function (successCallback, errorCallback) {
exec(successCallback,
errorCallback,
"Scanner",
"scan",
[]);
}
module.exports = new customScanner();
});
Here is plugin call from onDeviceReady function of index.js.
var Scanner = cordova.require("cordova/plugin/Scanner");
Scanner.scan();
Here is my Native ScannerActivity.java.
package com.mypackage.sample.SDK;
import com.mypackage.sample.SDK.ENGINE;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnDismissListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.RadioButton;
import android.widget.TextView;
public class ScanActivity extends Activity implements OnClickListener
{
private static FakeR fakeR;
private static final String TAG = "ScanActivity";
private static final int DIALOG_WAITTING = 2;
private BroadcastReceiver m_msgReceiver = null;
private DBaseUtil m_db = null;
private SparseArray<Boolean> m_engineSupported = null;
private TextView m_btnScan = null;
private RadioButton m_rbBarcode1D = null;
private RadioButton m_rbBarcodeCCD = null;
private TextView m_scanSymbology = null;
private TextView m_scanSize = null;
private TextView m_scanValue = null;
private TextView m_scanElapse = null;
private boolean m_inProgress = false;
private boolean m_scanStarted = false;
private int m_nextEngine = ADMSG.ENGINE.None;
private ProgressDialog m_dlgProgress = null;
private boolean m_showMoreInfo = false;
private long m_scanStartTime = 0;
private int m_scanMode = ADMSG.SCANMODE.ONETIME;
private int m_scanKeycode = -1;
#Override
public void onCreate(Bundle savedInstanceState)
{
fakeR = new FakeR(this);
super.onCreate(savedInstanceState);
setContentView(fakeR.getId("layout", "scan_main"));
m_db = new DBaseUtil(this);
m_engineSupported = new SparseArray<Boolean>();
decideScanEngine();
boolean Barcode1D_enabled = engineEnabled(ADMSG.ENGINE.Barcode_1D);
boolean BarcodeCCD_enabled = engineEnabled(ADMSG.ENGINE.Barcode_CCD);
Log.d(TAG, "onCreate - Barcode_1D="+Barcode1D_enabled+", Barcode_CCD="+BarcodeCCD_enabled);
if(!Barcode1D_enabled && !BarcodeCCD_enabled)
{
showDialog_noSupportedEngine();
}
m_btnScan = (TextView)findViewById(fakeR.getId("id", "btnScan"));
m_btnScan.setOnClickListener(this);
//m_btnScan.setOnKeyListener(this);
m_rbBarcode1D = setEngineSwitch(fakeR.getId("id", "Reader_Barcode_1D"), Barcode1D_enabled);
m_rbBarcodeCCD = setEngineSwitch(fakeR.getId("id", "Reader_Barcode_CCD"), BarcodeCCD_enabled);
m_scanKeycode = getBgScanKeycode();
//Log.d(TAG, "onCreate - scanKeycode="+m_scanKeycode);
int currentEngine = checkAndCorrectEngine(m_db.getCurrentEngine());
Log.d(TAG, "onCreate - currentEngine="+currentEngine);
switch(currentEngine)
{
case ADMSG.ENGINE.Barcode_1D: m_rbBarcode1D.setChecked(true); break;
case ADMSG.ENGINE.Barcode_CCD: m_rbBarcodeCCD.setChecked(true); break;
}
m_scanSymbology = (TextView)findViewById(fakeR.getId("id", "scan_symbology"));
//m_scanSymbology.setVisibility((m_rbBarcodeCCD.isChecked())?(View.GONE):(View.VISIBLE));
if(m_showMoreInfo)
{
m_scanSize = (TextView)findViewById(fakeR.getId("id", "scan_size"));
m_scanSize.setVisibility(View.VISIBLE);
m_scanElapse = (TextView)findViewById(fakeR.getId("id", "scan_elapse"));
m_scanElapse.setVisibility(View.VISIBLE);
}
m_scanValue = (TextView)findViewById(fakeR.getId("id", "scan_value"));
m_scanValue.setMovementMethod(new ScrollingMovementMethod());
}
#Override
public void onRestart()
{
Log.d(TAG, "onRestart");
super.onRestart();
m_scanSymbology.setText(null);
m_scanValue.setText(null);
if(m_scanSize != null)
{
m_scanSize.setText(null);
}
if(m_scanElapse != null)
{
m_scanElapse.setText(null);
}
}
#Override
public void onResume()
{
Log.d(TAG, "onResume");
super.onResume();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
if(pref != null)
{
m_scanMode = (pref.getBoolean("_System_ScanMode_Continuous_", false))?(ADMSG.SCANMODE.CONTINUOUS):(ADMSG.SCANMODE.ONETIME);
}
switch(m_db.getCurrentEngine())
{
case ADMSG.ENGINE.Barcode_1D: m_rbBarcode1D.setChecked(true); break;
case ADMSG.ENGINE.Barcode_CCD: m_rbBarcodeCCD.setChecked(true); break;
}
disableBgScanMode();
enableFgScanMode();
registerMessageReceivers();
}
#Override
public void onPause()
{
Log.d(TAG, "onPause");
unregisterMessageReceivers();
disableFgScanMode();
enableBgScanMode();
setScanButtonState(false);
super.onPause();
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
if(keyCode == m_scanKeycode)
{
onClick(m_btnScan);
return(true);
}
return(super.onKeyUp(keyCode, event));
}
#Override
public void onClick(View view)
{
if(view == m_btnScan)
{
if(m_inProgress)
{
if(m_scanMode == ADMSG.SCANMODE.CONTINUOUS)
{
stopScan();
}
}
else
{
startScan();
}
}
else if(view == m_rbBarcode1D)
{
changeEngine(ADMSG.ENGINE.Barcode_1D);
}
else if(view == m_rbBarcodeCCD)
{
changeEngine(ADMSG.ENGINE.Barcode_CCD);
}
}
private void decideScanEngine()
{
boolean enable_1D = m_db.getEngineSupported(ADMSG.ENGINE.Barcode_1D);
boolean enable_CCD = m_db.getEngineSupported(ADMSG.ENGINE.Barcode_CCD);
m_engineSupported.put(ADMSG.ENGINE.Barcode_1D, enable_1D);
m_engineSupported.put(ADMSG.ENGINE.Barcode_CCD, enable_CCD);
int currentEngine = m_db.getCurrentEngine();
Log.d(TAG, "decideScanEngine - currentEngine="+currentEngine);
if(!isValidEngine(currentEngine))
{
m_db.setCurrentEngine(checkAndCorrectEngine(currentEngine));
}
}
private boolean engineEnabled(int id)
{
return(m_engineSupported.get(id));
}
private boolean isValidEngine(int engine)
{
return((engine == ENGINE.Barcode_1D) || (engine == ENGINE.Barcode_CCD));
}
private int checkAndCorrectEngine(int engine)
{
int validEngine = engine;
/*
if(!isValidEngine(validEngine))
{
validEngine = m_db.getCurrentEngine();
}
*/
if(!isValidEngine(validEngine))
{
if(engineEnabled(ADMSG.ENGINE.Barcode_CCD))
{
validEngine = ADMSG.ENGINE.Barcode_CCD;
}
else if(engineEnabled(ADMSG.ENGINE.Barcode_1D))
{
validEngine = ADMSG.ENGINE.Barcode_1D;
}
else
{
validEngine = ADMSG.ENGINE.None;
}
}
Log.d(TAG, "checkAndCorrectEngine - validEngine="+validEngine);
return(validEngine);
}
private RadioButton setEngineSwitch(int resId, boolean enabled)
{
RadioButton rb = (RadioButton)findViewById(resId);
if(rb != null)
{
rb.setOnClickListener(this);
if(!enabled)
{
rb.setVisibility(View.GONE);
}
}
return(rb);
}
private void registerMessageReceivers()
{
if(m_msgReceiver == null)
{
m_msgReceiver = new MessageReceiver();
}
IntentFilter filter = new IntentFilter();
filter.addAction(ADMSG.ACTION.OBTAIN_SCAN_DATA);
filter.addAction(ADMSG.ACTION.ENGINE_STATE_CHANGED);
registerReceiver(m_msgReceiver, filter);
}
private void unregisterMessageReceivers()
{
if(m_msgReceiver != null)
{
unregisterReceiver(m_msgReceiver);
}
}
private class MessageReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Log.d(TAG, "onReceive - action="+action);
if(ADMSG.ACTION.OBTAIN_SCAN_DATA.equals(action))
{
String value = intent.getStringExtra(ADMSG.KEY.SCAN.VALUE);
String symbology = intent.getStringExtra(ADMSG.KEY.SCAN.SYMBOLOGY);
boolean finished = intent.getBooleanExtra(ADMSG.KEY.SCAN.FINISHED, true);
Log.d(TAG, "\tvalue="+value);
m_scanSymbology.setText(symbology);
m_scanValue.setText(value);
m_scanValue.scrollTo(0, 0);
if(m_scanSize != null)
{
int dataCnt = (value != null)?(value.length()):(0);
m_scanSize.setText(String.format("%d", dataCnt));
}
if(m_scanElapse != null)
{
long elapse = SystemClock.elapsedRealtime() - m_scanStartTime;
m_scanElapse.setText(String.format("%dms", elapse));
}
setScanButtonState(!finished);
}
else if(ADMSG.ACTION.ENGINE_STATE_CHANGED.equals(action))
{
Bundle extras = intent.getExtras();
if(extras == null)
{
return;
}
int currentEngine = m_db.getCurrentEngine();
int state = extras.getInt(ADMSG.KEY.ENGINE.STATE);
boolean engineChanged = extras.getBoolean(ADMSG.KEY.ENGINE.CHANGED);
Log.d(TAG, "onReceive - ENGINE_STATE_CHANGED - state="+state+", engineChanged="+engineChanged);
if(state == ADMSG.ENGINE.STATE.STARTED)
{
showInitEngineProgress(false);
}
else if((state == ADMSG.ENGINE.STATE.STARTING) ||
(state == ADMSG.ENGINE.STATE.STOPPING))
{
}
else if(state == ADMSG.ENGINE.STATE.STOPPED)
{
Log.d(TAG, "\tSTOPPED - engine: "+currentEngine+" -> "+m_nextEngine);
if((m_nextEngine == currentEngine) ||
!isValidEngine(m_nextEngine))
{
return;
}
m_db.setCurrentEngine(checkAndCorrectEngine(currentEngine));
m_nextEngine = ADMSG.ENGINE.None;
}
}
}
}
private void setScanMode(boolean bgScan, boolean enable)
{
Log.d(TAG, "setScanMode - bgScan="+bgScan+", enable="+enable);
Intent in = new Intent();
in.setAction((bgScan)?(ADMSG.ACTION.BGSCAN_MODE):(ADMSG.ACTION.FGSCAN_MODE));
in.putExtra(ADMSG.KEY.SCAN.COMMAND, (enable)?(ADMSG.CMD.ENABLE):(ADMSG.CMD.DISABLE));
in.putExtra(ADMSG.KEY.REQUESTER.PACKAGE, getPackageName());
in.putExtra(ADMSG.KEY.REQUESTER.CLASS, getClass().getName());
in.putExtra(ADMSG.KEY.SCAN.MODE, m_scanMode);
if(m_scanMode == ADMSG.SCANMODE.CONTINUOUS)
{
in.putExtra(ADMSG.KEY.SCAN.OPT.CS.FIXED_PERIOD, false);
in.putExtra(ADMSG.KEY.SCAN.OPT.CS.IGNORE_SAME_ONE, true);
in.putExtra(ADMSG.KEY.SCAN.OPT.CS.STOP_IF_SUCCESS, true);
in.putExtra(ADMSG.KEY.SCAN.OPT.CS.TIME_INTERVAL, 1500);
}
//in.putExtra(ADMSG.KEY.BGSCAN_KEYCODE, KeyEvent.KEYCODE_ENTER);
sendBroadcast(in);
}
private void enableBgScanMode()
{
setScanMode(true, true);
}
private void disableBgScanMode()
{
setScanMode(true, false);
}
private void enableFgScanMode()
{
setScanMode(false, true);
}
private void disableFgScanMode()
{
setScanMode(false, false);
}
private void startScan()
{
m_scanSymbology.setText(null);
m_scanValue.setText(null);
if(m_scanSize != null)
{
m_scanSize.setText(null);
}
if(m_scanElapse != null)
{
m_scanElapse.setText(null);
}
setScanButtonState(true);
sendScanCommand(this, -1, ADMSG.CMD.START);
m_scanStartTime = SystemClock.elapsedRealtime();
}
private void stopScan()
{
sendScanCommand(this, -1, ADMSG.CMD.STOP);
}
private void changeScanEngine(Context context, int engine)
{
//Log.d(TAG, "chageEngine - engine="+engine);
Intent in = new Intent();
in.setAction(ADMSG.ACTION.ENGINE_CHANGE);
in.putExtra(ADMSG.KEY.ENGINE.ID, engine);
context.sendBroadcast(in);
}
private void sendScanCommand(Context context, int engine, String cmd)
{
//Log.d(TAG, "startScanService - engine="+engine+", cmd="+cmd);
Bundle extras = new Bundle();
extras.putString(ADMSG.KEY.SCAN.COMMAND, cmd);
extras.putInt(ADMSG.KEY.SCAN.ENGINE, engine);
sendScanCommand(context, extras);
}
private void sendScanCommand(Context context, Bundle extras)
{
Intent in = new Intent();
in.setAction(ADMSG.ACTION.SCAN);
in.putExtras(extras);
context.sendBroadcast(in);
}
private void enableScanButton(boolean enabled)
{
//Log.d(TAG, "> enableScanButton - m_scanStarted="+m_scanStarted);
m_inProgress = !enabled;
Resources rcs = getResources();
if(m_scanMode == ADMSG.SCANMODE.CONTINUOUS)
{
int txtRes = (enabled)?(fakeR.getId("string", "txt_Scan")):(fakeR.getId("string", "txt_Stop"));
m_btnScan.setText(txtRes);
}
else
{
int txtColorRes = (enabled)?(fakeR.getId("color", "text_color_tab_checked")):(fakeR.getId("color", "text_color_tab_unchecked"));
m_btnScan.setTextColor(rcs.getColor(txtColorRes));
m_btnScan.setEnabled(enabled);
}
}
private void setScanButtonState(boolean pressed)
{
Log.d(TAG, ">> setScanButtonState - pressed="+pressed);
m_scanStarted = pressed;
enableScanButton(!pressed);
}
private void changeEngine(int engine)
{
int currentEngine = m_db.getCurrentEngine();
Log.d(TAG, "changeEngine - engine: "+currentEngine+" -> "+engine);
if(engine == currentEngine)
{
return;
}
showInitEngineProgress(true);
m_scanSymbology.setText(null);
m_scanValue.setText(null);
if(m_scanSize != null)
{
m_scanSize.setText(null);
}
if(m_scanElapse != null)
{
m_scanElapse.setText(null);
}
changeScanEngine(this, engine);
m_nextEngine = engine;
}
private void showInitEngineProgress(boolean show)
{
if(show)
{
enableScanButton(false);
showDialog(DIALOG_WAITTING);
return;
}
Log.d(TAG, "showInitEngineProgress - m_dlgProgress="+m_dlgProgress);
if(m_dlgProgress != null)
{
m_dlgProgress.dismiss();
//m_dlgProgress = null;
}
if(!m_scanStarted)
{
enableScanButton(true);
}
}
private int getBgScanKeycode()
{
try
{
return(Integer.valueOf(m_db.getBgScanKeycode()));
}
catch(NumberFormatException e)
{
Log.e(TAG, "getBgScanKeycode - "+e.toString());
}
catch(NullPointerException e)
{
Log.e(TAG, "getBgScanKeycode - "+e.toString());
}
return(KeyEvent.KEYCODE_DPAD_CENTER);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case DIALOG_WAITTING:
{
String msg = getResources().getString(fakeR.getId("string", "txt_Engine_initializing"));
if(m_dlgProgress == null)
{
m_dlgProgress = new ProgressDialog(this);
m_dlgProgress.setIndeterminate(true);
m_dlgProgress.setCancelable(false);
}
m_dlgProgress.setMessage(msg);
return(m_dlgProgress);
}
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(fakeR.getId("menu", "settings_menu"), menu);
MenuItem item = null;
item = menu.getItem(0);
item.setIcon(fakeR.getId("drawable", "ic_menu_preferences"));
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
{
public boolean onMenuItemClick(MenuItem item)
{
Intent preferences = new Intent();
preferences.setClass(ScanActivity.this, SettingsActivity.class);
startActivity(preferences);
return(true);
}
});
return(true);
}
private void showDialog_noSupportedEngine()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//builder.setTitle(R.string.txt_ResetToDefault);
builder.setMessage(fakeR.getId("string", "txt_NoAnyValidScanEngine"));
builder.setPositiveButton(fakeR.getId("string", "txt_OK"), null);
builder.show().setOnDismissListener(m_dlgResetDismissListener);
}
OnDismissListener m_dlgResetDismissListener = new OnDismissListener()
{
public void onDismiss(DialogInterface dialog)
{
finish();
}
};
}

Comparing Values from a text file with value entered ,Using Java For Login purpose

I am trying to make a GUI which works as a login screen. The code should compare the value entered with the values in a txt file. (two fields needed to be compared) The values in the text file are given as two columns separated by a space. My code is not comparing the data properly.
Login.txt file:
ABCD XDFG
KFHK ERTF
FFSF JFKF
SETG kgfb
Code part:
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
#SuppressWarnings({ "serial", "unused" })
public class Guilook extends JFrame{
public JTextField exmem;
public JTextField clermem;
public JButton bok;
private Object EGM;
private Object CM;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Guilook window = new Guilook();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Guilook() {
initialize();
}
public void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setSize(350,300);
clermem = new JTextField();
clermem.setBounds(90, 114, 105, 22);
add(clermem);
clermem.setColumns(20);
exmem = new JTextField();
exmem.setBounds(90, 79, 105, 22);
add(exmem);
exmem.setColumns(10);
JLabel lblExcmem = new JLabel("Exmem");
lblExcmem.setBounds(220, 82, 76, 16);
add(lblExcmem);
JLabel lblClrmem = new JLabel("clrmem");
lblClrmem.setBounds(220, 117, 66, 16);
add(lblClrmem);
JButton bok = new JButton("OK");
bok.setBounds(144, 158, 97, 25);
bok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
String info = ReadFile();
System.out.println(info);
String[] split = info.split(" ");
String EGM=split[0];
String CM =split[1];
Scanner s=null;
if(exmem.getText().equals(EGM) && clermem.getText().equals(CM)){
JOptionPane.showMessageDialog(null,"REquestSuccesfl");
}else{
JOptionPane.showMessageDialog(null,"Wrong exmem/clermem");
}
}});
add(bok);
}
private static String ReadFile(){
String line=null;
String text="";
FileReader filereader=null;
try{
filereader =new FileReader(new File ("/home/v3nky/Downloads/eclipse_java/EurexGUI/sample.txt"));
BufferedReader bf=new BufferedReader(filereader);
while((line=bf.readLine()) !=null){
text=text+line+'\n';
}
bf.close();
}catch(Exception e){
e.printStackTrace();
}
return text;
}
}
I recommend you to use an ArrayList to get all the lines of your file and then split them to get EGM and CM values. Like this:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now you have all the lines of your file, so you can split them to get both values, like this:
for(int i = 0; i < list.size(); i++)
{
String[] line = list.get(i).split(" ");
EGM = line[0];
CM = line[1];
}
Now you can compare both values:
if (exmem.equals(EGM)&& clermem.equals(CM))
{
JOptionPane.showMessageDialog(null,"REquestSuccesfl");
}
else
{
JOptionPane.showMessageDialog(null,"Wrong exmem/clermem");
}
Finally, close your Scanner variable, like this:
s.close();
I expect it will be helpful for you!

java library for parsing javaScript objects with numeric keys

I have some problem parsing javaScript objects received from a web server.
These objects supposed to be JSON but contains numeric keys.
javaScript object:
{a: "alpha", 2: "two"}
The question is how can i decode such javascript objects in java ?
Are there any existing libraries that could be used ? And if there are how to represent that object in java :
public class JavaObject {
private String a; // for field - a: "alpha"
private ??? // for field - 2: "two"
}
Thanks
As i didn't find any solution for my problem on the web, i implemented myself an adapter for GSON library to handle such data.
As well known JSON supports only strings keys.
If a have a json data like this {"a": "alpha", "2": "two", "3":3} i can convert it in a regular JSONObject, but still i can't convert it it my own java object.
To handle this situation i created a ObjectMap object
// ObjectMap.java
import java.util.Map;
public class ObjectMap<V> {
private Map<String, V> map;
public ObjectMap(Map<String, V> map) {
setMap(map);
}
public Map<String, V> getMap() {
return map;
}
public void setMap(Map<String, V> map) {
this.map = map;
}
#Override
public String toString() {
return "ObjectMap [map=" + map + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((map == null) ? 0 : map.hashCode());
return result;
}
#SuppressWarnings("rawtypes")
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ObjectMap other = (ObjectMap) obj;
if (map == null) {
if (other.map != null)
return false;
} else if (!map.equals(other.map))
return false;
return true;
}
}
and a gson adapter for it ObjectMapAdapter.
//ObjectMapAdapter.java
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
public class ObjectMapAdapter<V> extends TypeAdapter<ObjectMap<V>> {
public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
#SuppressWarnings({ "unchecked", "rawtypes" })
public <T> TypeAdapter create(Gson gson, TypeToken<T> typeToken) {
Type type = typeToken.getType();
Class<? super T> rawType = typeToken.getRawType();
if (!ObjectMap.class.isAssignableFrom(rawType)) {
return null;
}
// if (rawType != ObjectMap.class) {
// return null;
// }
Type componentType;
if (type instanceof ParameterizedType) {
componentType = ((ParameterizedType) type).getActualTypeArguments()[0];
} else {
componentType = Object.class;
}
TypeAdapter<?> componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType));
return new ObjectMapAdapter(gson, componentTypeAdapter, $Gson$Types.getRawType(componentType));
}
};
// private final Class<V> valueType;
private final TypeAdapter<V> valueTypeAdapter;
public ObjectMapAdapter(Gson context, TypeAdapter<V> componentTypeAdapter, Class<V> componentType) {
this.valueTypeAdapter = new TypeAdapterRuntimeTypeWrapper<V>(context, componentTypeAdapter, componentType);
// this.valueType = componentType;
}
public ObjectMap<V> read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
Map<String, V> map = new LinkedHashMap<String, V>();
in.beginObject();
while (in.hasNext()) {
String key = in.nextName();
V comp = valueTypeAdapter.read(in);
map.put(key, comp);
}
in.endObject();
return new ObjectMap<V>(map);
}
#Override
public void write(JsonWriter out, ObjectMap<V> map) throws IOException {
if (map == null) {
out.nullValue();
return;
}
out.beginObject();
for (Entry<String, V> entry : map.getMap().entrySet()) {
out.name(entry.getKey());
valueTypeAdapter.write(out, entry.getValue());
}
out.endObject();
}
}
Create a custom GSON builder and register this factory
gsonBuilder.registerTypeAdapterFactory(ObjectMapAdapter.FACTORY);
the you are ready to decode data like this
{"a": "alpha", "2": "two", "3":3}
into a map
ObjectMap [map={a=alpha, 2=two, 3=3}]

Categories