Im trying to send notifications to a Titanium App from AeroGear. After getting the token, how can subscribe to the channel?
Obteining the token:
var CloudPush = require('ti.cloudpush');
var deviceToken = null;
CloudPush.retrieveDeviceToken({
success: deviceTokenSuccess,
error: deviceTokenError
});
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
CloudPush.addEventListener('callback', function (evt) {
alert("Notification received: " + evt.payload);
});
This is the example code for native Androiod:
package com.push.pushapplication;
import java.net.URI;
import java.net.URISyntaxException;
import org.jboss.aerogear.android.unifiedpush.PushConfig;
import org.jboss.aerogear.android.unifiedpush.PushRegistrar;
import org.jboss.aerogear.android.unifiedpush.Registrations;
import android.app.Application;
public class PushApplication extends Application {
private final String VARIANT_ID = "variant_id";
private final String SECRET = "secret";
private final String GCM_SENDER_ID = "1";
private final String UNIFIED_PUSH_URL = "URL";
private PushRegistrar registration;
#Override
public void onCreate() {
super.onCreate();
Registrations registrations = new Registrations();
try {
PushConfig config = new PushConfig(new URI(UNIFIED_PUSH_URL), GCM_SENDER_ID);
config.setVariantID(VARIANT_ID);
config.setSecret(SECRET);
config.setAlias(MY_ALIAS);
registration = registrations.push("unifiedpush", config);
registration.register(getApplicationContext(), new Callback() {
private static final long serialVersionUID = 1L;
#Override
public void onSuccess(Void ignore) {
Toast.makeText(MainActivity.this, "Registration Succeeded!",
Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Exception exception) {
Log.e("MainActivity", exception.getMessage(), exception);
}
});
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
Really lost here, any help would be appreciated!
You need to make wrapper around AeroGear native library as titanium module. However, it may be difficult if you didn't it before.
The titanium module that you need to get this working has been made by "Mads" and you can find it here: https://github.com/Napp/AeroGear-Push-Titanium
Related
I have created an application where it scans bar codes and QR codes on the phone and send an email of the collected data to my personal email which is a gmail. However, recently it stopped sending emails and prompted me an error as shown below:
javax.mail.authenticationfailedexception: [EOF]
NOTE: I am relatively new at this
I have been told to change it from SMTP to SSL but I cant seem to fix the issue.
package com.example.createexcelsample;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.nio.charset.Charset;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import static android.content.ContentValues.TAG;
public class SendMail extends AsyncTask<Void, Void, Void> {
private Context context;
private Session session;
private String email;
private String subject;
private String message;
private String fileName;
private MyWebServiceResult listener;
public String SendError = "";
private ProgressDialog progressDialog;
private String email_uid = "EMAIL";//Email written here
private String email_pwd = "123456";
/*URL url = new URL("https://office365.com");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
//copyInputStreamToOutputStream(in, System.out);*/
public interface MyWebServiceResult {
public void onSendIsComplete();
public void onSendError(String Error);
}
public void setWebServiceResult(MyWebServiceResult listener) {
this.listener = listener;
}
public SendMail(Context context, String email, String subject, String message,String fileName,String email_uid, String email_pwd){
//this.email_uid = email_uid;
//this.email_pwd = email_pwd;
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
this.fileName = fileName;
this.listener = null;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//props.put("mail.smtp.host", "smtp.gmail.com");
/* props.put("mail.smtp.host", "212.12.184.20");
props.put("mail.smtp.port", "110");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");*/
//props.put("mail.smtp.ssl.trust", "212.12.184.20");
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email_uid, email_pwd);
}
});
try {
MimeMessage mm = new MimeMessage(session);
mm.setFrom(new InternetAddress(email_uid));
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
mm.setSubject(subject);
mm.setText("body");
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileName);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
mm.setContent(multipart);
SendError = "";
Transport.send(mm);
}
catch (MessagingException e) {
SendError = e.toString().toString();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// progressDialog.dismiss();
if (SendError.toString().isEmpty()){
listener.onSendIsComplete();
} else {
listener.onSendError(SendError);
}
}
/* public void hideSoftKeyboard(AutoProgramingValid activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
AutoProgramingValid.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}*/
}
I'm working with a specific API that returns a class as a string to me. I need to insert a string at a certain block of the string that is given to me. So basically a function that takes the whole string, and appends the string I want to add to it after a specific block.
The string passed to me is a java class, and I want to basically enter my own function at the end of it after all of the existing functions. Incase you are confused.. I don't have access to the java file, this is the only way to modify the file when you are using config plugins in expo react native.
I believe some sort of regex is supposed to be used to get this result ? but really I have no idea how to target the specific part of the string.
The string I want to add:
'#Override\nprotected List getPackages() {\nreturn Arrays.asList(\nnew MainReactPackage(), // <---- add comma\nnew RNFSPackage() // <---------- add package\n);\n}'
The string that is passed to me
import expo.modules.updates.UpdatesDevLauncherController;
import expo.modules.devlauncher.DevLauncherController;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import androidx.annotation.NonNull;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import expo.modules.ApplicationLifecycleDispatcher;
import expo.modules.ReactNativeHostWrapper;
import com.facebook.react.bridge.JSIModulePackage;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHostWrapper(
this,
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return DevLauncherController.getInstance().getUseDeveloperSupport();
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
#Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage();
}
});
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
DevLauncherController.initialize(this, getReactNativeHost());
if (BuildConfig.DEBUG) {
DevLauncherController.getInstance().setUpdatesInterface(UpdatesDevLauncherController.initialize(this));
}
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
ApplicationLifecycleDispatcher.onApplicationCreate(this);
}
#Override
public void onConfigurationChanged(#NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig);
}
<--- I WANT TO INSERT MY STRING HERE
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* #param context
* #param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.haibert.GitTest.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
const addToMainApp = (content) => {
const regexpPackagingOptions = /\s*?(?=\/\*\*\n \* Loads Flipper)/
const insertLocation = content.match(regexpPackagingOptions)
const newContent =
content.substring(0, insertLocation.index) +
'//INSERTED \n#Override\nprotected List<ReactPackage> getPackages() {\nreturn Arrays.<ReactPackage>asList(\nnew MainReactPackage(), // <---- add comma\nnew RNFSPackage() // <---------- add package\n);\n}' +
content.substring(insertLocation.index, content.length)
return newContent
}
I'd like to import a module written natively (java, Android) into my React Native sources, in JS.
To access your functionality implemented in java you have to create a bridge. You can see the most recent instructions in the RN documentation site*.
The steps, assuming React Native 0.61, for a hello world, to be implemented in the android project inside the react native app directory (android directory):
1) First you create a simple POJO class to be returned to the react native context:
class MyData{
private int timeSpentSleeping;
public int getTimeSpentSleeping() {
return timeSpentSleeping;
}
public void setTimeSpentSleeping(int timeSpentSleeping) {
this.timeSpentSleeping = timeSpentSleeping;
}
#NonNull
#Override
public String toString() {
Gson gson = new Gson();
String json = gson.toJson(this);
return json;
}
static MyData build(final int timeSpentSleeping){
MyData newInstance = new MyData();
newInstance.timeSpentSleeping = timeSpentSleeping;
return newInstance;
}
}
And the react native module that do something and return objects of this class as javascript Promises:
public class HelloPromiseModule extends ReactContextBaseJavaModule {
public HelloPromiseModule(#NonNull ReactApplicationContext reactContext) {
super(reactContext);
}
#NonNull
#Override
public String getName() {
return "HelloPromise";
}
#ReactMethod
public void foobar(Promise promise){
Random r = new Random();
final int timeToSleep = r.nextInt(1000);
runThreadAndCallPromiseToJavascript(timeToSleep, promise);
}
//Cria um thread pra executar algo em paralelo
private void runThreadAndCallPromiseToJavascript(final int timeToSleep,final Promise promise){
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(timeToSleep);
MyData result = MyData.build(timeToSleep);
promise.resolve(result.toString());
} catch (InterruptedException e) {
e.printStackTrace();
promise.reject(e);
}
}
});
t.run();
}
}
Now, we create the React Native Package (that is different from java packages):
public class HelloWorldPackage implements ReactPackage{
#NonNull
#Override
public List<NativeModule> createNativeModules(#NonNull ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new HelloPromiseModule(reactContext));
}
#NonNull
#Override
public List<ViewManager> createViewManagers(#NonNull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
The last step in the android version of your react native app is to register your HelloWorldPackage:
In the MainApplication.java inside your android project, inside the getPackages(), in the list of packages (new PackageList(this)...):
packages.add(new HelloWorldPackage());
Something like that:
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new HelloWorldPackage());
return packages;
}
Now, to get your native class in the javascript world:
import {
NativeModules,
} from 'react-native';
...
const {HelloPromise} = NativeModules;
Your native class is accessible from the variable HelloPromise.
You can get the result of HelloPromise.foobar() with something like this, in the react native side of your code:
async function handleHelloPromisesPress() {
let result = await HelloPromise.foobar();
console.log(result);
}
You may notice that 'result' is a json whose structure is equal to the POJO class we created in the beginning.
I have test code in which I want to read configurations from consul.The application.properties (src/main/resources) enables the consul config. And I have one POJO class name DBConfig (in src/main/java) which gets the configuration from consul. I have autowired the DBConfig in test class and when I'm running the unit test it is giving me nullpointerexception as it is not getting the values from consul.
How to handle the situation. Please help.
#Configuration
#ConfigurationProperties(prefix="db")
#RefreshScope
public class DBConfig {
private String jdbcURL;
private String username;
private String password;
private String driverClass;
...getter setters.
}
Test Class---
#RunWith(MockitoJUnitRunner.class)
#Transactional(propagation=Propagation.REQUIRED,readOnly=false,rollbackFor=Exception.class)
#SpringBootTest(classes={DBConfig.class})
public class TestUserDao extends DBTestCase {
#Autowired
private DBConfig dbConfig;
protected final Resource res = new ClassPathResource("actualDataSet.xml");
#Bean
#Profile("test")
#RefreshScope
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(dbConfig.getDriverClass());
dataSource.setUrl(dbConfig.getJdbcURL());
dataSource.setUsername(dbConfig.getUsername());
dataSource.setPassword(dbConfig.getPassword());
return dataSource;
}
#Bean
#Autowired
public NamedParameterJdbcTemplate jdbcTemplate(DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean
#Autowired
public UserDAO userDAO(NamedParameterJdbcTemplate jdbcTemplate) {
return new UserDAO(jdbcTemplate);
}
#Override
protected IDataSet getDataSet() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
String file = classLoader.getResource("actualDataSet.xml").getFile();
return new FlatXmlDataSetBuilder().build(new FileInputStream(file));
}
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.REFRESH;
}
#Test
public void insertTodo() throws Exception {
}
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.DELETE;
}
It may be caused by usage of MockitoJUnitRunner class, which will not load ApplicationContext at startup, which means, your beans won't be accessible.
Once you will use SpringRunner class in #RunWith() annotation, Spring should be able to inject DBConfig bean.
Am working on app which i recently implemented a background service with help from the following: https://github.com/Red-Folder/Cordova-Plugin-BackgroundService/
Everything works fine and the service runs in the background when the phone is restarted.
But in the background service which executes a Java method Every 5mins 'DoWork' Line 20 https://github.com/Red-Folder/Cordova-Plugin-BackgroundService/blob/master/2.2.0/MyService.java
package com.yournamespace.yourappname;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.red_folder.phonegap.plugin.backgroundservice.BackgroundService;
public class MyService extends BackgroundService {
private final static String TAG = MyService.class.getSimpleName();
private String mHelloTo = "World";
#Override
protected JSONObject doWork() {
JSONObject result = new JSONObject();
try {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String now = df.format(new Date(System.currentTimeMillis()));
String msg = "Hello " + this.mHelloTo + " - its currently " + now;
result.put("Message", msg);
Log.d(TAG, msg);
} catch (JSONException e) {
}
return result;
}
#Override
protected JSONObject getConfig() {
JSONObject result = new JSONObject();
try {
result.put("HelloTo", this.mHelloTo);
} catch (JSONException e) {
}
return result;
}
#Override
protected void setConfig(JSONObject config) {
try {
if (config.has("HelloTo"))
this.mHelloTo = config.getString("HelloTo");
} catch (JSONException e) {
}
}
#Override
protected JSONObject initialiseLatestResult() {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onTimerEnabled() {
// TODO Auto-generated method stub
}
#Override
protected void onTimerDisabled() {
// TODO Auto-generated method stub
}
}
I would like to call a JavaScript function also from that method.
The Javascript Function does the following:
- Gets all the device contacts
- Get the device GeoLocation
- Get the device IMEI and phonenumber
and post to an external server.
I would like to know if that is possible i.e calling the javascript function from Java.
Note: I do not know much about Java so detailed explanation will be appreciated.
Thanks in advance !