DynamicDSGenerator in SmartGWT throws exceptions for fromXML(doc) - smartgwt

Sir, in my SmartGwt app i am updating my server config on fly. But here i use DynamicDSGenerator after property change so new user can connect on new config. I Create servlet that set my custom DynamicDSGenerator the code in this class thows null point exception
here is code
class CustomDSGenerator implements com.isomorphic.datasource.DynamicDSGenerator {
public CustomDSGenerator() {
super();
}
#Override
public DataSource getDataSource(String id, DSRequest dsRequest) {
DataSource ds = null;
try {
if (dsRequest != null) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream input = dsRequest.getServletContext().getResourceAsStream( "/ds/" + dsRequest.getDataSourceName() + ".ds.xml");
Document doc = builder.parse(input);
//>>>>> here doc is null
doc.getDocumentElement().setAttribute("dbName",thi s.dbName);
//>>>>> thows error after this
ds = DataSource.fromXML(doc);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return ds;
}
}
errors :
java.sql.SQLException: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at com.isomorphic.sql.SQLConnectionManager.getConnect ion(SQLConnectionManager.java:174)
at com.isomorphic.sql.SQLDriver.implementerClassForDB (SQLDriver.java:471)
at com.isomorphic.sql.SQLDriver.instance(SQLDriver.ja va:432)
at com.isomorphic.sql.SQLDataSource.init(SQLDataSourc e.java:186)
at com.isomorphic.datasource.DataSource.initialize(Da taSource.java:400)
at com.isomorphic.datasource.BasicDataSource.fromConf ig(BasicDataSource.java:163)
at com.isomorphic.datasource.DataSource.fromConfig(Da taSource.java:385)
at com.isomorphic.datasource.DataSource.fromXML(DataS ource.java:450)
at com.isomorphic.datasource.DataSource.fromXML(DataS ource.java:482)
at com.streetsmart1.dbsetup.CustomDSGenerator.getData Source(CustomDSGenerator.java:64)
at com.isomorphic.datasource.DataSource.getDynamicDat aSource(DataSource.java:364)
at com.isomorphic.datasource.DataSource.forName(DataS ource.java:202)
at com.isomorphic.datasource.DataSource.forName(DataS ource.java:195)
at com.isomorphic.datasource.DataSource.forName(DataS ource.java:184)
at com.isomorphic.datasource.PoolableDataSourceFactor y.makeUnpooledObject(PoolableDataSourceFactory.jav a:119)
at com.isomorphic.datasource.PoolableDataSourceFactor y.makeObject(PoolableDataSourceFactory.java:127)
at com.isomorphic.pool.PoolManager.borrowObject(PoolM anager.java:94)
at com.isomorphic.datasource.DataSourceManager.getDat aSource(DataSourceManager.java:89)
at com.isomorphic.datasource.DataSourceManager.getDat aSource(DataSourceManager.java:83)
at com.isomorphic.servlet.DataSourceLoader.processReq uest(DataSourceLoader.java:126)
at com.isomorphic.servlet.DataSourceLoader.doGet(Data SourceLoader.java:94)
at javax.servlet.http.HttpServlet.service(HttpServlet .java:617)
at com.isomorphic.servlet.BaseServlet.service(BaseSer vlet.java:152)
at javax.servlet.http.HttpServlet.service(HttpServlet .java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(Ser vletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler$CachedCha in.doFilter(ServletHandler.java:1097)
at com.isomorphic.servlet.CompressionFilter.doFilter( CompressionFilter.java:259)
at org.mortbay.jetty.servlet.ServletHandler$CachedCha in.doFilter(ServletHandler.java:1088)
at org.mortbay.jetty.servlet.ServletHandler.handle(Se rvletHandler.java:360)
at org.mortbay.jetty.security.SecurityHandler.handle( SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(Se ssionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(Co ntextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebA ppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(Ha ndlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle (RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(Ha ndlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(Htt pConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.he aderComplete(HttpConnection.java:829)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser. java:513)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpPa rser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnec tion.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(Selec tChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run (QueuedThreadPool.java:488)

Related

Model value not being set in Xamarin in iOS Only

I am working on a Xamarin App where I am facing an issue.
Case 1:
Mode: Debug
Error: System.NullReferenceException: 'Object reference not set to an instance of an object'
Explanation:
No value is being set and passed to ViewModel, Controller.
Even I tried setting static values to variables and parameters.
LoginModel logtest = new LoginModel();
logtest.Username = "Test#user.com"; //uName;
logtest.Password = "2342534"; //pWord;
Tried solution:
In the beginning, I tried many different solutions nothing worked.
Then I create a new project and moved all the code to the new project, then it started working.
Case 2:
Mode: release
Now the same issue I am getting in release mode.
No value is being set and passed to ViewModels and Controller.
I have already tried moving code to a new project.
How can I resolve this? I am not sure is this a Visual studio issue or Xamarin issue or Apple.
I have tried updating Visual Studio enterprise 2019 and Xcode on Mac.
Deleted and recreated Provisioning Profiles and Signing Identities.
Code From LoginPage.xaml.cs
private async void LoginButtonClicked(object sender, EventArgs e)
{
await ((LoginViewModel)BindingContext).Login();
}
protected async override void OnAppearing()
{
//App.Current.MainPage = new Navigation(new DashboardPage());
//load the login page
Device.BeginInvokeOnMainThread(() =>
{
try
{
((LoginViewModel)BindingContext).IsLoading = false;
((LoginViewModel)BindingContext).RememberMe = DeviceStorage.RememberMe;
if (DeviceStorage.RememberMe == true)
{
((LoginViewModel)BindingContext).UserName = "Test#user.ca"; //Trying set static values here
((LoginViewModel)BindingContext).Password = "password"; //Trying set static values here
}
//RememberMeToggle.Toggled += switcher_Toggled;
((LoginViewModel)BindingContext).Load();
}
catch (Exception ex)
{
//logger.Error(App.LogPrefix() + "Error opening Navigation Page: " + ex.Message);
Console.WriteLine(App.LogPrefix() + "Error opening Load(): " + ex.Message);
}
});
}
Code from LoginViewModel.cs
public async Task Login()
{
IsLoading = true;
await TokenController.GetAuthorizationToken(UserName, Password);
}
Code from TokenController.cs
public static async Task GetAuthorizationToken(string uName, string pWord)
{
bool tokenReturned = false;
string tokenGetResponse = string.Empty;
// Have tried setting them static values as well
LoginModel logtest = new LoginModel();
logtest.Username = uName;
logtest.Password = pWord;
logtest.AppType = Constants.AppDetails.APP_CODE;
logtest.SystemCode = Constants.AppDetails.SYSTEM_CODE;
logtest.Push.PushSystem = PushAddressModel.PushSystemCode.FireBase;
logtest.Push.Address = ((App)App.Current).PushNotificationToken;
logtest.Push.AppCode = Constants.AppDetails.APP_CODE;
string uri = URI.message_Chat_Endpoint;
(tokenReturned, tokenGetResponse) = await ApiFunctions.Post(logtest, URI.token_Endpoint, false);
if (tokenReturned)
{
try
{
//deserialize the return object
TokenModel token = JsonConvert.DeserializeObject<TokenModel>(tokenGetResponse);
((App)App.Current).token = token;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
//logger.Error(App.LogPrefix() + "Error: " + ex.Message);
}
Console.WriteLine("Profile Token loaded: " + ((App)App.Current).token.access_token);
}
else
{
Console.WriteLine("Error: Error loading profile token ");
//logger.Error(App.LogPrefix() + "Error loading profile token");
}
}

Android: Retrofit 2 multiple file upload howto?

Uploading a single image seems to be no problem with retrofit 2.
However,
i cant figure out how to upload 2 images at the same time.
if followed the documentation:
http://square.github.io/retrofit/2.x/retrofit/retrofit2/http/PartMap.html
File file = new File(path, "theimage");
File file2 = new File(path2, "theimage");
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
RequestBody requestBody2 = RequestBody.create(MediaType.parse("image/png"), file2);
Map<String, RequestBody> params = new HashMap<>();
params.put("image2", requestBody2 );
Call<ResponseBody> call = service.upload(requestBody, params);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
Log.v("Upload", "success");
}
interface:
public interface FileUploadService {
#Multipart
#POST("/upload")
Call<ResponseBody> upload(
//#Part("image_logo\"; filename=\"image.png\" ") RequestBody file,
#Part("file") RequestBody file,
#PartMap Map<String, RequestBody> params
// #Part("description") String description
);
this gives a 'Upload: success' but on the server side i get gibberish:
CONTENT_TYPE: multipart/form-data;
boundary=50fbfeb3-3abc-4f15-b130-cdcb7e3a0e4f
CONTENT POST:Array (
[file] => �PNG IHDR L alotofbinarygibberish.... ... snip
[file2] => �PNG
IHDR L more binary gibberish...
can anyone point me in the right direction?
single upload does work so thats not the problem, i'm trying to upload 2 or more images.
if i change it to this:
HashMap<String, RequestBody> partMap = new HashMap<String, RequestBody>();
partMap.put("file\"; filename=\"" + file.getName(), requestBody);
partMap.put("file\"; filename=\"" + file2.getName(), requestBody);
Call<ResponseBody> call = service.upload(partMap);
#Multipart
#POST("/upload")
Call<ResponseBody> upload(
#PartMap() Map<String, RequestBody> partMap,
i get no gibberish but only the second image is uploaded... !?
UPDATE
i tried this Retrofit(2.0 beta2) Multipart file upload doesn't work solution but get an error that #body can not me used with multipart:
Java.lang.IllegalArgumentException: #Body parameters cannot be used with form or multi-part encoding. (parameter #1)
for (String key : keys) {
Bitmap bm = selectedImages.get(key);
File f = new File(saveToInternalStorage(bm, key), key);
if (f.exists()) {
buildernew.addFormDataPart(key, key + ".png", RequestBody.create(MEDIA_TYPE, f));
}
}
RequestBody requestBody = buildernew.build();
-
Call<ResponseBody> upload(
#Body RequestBody requestBody
This works:
final MediaType MEDIA_TYPE=MediaType.parse("image/png");
HashMap<String,RequestBody> map=new HashMap<>(selectedImages.size());
RequestBody file=null;
File f=null;
Set<String> keys = selectedImages.keySet();
for (String key : keys) {
try {
Bitmap bitmap = selectedImages.get(key);
f = new File(saveToInternalStorage(bitmap, key), key);
FileOutputStream fos = new FileOutputStream(f);
if(bitmap!=null){
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , fos);
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
return;
}
file=RequestBody.create(MEDIA_TYPE, f);
map.put(""+key+"\"; filename=\""+key+".jpg",file);
Log.i("##MYLOG###", "### MAP PUT:" + key + " filename:"+key+".jpg file:" + file.toString() +" type:"+ file.contentType() );
file=null;
f = null;
}
--
Call<ResponseBody> upload(
#PartMap() Map<String,RequestBody> mapFileAndName //for sending multiple images
--
beware: while debugging this with the httpClient.interceptors() i saw only a single upload but when checking the endpoint itself to see what it actually got, it DID get the multiple uploads!
I might be late but my answer might help future visitors
I am asking user to select multiple images like this:
int PICK_IMAGE_MULTIPLE = 1;
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE);
Then in onActivityResult() I am doing this:
ArrayList<String> filePaths;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_MULTIPLE) {
if (data != null) {
filePaths=new ArrayList<>();
// If data.getData() == null means multiple images selected, else single image selected.
if (data.getData() == null) {
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
Uri uri = item.getUri();
filePaths.add(FileUtils.getPath(Activity.this, uri));
}
}
} else {
filePaths.add(FileUtils.getPath(Activity.this,data.getData()));
}
sendToServer();
}
}
}
You can get FileUtils class from this Github link
My sendToServer() method looks like this:
private void sendToServer() {
if(filePaths!=null) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
MediaType MEDIA_TYPE_IMG = MediaType.parse("image/jpeg");
MultipartBody.Builder builder=new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
RequestBody requestBody;
try {
for (int i = 0; i < filePaths.size(); i++) {
File file = new File(filePaths.get(i));
requestBody=RequestBody.create(MEDIA_TYPE_IMG,file);
builder.addFormDataPart("photo"+i,file.getName(),requestBody);
}
RequestBody finalRequestBody=builder.build();
Call<YourResponse> call=apiService.addEvent(finalRequestBody);
call.enqueue(new Callback<YourResponse>() {
#Override
public void onResponse(Call<YourResponse> call, Response<YourResponse> response) {
// process response
}
#Override
public void onFailure(Call<YourResponse> call, Throwable t) {
t.printStackTrace();
t.getCause();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
}
Finally my Retrofit endpoint looks like this:
#POST("event/add")
Call<YourResponse> addEvent(#Body RequestBody body);
Note that YourResponse can be your custom model class for handling response, or you can also use raw Response class in you don't want to make your model class.
Hope this helps new visitors.
Try This
For API:
//Multiple Images
#Multipart
#POST(HttpConstants.FILEMULTIPLEUPLOAD)
Call<Result>uploadMultipleImage(#Part MultipartBody.Part files1,#Part MultipartBody.Part files2, #Query("total_images") int total, #Query("stdID") int stdID);
Client
public class RaytaServiceClass {
public RaytaServiceClass() {
}
private static Retrofit getRetroClient(){
Gson gson = new GsonBuilder()
.setLenient()
.create();
return new Retrofit.Builder()
.baseUrl(HttpConstants.baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static RaytaApi getApiService(){
return getRetroClient().create(RaytaApi.class);
}
}
The Call
RaytaApi service= RaytaServiceClass.getApiService();
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file1);
RequestBody requestFile2 = RequestBody.create(MediaType.parse("multipart/form-data"), file2);
MultipartBody.Part body =
MultipartBody.Part.createFormData("uploaded_file", file1.getName(), requestFile);
MultipartBody.Part body2 =
MultipartBody.Part.createFormData("uploaded_file", file2.getName(), requestFile2);
Call<Result> resultCall=service.uploadMultipleImage(body,body2,2,1);
Log.v("####WWE","REquest "+resultCall.toString());
Log.v("###WWE","Retrofit Request Method = "+resultCall.request().method());
Log.v("###WWE","Retrofit Request Body = "+resultCall.request().body());
Log.v("###WWE","Retrofit Request Url = "+resultCall.request().url());
final Result[] result = {new Result()};
resultCall.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
progressDialog.dismiss();
Log.v("###WWE","Respnse");
result[0] =response.body();
Log.v("###WWE","Response Result "+result[0].getResult());
if(response.isSuccessful()){
Toast.makeText(UploadMultipleImageActivity.this,"Sucess",Toast.LENGTH_SHORT).show();
Toast.makeText(UploadMultipleImageActivity.this,"Press Refresh Button",Toast.LENGTH_LONG).show();
supportFinishAfterTransition();
}
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
progressDialog.dismiss();
Log.v("###WWE","Failure ");
Log.v("###WWE","MEssage "+t.getMessage());
}
});

BouncyCastle PGP Encryption / Decryption: Caused by: java.io.EOFException: premature end of stream in PartialInputStream

When attempting to encrypt then decrypt a file I run into the following exception:
com.example.common.crypto.CipherException: org.bouncycastle.openpgp.PGPException: Exception starting decryption
at com.example.common.crypto.PGPFileCipher.decrypt(PGPFileCipher.java:151)
at com.example.common.crypto.PGPFileCipherTest.testEncryptDecryptFile(PGPFileCipherTest.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:43)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:62)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:140)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:127)
at org.apache.maven.surefire.Surefire.run(Surefire.java:177)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:345)
at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1009)
Caused by: org.bouncycastle.openpgp.PGPException: Exception starting decryption
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at org.bouncycastle.openpgp.PGPPublicKeyEncryptedData.getDataStream(Unknown Source)
at com.example.common.crypto.PGPFileCipher.decrypt(PGPFileCipher.java:128)
... 28 more
Caused by: java.io.EOFException: premature end of stream in PartialInputStream
at org.bouncycastle.bcpg.BCPGInputStream$PartialInputStream.read(Unknown Source)
at org.bouncycastle.bcpg.BCPGInputStream.read(Unknown Source)
at java.io.InputStream.read(InputStream.java:82)
at javax.crypto.CipherInputStream.a(DashoA13*..)
at javax.crypto.CipherInputStream.read(DashoA13*..)
at org.bouncycastle.bcpg.BCPGInputStream.read(Unknown Source)
... 31 more
My PGPFileCipher class is:
package com.example.common.crypto;
public class PGPFileCipher implements FileCipher {
private static final Logger logger = LoggerFactory.getLogger(PGPFileCipher.class);
public File encryptFile(File inputFile, String encryptedFilePath, String publicKeyPath) throws CipherException {
FileInputStream publicKeyStream = null;
FileOutputStream encryptedFileOutputStream = null;
try {
publicKeyStream = new FileInputStream(new File(publicKeyPath));
File encryptedFile = new File(encryptedFilePath);
encryptedFileOutputStream = new FileOutputStream(encryptedFile);
encryptedFileOutputStream.write(encrypt(getBytesFromFile(inputFile), publicKeyStream, ""));
encryptedFileOutputStream.flush();
return encryptedFile;
} catch (Exception e) {
throw new CipherException(e);
} finally {
IOUtils.closeQuietly(encryptedFileOutputStream);
IOUtils.closeQuietly(publicKeyStream);
}
}
private PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass) throws CipherException {
try {
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) {
return null;
}
return pgpSecKey.extractPrivateKey(pass, new BouncyCastleProvider());
} catch (Exception e) {
throw new CipherException(e);
}
}
/**
* decrypt the passed in message stream
*
* #param encrypted
* The message to be decrypted.
* #param keyIn
* InputStream of the key
*
* #return Clear text as a byte array. I18N considerations are not handled
* by this routine
* #exception CipherException
*/
public byte[] decrypt(byte[] encrypted, InputStream keyIn, char[] password) throws CipherException {
ByteArrayOutputStream out = null;
InputStream clear = null;
InputStream in = null;
InputStream unc = null;
try {
in = new ByteArrayInputStream(encrypted);
in = PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc = null;
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));
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = findSecretKey(pgpSec, pbe.getKeyID(), password);
}
if (sKey == null) {
throw new IllegalArgumentException(
"secret key for message not found.");
}
clear = pbe.getDataStream(sKey, new BouncyCastleProvider());
PGPObjectFactory pgpFact = new PGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();
pgpFact = new PGPObjectFactory(cData.getDataStream());
PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();
unc = ld.getInputStream();
out = new ByteArrayOutputStream();
int ch;
while ((ch = unc.read()) >= 0) {
out.write(ch);
}
out.flush();
byte[] returnBytes = out.toByteArray();
return returnBytes;
} catch (Exception e) {
e.printStackTrace();
throw new CipherException(e);
} finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(clear);
IOUtils.closeQuietly(unc);
}
}
/**
* Simple PGP encryptor between byte[].
*
* #param clearData
* The test to be encrypted
* #param keyInputStream
* Input stream of the key
* #param fileName
* File name. This is used in the Literal Data Packet (tag 11)
* which is really inly important if the data is to be related to
* a file to be recovered later. Because this routine does not
* know the source of the information, the caller can set
* something here for file name use that will be carried. If this
* routine is being used to encrypt SOAP MIME bodies, for
* example, use the file name from the MIME type, if applicable.
* Or anything else appropriate.
*
* #return encrypted data.
* #exception CipherException
*/
public byte[] encrypt(byte[] clearData, InputStream keyInputStream, String fileName)
throws CipherException {
OutputStream out = null;
OutputStream cOut = null;
PGPCompressedDataGenerator comData = null;
PGPLiteralDataGenerator lData = null;
ByteArrayOutputStream encOut = null;
ByteArrayOutputStream bOut = null;
OutputStream cos = null;
OutputStream pOut = null;
try {
PGPPublicKey encKey = readPublicKey(keyInputStream);
if (fileName == null || fileName.trim().length() < 1) {
fileName = PGPLiteralData.CONSOLE;
}
encOut = new ByteArrayOutputStream();
out = encOut;
bOut = new ByteArrayOutputStream();
comData = new PGPCompressedDataGenerator(
PGPCompressedDataGenerator.ZIP);
cos = comData.open(bOut); // open it with the final
// destination
lData = new PGPLiteralDataGenerator();
// we want to generate compressed data. This might be a user option
// later,
// in which case we would pass in bOut.
pOut = lData.open(cos, // the compressed output stream
PGPLiteralData.BINARY, fileName, // "filename" to store
clearData.length, // length of clear data
new Date() // current time
);
pOut.write(clearData);
pOut.flush();
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
PGPEncryptedData.CAST5, false, new SecureRandom(),
new BouncyCastleProvider());
cPk.addMethod(encKey);
byte[] bytes = bOut.toByteArray();
cOut = cPk.open(out, bytes.length);
cOut.write(bytes); // obtain the actual bytes from the compressed stream
cOut.flush();
encOut.flush();
return encOut.toByteArray();
} catch (Exception e) {
throw new CipherException(e);
} finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(cOut);
IOUtils.closeQuietly(encOut);
IOUtils.closeQuietly(bOut);
IOUtils.closeQuietly(cos);
IOUtils.closeQuietly(pOut);
try {
if (lData != null) {
lData.close();
}
if (comData != null) {
comData.close();
}
} catch (IOException ignored) {}
}
}
private PGPPublicKey readPublicKey(InputStream in)
throws CipherException {
try {
in = PGPUtil.getDecoderStream(in);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);
//
// we just loop through the collection till we find a key suitable for
// encryption, in the real
// world you would probably want to be a bit smarter about this.
//
//
// iterate through the key rings.
//
Iterator rIt = pgpPub.getKeyRings();
while (rIt.hasNext()) {
PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
Iterator kIt = kRing.getPublicKeys();
while (kIt.hasNext()) {
PGPPublicKey k = (PGPPublicKey) kIt.next();
if (k.isEncryptionKey()) {
return k;
}
}
}
throw new IllegalArgumentException("Can't find encryption key in key ring.");
} catch (Exception e) {
throw new CipherException(e);
}
}
private byte[] getBytesFromFile(File file) throws CipherException {
InputStream is = null;
try {
is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new CipherException("File is too large: " + file.getName());
}
return IOUtils.toByteArray(is);
} catch (IOException e) {
throw new CipherException(e);
} finally {
IOUtils.closeQuietly(is);
}
}
}
And the test I'm attempting to run is:
package com.example.common.crypto;
public class PGPFileCipherTest {
private static final Logger logger = LoggerFactory.getLogger(PGPFileCipherTest.class);
#Rule
public TemporaryFolder folder = new TemporaryFolder();
#Test
public void testEncryptDecryptFile() throws IOException, CipherException {
FileOutputStream decryptedFileOutputStream = null;
InputStream privateKeyStream = null;
try {
PGPFileCipher fileCipher = new PGPFileCipher();
Resource inputFile = new ClassPathResource("testInputFile.txt");
Resource publicKey = new ClassPathResource("PUBLIC.asc");
Resource privateKey = new ClassPathResource("PRIVATE.asc");
// Encrypt file
File encryptedFile = fileCipher.encryptFile(inputFile.getFile(), folder.newFile("testInputFile_enc.txt").getPath(), publicKey.getFile().getPath());
// Now decrypt the file
File decryptedFile = folder.newFile("testInputFile_dec.txt");
decryptedFileOutputStream = new FileOutputStream(decryptedFile);
privateKeyStream = new FileInputStream(privateKey.getFile());
decryptedFileOutputStream.write(fileCipher.decrypt(FileUtils.readFileToByteArray(encryptedFile), privateKeyStream, "".toCharArray()));
decryptedFileOutputStream.flush();
} finally {
IOUtils.closeQuietly(decryptedFileOutputStream);
IOUtils.closeQuietly(privateKeyStream);
}
}
}
Unfortunately I'm not all that familiar with the BouncyCastle and it would seem as if a stream is not properly being closed / flushed but I can't seem to track it down. This is a modified version of one of the BouncyCastle examples FYI. Thanks in advance for your help.
check the jdk version.. we were facing issue running encryption and both in jdk1.5. but jdk 1.6 it work fine. and yes the bc pro jars "bcpg-jdk16" and" bcprov-ext-jdk16" verison should be 1.46
Be careful when using new BouncyCastleProvider() as it will result in the provider being registered in JceSecurity each time you instantiate it. This will cause a memory leak.
Consider doing something like this instead
private Provider getProvider() {
Provider provider = Security.getProvider("BC");
if (provider==null){
provider = new BouncyCastleProvider();
Security.addProvider(provider);
}
return provider;
}

Deferring persistence as device is being used in BlackBerry when listening file change

I tried to listen file change event in BlackBerry base on FileExplorer example, but whenever I added or deleted file, it always showed "Deferring persistence as device is being used" and I can't catch anything .Here is my code:
public class FileChangeListenner implements FileSystemJournalListener{
private long _lastUSN; // = 0;
public void fileJournalChanged() {
long nextUSN = FileSystemJournal.getNextUSN();
String msg = null;
for (long lookUSN = nextUSN - 1; lookUSN >= _lastUSN && msg == null; --lookUSN)
{
FileSystemJournalEntry entry = FileSystemJournal.getEntry(lookUSN);
// We didn't find an entry
if (entry == null)
{
break;
}
// Check if this entry was added or deleted
String path = entry.getPath();
if (path != null)
{
switch (entry.getEvent())
{
case FileSystemJournalEntry.FILE_ADDED:
msg = "File was added.";
break;
case FileSystemJournalEntry.FILE_DELETED:
msg = "File was deleted.";
break;
}
}
}
_lastUSN = nextUSN;
if ( msg != null )
{
System.out.println(msg);
}
}
}
Here is the caller:
Thread t = new Thread(new Runnable() {
public void run() {
new FileChangeListenner();
try {
Thread.sleep(5000);
createFile();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
Create file method worked fine:
private void createFile() {
try {
FileConnection fc = (FileConnection) Connector
.open("file:///SDCard/newfile.txt");
// If no exception is thrown, then the URI is valid, but the file
// may or may not exist.
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and output:
0:00:44.475: Deferring persistence as device is being used.
0:00:46.475: AG,+CPT
0:00:46.477: AG,-CPT
0:00:54.476: VM:+GC(f)w=11
0:00:54.551: VM:-GCt=9,b=1,r=0,g=f,w=11,m=0
0:00:54.553: VM:QUOT t=1
0:00:54.554: VM:+CR
0:00:54.596: VM:-CR t=5
0:00:55.476: AM: Exit net_rim_bb_datatags(291)
0:00:55.478: Process net_rim_bb_datatags(291) cleanup started
0:00:55.479: VM:EVTOv=7680,w=20
0:00:55.480: Process net_rim_bb_datatags(291) cleanup done
0:00:55.481: 06/25 03:40:41.165 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
0:00:55.487: 06/25 03:40:41.171 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
I also tried to remove the thread or create or delete file in simulator 's sdcard directly but it doesn't help. Please tell me where is my problem. Thanks
You instantiate the FileChangeListenner, but you never register it, and also don't keep it as a variable anywhere. You probably need to add this call
FileChangeListenner listener = new FileChangeListenner();
UiApplication.getUiApplication().addFileSystemJournalListener(listener);
You also might need to keep a reference (listener) around for as long as you want to receive events. But maybe not (the addFileSystemJournalListener() call might do that). But, you at least need that call to addFileSystemJournalListener(), or you'll never get fileJournalChanged() called back.

Critical Tunnel failure exception. How to solve this

I wrote the below code to send location coordinates to server:
setTitle("version 5.0");
Criteria criteria = new Criteria();
criteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setCostAllowed(true);
criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
// bc.setFailoverMode(GPSInfo.GPS_MODE_ssCDMA_MS_ASSIST, 2, 100);
try {
LocationProvider lp=LocationProvider.getInstance(criteria);
if(lp !=null)
{
Location loc=null;
// while(loc==null)
// {
loc=lp.getLocation(-1);
// }
if(loc!=null){
add(new EditField(loc.getQualifiedCoordinates().getLatitude()+"\n"+loc.getQualifiedCoordinates().getLongitude(),""));
}
else
add(new EditField("unable to find the location provider", ""));
}
else
{
add(new EditField("unable to find the location provider", ""));
}
} catch (LocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ButtonField b = new ButtonField("Send");
add(b);
b.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
try{
String url="http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true";
Dialog.alert(url);
ConnectionFactory factory = new ConnectionFactory();
// use the factory to get a connection
ConnectionDescriptor conDescriptor = factory.getConnection(url, TransportInfo.TRANSPORT_TCP_CELLULAR,null);
if ( conDescriptor != null ) {
HttpConnection conn = (HttpConnection) conDescriptor.getConnection();
Dialog.alert("http");
//conn.setRequestMethod(HttpConnection.GET);
Dialog.alert("conn.setre");
int responseCode = conn.getResponseCode();
Dialog.alert(Integer.toString(responseCode));
if(responseCode == HttpConnection.HTTP_OK)
{
Dialog.alert("OK");
InputStream data = conn.openInputStream();
StringBuffer raw = new StringBuffer();
byte[] buf = new byte[4096];
int nRead = data.read(buf);
while(nRead > 0)
{
raw.append(new String(buf, 0, nRead));
nRead = data.read(buf);
}
}
}
}catch(Exception e){
Dialog.alert(e.getMessage());
}
}
});
I am getting an exception Critical tunnel failure. But i am able to retrieve the location coordinates correctly. I am using blackberry 8520 with airtel sim which is enabled with data services. Actually this app worked well in the mobile with version 5.0. But it's not working in the mobile which i've upgraded from 4.6.1.3 to 5.0.0 what might be the problem? Please provide me a solution. thank you
I also tried the below url's:
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=null
http://56.91.532.72:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.9477&lon=82.23970;deviceside=true;apn=airtelgprs.com
I also enabled apn settings in my mobile
It is because you haven't set up the apn correctly. As you are using direct tcp, the apn has to be set in order to connect to the network.
Also , network connections should be done on a separate thread.

Resources