SAX parser in BlackBerry - blackberry

My XML is in following format
<users>
<user uid="1" dispname ="Yogesh C" statid="1" statmsg = "Busy">Yogesh Chaudhari</user>
<user uid="2" dispname ="Sameer S" statid="2" statmsg = "Available">Yogesh Chaudhari</user>
</users>
In my BlackBerry app, I want to change the value of a particualar attribute, such as statmsg for uid 2. Is it possible to do this using a SAX parser? My aim is to update the XML and restore it.
I used the following code for parsing my XML using SAX:
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
public class SaxParseUrl extends UiApplication {
public SaxParseUrl() {
pushScreen(new Pars());
}
public static void main(String[] args) {
SaxParseUrl app = new SaxParseUrl();
app.enterEventDispatcher();
}
}
class Pars extends MainScreen implements ContentHandler
{
boolean name;
Pars() {
try {
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(this);
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/employee.xml");
InputStream is = conn.openDataInputStream();
InputSource iss = new InputSource(is);
parser.parse(iss);
} catch (Exception e) {
debug("file:///store/home/user/SAXParser.txt","Exception in pars() :"+e);
}
}
public void startElement(String nsURI, String strippedName, String tagName,
Attributes attributes) throws SAXException {
try {
debug("file:///store/home/user/SAXParser.txt","startElement");
if (tagName.equalsIgnoreCase("user"))
{
debug("file:///store/home/user/SAXParser.txt","Inside startElement");
name = true;
String uid = attributes.getValue("uid");
String dispname = attributes.getValue("dispname");
String statid = attributes.getValue("statid");
String statmsg = attributes.getValue("statmsg");
attributes.
//LabelField lb = new LabelField(uid+"==>"+dispname+"==>"+statid+"==>"+statmsg);
LabelField lb = new LabelField("uid ==>"+uid+"\ndispname==>"+dispname+"\nstatid==>"+statid+"\nstatmsg==>"+statmsg);
add(lb);
}
} catch (Exception e) {
System.out.println(e);
}
}
public void characters(char[] ch, int start, int length) {
debug("file:///store/home/user/SAXParser.txt","characters");
if (name) {
try {
System.out.println("Title: " + new String(ch, start, length));
LabelField lb=new LabelField(""+ new String(ch, start, length));
HorizontalFieldManager sr=new HorizontalFieldManager();
sr.add(lb);
add(sr);
//v_cid.addElement(new String(ch, start, length));
//System.out.println("the elements of vector: " + v_cid);
// name = false;
//Enumeration e = v_cid.elements();
//System.out.println("The elements of vector: " + v_cid);
//while (e.hasMoreElements()) {
//System.out.println("The elements are: " + e.nextElement());
//}*/
} catch (Exception e) {
System.out.println(e);
}
}
}
public void endDocument() throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endDocument");
}
public void endElement(String uri, String localName, String tagName)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endElement");
}
public void endPrefixMapping(String prefix) throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endPrefixMapping");
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","ignorableWhitespace");
}
public void processingInstruction(String target, String data)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","processingInstruction");
}
public void setDocumentLocator(Locator locator) {
debug("file:///store/home/user/SAXParser.txt","setDocumentLocator");
}
public void skippedEntity(String name) throws SAXException {
}
public void startDocument() throws SAXException {
debug("file:///store/home/user/SAXParser.txt","startDocument");
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","startPrefixMapping");
}
public static void debug(String strFileName,String strData)
{
FileConnection fc = null;
StringBuffer strbufData = null;
OutputStream ops = null;
try
{
fc = (FileConnection)Connector.open(strFileName,Connector. READ_WRITE);
//create the file if it doesnt exist
if(!fc.exists())
{
fc.create();
}
InputStream is = fc.openDataInputStream();
strbufData = new StringBuffer();
int intCh;
while((intCh = is.read())!= -1)
{
strbufData.append((char)intCh);
}
strbufData.append("\n\n"+strData);
String strFileContent = new String(strbufData.toString());
byte byteData[] = strFileContent.getBytes();
ops = fc.openOutputStream();
ops.write(byteData);
}
catch(Exception e)
{
Dialog.alert("Exception in writing logs :"+e);
}
finally
{
if(ops != null)
{
try
{
ops.close();
}catch(Exception e)
{
}
}
if(fc != null)
{
try
{
fc.close();
}catch(Exception e)
{
}
}
}
}
}

Related

Return value from Jenkins plugin

I'm developing a Jenkins plugin and in one of my build steps, I need to return a value. In this build step, I'm sending an API call to generate a registration token and I want to return that token as the output of this build step. The idea is to use this generated token later in pipeline/free-style.
My question is, how do I do that?
Here's my Build class:
package **.********.plugins;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.*;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Builder;
import hudson.util.ListBoxModel;
import **.********.constants.Constants;
import **.********.helpers.ApiHelper;
import **.********.helpers.ApiResponse;
import **.********.helpers.LogHelper;
import **.********.model.AgentDockerConfigData;
import **.********.model.AgentDockerConfigGenerationRequestData;
import **.********.model.JobData;
import **.********.model.ProjectData;
import jenkins.tasks.SimpleBuildStep;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.HashMap;
public class GenerateAgentConfigToken extends Builder implements SimpleBuildStep {
//region Private members
private ApiHelper apiHelper;
private String alias;
private String projectId;
private String jobId;
private String browsers;
private AgentDockerConfigData config;
//endregion
//region Constructors
public GenerateAgentConfigToken() { }
#DataBoundConstructor
public GenerateAgentConfigToken(String alias, String projectId, String jobId, String browsers) {
this.alias = alias;
this.projectId = projectId;
this.jobId = jobId;
this.browsers = browsers;
}
//endregion
//region Setters & Getters
public String getAlias() {
return alias;
}
#DataBoundSetter
public void setAlias(String alias) {
this.alias = alias;
}
public String getProjectId() {
return projectId;
}
#DataBoundSetter
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getJobId() {
return jobId;
}
#DataBoundSetter
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getBrowsers() {
return browsers;
}
#DataBoundSetter
public void setBrowsers(String browsers) {
this.browsers = browsers;
}
//endregion
private void init() {
LogHelper.Debug("Initializing API helper...");
this.apiHelper = new ApiHelper(PluginConfiguration.DESCRIPTOR.getApiKey());
}
#Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
#Override
public void perform(#Nonnull Run<?, ?> run, #Nonnull FilePath filePath, #Nonnull Launcher launcher, #Nonnull TaskListener taskListener) throws InterruptedException, IOException {
try {
EnvVars envVars = new EnvVars();
envVars = run.getEnvironment(taskListener);
envVars.put("jobId", jobId);
init();
LogHelper.SetLogger(taskListener.getLogger(), PluginConfiguration.DESCRIPTOR.isVerbose());
generateAgentConfigToken();
} catch (Exception e) {
LogHelper.Error(e);
run.setResult(Result.FAILURE);
}
}
private void generateAgentConfigToken() throws IOException {
LogHelper.Info("Sending a request to generate agent configuration token...");
//TODO: Change the URL to the production URL
ApiResponse<AgentDockerConfigData> response = apiHelper.Post(
Constants.TP_GENERATE_AGENT_CONFIG_TOKEN_URL,
null,
null,
generateRequestBody(),
AgentDockerConfigData.class);
if (response.isSuccessful()) {
if (response.getData() != null) {
config = response.getData();
}
} else {
int statusCode = response.getStatusCode();
String responseMessage = response.getMessage();
String message = "Unable to generate agent configuration token" + (statusCode > 0 ? " - " + statusCode : "") + (responseMessage != null ? " - " + responseMessage : "");
throw new hudson.AbortException(message);
}
}
private AgentDockerConfigGenerationRequestData generateRequestBody() {
// if the user did not provide an alias and jobId, send the body as null
if (StringUtils.isEmpty(alias) && StringUtils.isEmpty(jobId))
return null;
AgentDockerConfigGenerationRequestData body = new AgentDockerConfigGenerationRequestData();
if (!StringUtils.isEmpty(alias))
body.setAlias(alias);
if (!StringUtils.isEmpty(jobId)) {
body.setJobId(jobId);
if (!StringUtils.isEmpty(browsers))
body.setBrowsers(browsers.split(","));
}
return body;
}
#Override
public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); }
#Extension
#Symbol(Constants.TP_GENERATE_AGENT_CONFIG_TOKEN_SYMBOL)
public static class DescriptorImpl extends BuildStepDescriptor<Builder> {
public DescriptorImpl() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req, formData);
}
#Override
public boolean isApplicable(#SuppressWarnings("rawtypes") Class<? extends AbstractProject> jobType) {
return true;
}
#Nonnull
#Override
public String getDisplayName() {
return Constants.TP_GENERATE_AGENT_CONFIG_TOKEN;
}
public ListBoxModel doFillProjectIdItems() {
HashMap<String, Object> headers = new HashMap<>();
headers.put(Constants.ACCEPT, Constants.APPLICATION_JSON);
ApiResponse<ProjectData[]> response = null;
try {
ApiHelper apiHelper = new ApiHelper(PluginConfiguration.DESCRIPTOR.getApiKey());
response = apiHelper.Get(Constants.TP_RETURN_ACCOUNT_PROJECTS, headers, ProjectData[].class);
if (!response.isSuccessful()) {
int statusCode = response.getStatusCode();
String responseMessage = response.getMessage();
String message = "Unable to fetch the projects list" + (statusCode > 0 ? " - " + statusCode : "") + (responseMessage != null ? " - " + responseMessage : "");
throw new hudson.AbortException(message);
}
ListBoxModel model = new ListBoxModel();
model.add("Select a project", "");
for (ProjectData project : response.getData()) {
model.add(
project.getName() + " [" + project.getId() + "]",
project.getId());
}
return model;
} catch (IOException | NullPointerException e) {
LogHelper.Error(e);
}
return null;
}
public ListBoxModel doFillJobIdItems(#QueryParameter String projectId) {
if (projectId.isEmpty()) {
return new ListBoxModel();
}
HashMap<String, Object> headers = new HashMap<>();
headers.put(Constants.ACCEPT, Constants.APPLICATION_JSON);
ApiResponse<JobData[]> response = null;
try {
ApiHelper apiHelper = new ApiHelper(PluginConfiguration.DESCRIPTOR.getApiKey());
response = apiHelper.Get(String.format(Constants.TP_RETURN_PROJECT_JOBS, projectId), headers, JobData[].class);
if (!response.isSuccessful()) {
int statusCode = response.getStatusCode();
String responseMessage = response.getMessage();
String message = "Unable to fetch the project's jobs list" + (statusCode > 0 ? " - " + statusCode : "") + (responseMessage != null ? " - " + responseMessage : "");
throw new hudson.AbortException(message);
}
ListBoxModel model = new ListBoxModel();
model.add("Select a job to execute from the selected project (You must select a project first)", "");
for (JobData job : response.getData()) {
model.add(
job.getName() + " [" + job.getId() + "]",
job.getId());
}
return model;
} catch (IOException | NullPointerException e) {
LogHelper.Error(e);
}
return null;
}
}
}
Is there a way to return anything from perform rather than void or boolean ?

How to publish and receive data from Android Studio and have it on Google Cloud IoT Core?

I'm a student doing an Android Things project, which is about connecting Rasperi pi with an Accelerometer sensor to get acceleration data, I finished the coding part in Android Studio and the sensor is working fine, then I tried to connect my project to the cloud by following this tutorial: http://blog.blundellapps.co.uk/tut-google-cloud-iot-core-mqtt-on-android/
I think I have to publish the accelerometer data to the cloud by calling this method below in MainActivity class, I did that but still have an error, see the update I did at end of this question please.
#Override
public void onSensorChanged(SensorEvent event) {
Log.d(TAG, "Accel X " + event.values[0]);
Log.d(TAG, "Accel Y " + event.values[1]);
Log.d(TAG, "Accel Z " + event.values[2]);
}
Also, do I have to do something in the cloud platform to receive the data?, I already set up the communication with my Google IoT Core details as shown in the below code:
communicator = new IotCoreCommunicator.Builder()
.withContext(this)
.withCloudRegion("us-central1")
.withProjectId("my-first-project-198704")
.withRegistryId("vibration")
.withDeviceId("my-device")
.withPrivateKeyRawFileId(R.raw.rsa_private)
.build();
This is what I'm seeing in the cloud:
And this is the acceleration data I have in Android Studio:
My project consists of two modules but here I will attach only the second module because the question is limited to 3000 characters only and the second module is what I need to edit I think.
sample module:
AccelerometerActivity class:
package com.cacaosd.sample;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import com.cacaosd.adxl345.ADXL345SensorDriver;
import com.cacaosd.sample.BoardDefaults;
import java.io.IOException;
public class AccelerometerActivity extends Activity implements SensorEventListener {
private static final String TAG = AccelerometerActivity.class.getSimpleName();
private ADXL345SensorDriver mSensorDriver;
private SensorManager mSensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerDynamicSensorCallback(new SensorManager.DynamicSensorCallback() {
#Override
public void onDynamicSensorConnected(Sensor sensor) {
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mSensorManager.registerListener(AccelerometerActivity.this,
sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
});
try {
mSensorDriver = new ADXL345SensorDriver(BoardDefaults.getI2CPort());
mSensorDriver.registerAccelerometerSensor();
} catch (IOException e) {
Log.e(TAG, "Error configuring sensor", e);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "Closing sensor");
if (mSensorDriver != null) {
mSensorManager.unregisterListener(this);
try {
mSensorDriver.close();
} catch (IOException e) {
Log.e(TAG, "Error closing sensor", e);
} catch (Exception e) {
e.printStackTrace();
} finally {
mSensorDriver = null;
}
}
}
#Override
public void onSensorChanged(SensorEvent event) {
Log.d(TAG, "Accel X " + event.values[0]);
Log.d(TAG, "Accel Y " + event.values[1]);
Log.d(TAG, "Accel Z " + event.values[2]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.i(TAG, "sensor accuracy changed: " + accuracy);
}
}
BoardDefaults class:
package com.cacaosd.sample;
import android.os.Build;
import com.google.android.things.pio.PeripheralManagerService;
import java.util.List;
/**
* Created by cagdas on 20.12.2016.
*/
#SuppressWarnings("WeakerAccess")
public class BoardDefaults {
private static final String DEVICE_EDISON_ARDUINO = "edison_arduino";
private static final String DEVICE_EDISON = "edison";
private static final String DEVICE_RPI3 = "rpi3";
private static final String DEVICE_NXP = "imx6ul";
private static String sBoardVariant = "";
/**
* Return the preferred I2C port for each board.
*/
public static String getI2CPort() {
switch (getBoardVariant()) {
case DEVICE_EDISON_ARDUINO:
return "I2C6";
case DEVICE_EDISON:
return "I2C1";
case DEVICE_RPI3:
return "I2C1";
case DEVICE_NXP:
return "I2C2";
default:
throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
}
}
private static String getBoardVariant() {
if (!sBoardVariant.isEmpty()) {
return sBoardVariant;
}
sBoardVariant = Build.DEVICE;
// For the edison check the pin prefix
// to always return Edison Breakout pin name when applicable.
if (sBoardVariant.equals(DEVICE_EDISON)) {
PeripheralManagerService pioService = new PeripheralManagerService();
List<String> gpioList = pioService.getGpioList();
if (gpioList.size() != 0) {
String pin = gpioList.get(0);
if (pin.startsWith("IO")) {
sBoardVariant = DEVICE_EDISON_ARDUINO;
}
}
}
return sBoardVariant;
}
}
IotCoreCommunicator class:
package com.cacaosd.sample1;
import android.content.Context;
import android.util.Log;
import java.util.concurrent.TimeUnit;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class IotCoreCommunicator {
private static final String SERVER_URI = "ssl://mqtt.googleapis.com:8883";
public static class Builder {
private Context context;
private String projectId;
private String cloudRegion;
private String registryId;
private String deviceId;
private int privateKeyRawFileId;
public Builder withContext(Context context) {
this.context = context;
return this;
}
public Builder withProjectId(String projectId) {
this.projectId = projectId;
return this;
}
public Builder withCloudRegion(String cloudRegion) {
this.cloudRegion = cloudRegion;
return this;
}
public Builder withRegistryId(String registryId) {
this.registryId = registryId;
return this;
}
public Builder withDeviceId(String deviceId) {
this.deviceId = deviceId;
return this;
}
public Builder withPrivateKeyRawFileId(int privateKeyRawFileId) {
this.privateKeyRawFileId = privateKeyRawFileId;
return this;
}
public IotCoreCommunicator build() {
if (context == null) {
throw new IllegalStateException("context must not be null");
}
if (projectId == null) {
throw new IllegalStateException("projectId must not be null");
}
if (cloudRegion == null) {
throw new IllegalStateException("cloudRegion must not be null");
}
if (registryId == null) {
throw new IllegalStateException("registryId must not be null");
}
if (deviceId == null) {
throw new IllegalStateException("deviceId must not be null");
}
String clientId = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/" + registryId + "/devices/" + deviceId;
if (privateKeyRawFileId == 0) {
throw new IllegalStateException("privateKeyRawFileId must not be 0");
}
MqttAndroidClient client = new MqttAndroidClient(context, SERVER_URI, clientId);
IotCorePasswordGenerator passwordGenerator = new IotCorePasswordGenerator(projectId, context.getResources(), privateKeyRawFileId);
return new IotCoreCommunicator(client, deviceId, passwordGenerator);
}
}
private final MqttAndroidClient client;
private final String deviceId;
private final IotCorePasswordGenerator passwordGenerator;
IotCoreCommunicator(MqttAndroidClient client, String deviceId, IotCorePasswordGenerator passwordGenerator) {
this.client = client;
this.deviceId = deviceId;
this.passwordGenerator = passwordGenerator;
}
public void connect() {
monitorConnection();
clientConnect();
subscribeToConfigChanges();
}
private void monitorConnection() {
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
Log.e("TUT", "connection lost", cause);
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.d("TUT", "message arrived " + topic + " MSG " + message);
// You need to do something with messages when they arrive
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d("TUT", "delivery complete " + token);
}
});
}
private void clientConnect() {
try {
MqttConnectOptions connectOptions = new MqttConnectOptions();
// Note that the the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we explicitly set this.
// If you don't, the server will immediately close its connection to your device.
connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
// With Google Cloud IoT Core, the username field is ignored, however it must be set for the
// Paho client library to send the password field. The password field is used to transmit a JWT to authorize the device.
connectOptions.setUserName("unused-but-necessary");
connectOptions.setPassword(passwordGenerator.createJwtRsaPassword());
IMqttToken iMqttToken = client.connect(connectOptions);
iMqttToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("TUT", "success, connected");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e("TUT", "failure, not connected", exception);
}
});
iMqttToken.waitForCompletion(TimeUnit.SECONDS.toMillis(30));
Log.d("TUT", "IoT Core connection established.");
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
/**
* Configuration is managed and sent from the IoT Core Platform
*/
private void subscribeToConfigChanges() {
try {
client.subscribe("/devices/" + deviceId + "/config", 1);
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
public void publishMessage(String subtopic, String message) {
String topic = "/devices/" + deviceId + "/" + subtopic;
String payload = "{msg:\"" + message + "\"}";
MqttMessage mqttMessage = new MqttMessage(payload.getBytes());
mqttMessage.setQos(1);
try {
client.publish(topic, mqttMessage);
Log.d("TUT", "IoT Core message published. To topic: " + topic);
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
public void disconnect() {
try {
Log.d("TUT", "IoT Core connection disconnected.");
client.disconnect();
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
}
IotCorePasswordGenerator class:
package com.cacaosd.sample1;
import android.content.res.Resources;
import android.util.Base64;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
class IotCorePasswordGenerator {
private final String projectId;
private final Resources resources;
private final int privateKeyRawFileId;
IotCorePasswordGenerator(String projectId, Resources resources, int privateKeyRawFileId) {
this.projectId = projectId;
this.resources = resources;
this.privateKeyRawFileId = privateKeyRawFileId;
}
char[] createJwtRsaPassword() {
try {
byte[] privateKeyBytes = decodePrivateKey(resources, privateKeyRawFileId);
return createJwtRsaPassword(projectId, privateKeyBytes).toCharArray();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Algorithm not supported. (developer error)", e);
} catch (InvalidKeySpecException e) {
throw new IllegalStateException("Invalid Key spec. (developer error)", e);
} catch (IOException e) {
throw new IllegalStateException("Cannot read private key file.", e);
}
}
private static byte[] decodePrivateKey(Resources resources, int privateKeyRawFileId) throws IOException {
try(InputStream inStream = resources.openRawResource(privateKeyRawFileId)) {
return Base64.decode(inputToString(inStream), Base64.DEFAULT);
}
}
private static String inputToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private static String createJwtRsaPassword(String projectId, byte[] privateKeyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
return createPassword(projectId, privateKeyBytes, "RSA", SignatureAlgorithm.RS256);
}
private static String createPassword(String projectId, byte[] privateKeyBytes, String algorithmName, SignatureAlgorithm signatureAlgorithm) throws NoSuchAlgorithmException, InvalidKeySpecException {
Instant now = Instant.now();
// Create a JWT to authenticate this device. The device will be disconnected after the token
// expires, and will have to reconnect with a new token. The audience field should always be set
// to the GCP project id.
JwtBuilder jwtBuilder =
Jwts.builder()
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(now.plus(Duration.ofMinutes(20))))
.setAudience(projectId);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory kf = KeyFactory.getInstance(algorithmName);
return jwtBuilder.signWith(signatureAlgorithm, kf.generatePrivate(spec)).compact();
}
}
MainActivity class:
package com.cacaosd.sample1;
import android.app.Activity;
import android.hardware.SensorEvent;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.cacaosd.sample.AccelerometerActivity;
import com.cacaosd.sample.R;
import com.cacaosd.sample1.IotCoreCommunicator;
import com.google.android.things.pio.Gpio;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity {
AccelerometerActivity mAccelerometerActivity = new AccelerometerActivity();
private IotCoreCommunicator communicator;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the communication with your Google IoT Core details
communicator = new IotCoreCommunicator.Builder()
.withContext(this)
.withCloudRegion("us-central1") // ex: europe-west1
.withProjectId("my-first-project-198704") // ex: supercoolproject23236
.withRegistryId("vibration") // ex: my-devices
.withDeviceId("my-device") // ex: my-test-raspberry-pi
.withPrivateKeyRawFileId(R.raw.rsa_private)
.build();
HandlerThread thread = new HandlerThread("MyBackgroundThread");
thread.start();
handler = new Handler(thread.getLooper());
handler.post(connectOffTheMainThread); // Use whatever threading mechanism you want
}
private final Runnable connectOffTheMainThread = new Runnable() {
#Override
public void run() {
communicator.connect();
handler.post(sendMqttMessage);
}
};
private final Runnable sendMqttMessage = new Runnable() {
private int i;
/**
* We post 100 messages as an example, 1 a second
*/
#Override
public void run() {
if (i == 100) {
return;
}
SensorEvent event = null;
// events is the default topic for MQTT communication
String subtopic = "events";
// Your message you want to send
String message = "Hello World " + i++;
communicator.publishMessage(subtopic, message);
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1));
}
};
#Override
protected void onDestroy() {
communicator.disconnect();
super.onDestroy();
}
MainActivity class:
package com.cacaosd.sample1;
import android.app.Activity;
import android.hardware.SensorEvent;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.cacaosd.sample.AccelerometerActivity;
import com.cacaosd.sample.R;
import com.cacaosd.sample1.IotCoreCommunicator;
import com.google.android.things.pio.Gpio;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity {
AccelerometerActivity mAccelerometerActivity = new AccelerometerActivity();
private IotCoreCommunicator communicator;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the communication with your Google IoT Core details
communicator = new IotCoreCommunicator.Builder()
.withContext(this)
.withCloudRegion("us-central1") // ex: europe-west1
.withProjectId("my-first-project-198704") // ex: supercoolproject23236
.withRegistryId("vibration") // ex: my-devices
.withDeviceId("my-device") // ex: my-test-raspberry-pi
.withPrivateKeyRawFileId(R.raw.rsa_private)
.build();
HandlerThread thread = new HandlerThread("MyBackgroundThread");
thread.start();
handler = new Handler(thread.getLooper());
handler.post(connectOffTheMainThread); // Use whatever threading mechanism you want
}
private final Runnable connectOffTheMainThread = new Runnable() {
#Override
public void run() {
communicator.connect();
handler.post(sendMqttMessage);
}
};
private final Runnable sendMqttMessage = new Runnable() {
private int i;
/**
* We post 100 messages as an example, 1 a second
*/
#Override
public void run() {
if (i == 100) {
return;
}
SensorEvent event = null;
// events is the default topic for MQTT communication
String subtopic = "events";
// Your message you want to send
String message = "Hello World " + i++;
communicator.publishMessage(subtopic, message);
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1));
}
};
#Override
protected void onDestroy() {
communicator.disconnect();
super.onDestroy();
}
}
Update:
I added a third input (int acceleration) on publishMessage() method inside IotCoreCommunicator class like below:
public void publishMessage(String subtopic, String message, int acceleration) {
String topic = "/devices/" + deviceId + "/" + subtopic;
String payload = "{msg:\"" + message + "\"}";
MqttMessage mqttMessage = new MqttMessage(payload.getBytes());
mqttMessage.setQos(1);
try {
client.publish(topic, mqttMessage);
Log.d("TUT", "IoT Core message published. To topic: " + topic);
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
Then I call it on run() method inside the MainActivity class like below:
public void run() {
if (i == 100) {
return;
}
SensorEvent event = null;
// events is the default topic for MQTT communication
String subtopic = "events";
// Your message you want to send
String message = "Hello World " + i++;
int acceleration = mAccelerometerActivity.onSensorChanged(SensorEvent event.values);
communicator.publishMessage(subtopic, message, acceleration);
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1));
}
};
But I still have this error in the below screenshot:
(';' or ) expected)
Also the third input I added is shown like never been used as you see in the screenshot below, is this has any effect?
Thank you.

Excel Array Java

I imported my excel file into Java. I am now trying to randomly pick 5 people from my data. How would I go about doing that... Here is my code that I have so far.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Rewards {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = "C:/Users/Jordan/Desktop/Project5.csv";
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while((fileName = br.readLine()) != null) {
lineNumber++;
String[] result = fileName.split(",");
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'd start with a Random instance. How else can you do anything pseudo-randomly in any programming language?

Sending a tweet from Blackberry -- working in simulator, but not working on device

I am working on Blackberry Twitter integration to tweet a message on twitter.
The app is working fine in simulator but giving exception when I am running it on a device.
Here is the exception I am getting every time I run the app on the device{
OAuth_IO_Exception
I have done some research and saw a solution to set the correct date time on device, but it still is not working.
Here is my code:
import com.kc.twitter.activity.TweetToFriend;
import com.twitterapime.rest.Credential;
import com.twitterapime.xauth.Token;
import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class TwitterScreen extends MainScreen {
private final String CONSUMER_KEY = "{redected}";
private final String CONSUMER_SECRET = "{redected}";
private final String CALLBACK_URL = "http://kingdomconnectng.net/redirect.php";
private LabelField _labelStutus;
public static OAuthDialogWrapper pageWrapper = null;
private ShowAuthBrowser showAuthBrowserScreen;
private String adminMessage;
public String adminMessages[];
boolean done=false;
Credential c ;
TweetToFriend tw;
public static StoreToken _tokenValue;
public static boolean isTweetPosted=false;
public static boolean isTweeterScreen =false ;
public TwitterScreen(final String adminMessage)
{
this.adminMessage=adminMessage;
isTweeterScreen = true ;
showAuthBrowserScreen = new ShowAuthBrowser();
_tokenValue = StoreToken.fetch();
/*if(_tokenValue.token.equalsIgnoreCase("nothing"))
{*/
showAuthBrowserScreen.doAuth(null);
UiApplication.getUiApplication().pushScreen(showAuthBrowserScreen);
/*}
else
{
final Token t = new Token(_tokenValue.token, _tokenValue.secret,
_tokenValue.userId, _tokenValue.username);
Credential c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, t);
TweetToFriend tw=new TweetToFriend();
boolean done=tw.doTweet(adminMessage, c);
if(done==true){
Dialog.alert("Tweet posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
else{
Dialog.alert("Tweet not posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
}*/
}
class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
{
BrowserField b = new BrowserField();
public ShowAuthBrowser()
{
//if(isTweetPosted==false){
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
//}
_labelStutus = new LabelField("KingdomConnect App" );
//add(_labelStutus );
add(b);
pageWrapper = new BrowserFieldOAuthDialogWrapper(b,CONSUMER_KEY,CONSUMER_SECRET,CALLBACK_URL,this);
pageWrapper.setOAuthListener(this);
}
public void doAuth( String pin )
{
try
{
if ( pin == null )
{
pageWrapper.login();
}
else
{
this.deleteAll();
add(b);
pageWrapper.login(pin);
}
}
catch ( Exception e )
{
final String message = "Error loggin Twitter: " + e.getMessage();
Dialog.alert( message );
}
}
public void onAccessDenied(String response ) {
System.out.println("Access denied! -> " + response );
updateScreenLog( "Acceso denegado! -> " + response );
}
public void onAuthorize(final Token token) {
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
final Token myToken = token;
_tokenValue = StoreToken.fetch();
_tokenValue.token = myToken.getToken();
_tokenValue.secret = myToken.getSecret();
_tokenValue.userId = myToken.getUserId();
_tokenValue.username = myToken.getUsername();
_tokenValue.save();
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
try{
deleteAll();
c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, myToken);
tw = new TweetToFriend();
/*done=tw.doTweet("KingdomConnect App: "+adminMessage, c);
if(done == true)
{
Dialog.alert( "Buzz posted successfully." );
close();
}
*/
prepareMessage(adminMessage);
}catch(NullPointerException e){
}catch(Exception e){
}
}
});
}
public void onFail(String arg0, String arg1) {
updateScreenLog("Error authenticating user! -> " + arg0 + ", " + arg1);
}
}
//TWEET METHOD
public void tweet(String message){
done=tw.doTweet("KingdomConnect: "+message, c);
/*if(done == true){
Dialog.alert( "Shared successfully." );
close();
} */
}
//PREPARE MESSAGE TO TWEET
public void prepareMessage(String msg){
int charLimit = 120;
int _msgSize = msg.length();
int i=0;
int parts = _msgSize/124;
try {
if(_msgSize > charLimit){
int temp1=0,temp2=charLimit;
while(i<parts+1){
String data = null;
if(i==parts){
data = msg.substring(temp1, _msgSize);
}else{
data = msg.substring(temp1, temp2);
temp1=temp2;
temp2=temp2+charLimit;
}
i++;
tweet(data);
}
Dialog.alert( "Shared successfully." );
}else{
tweet(msg);
//System.out.println("Data:======================"+msg);
}
}catch (Exception e) {
System.out.println("e = "+e);
}
}
private void updateScreenLog( final String message )
{
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
_labelStutus.setText( message );
}
});
}
}

How to parse xml document in Blackberry?

How can I parse a xml file in Blackberry? Can I have a link or sample code or tutorial?
I've used SAX to process XML responses from a web api and it worked well for me. Check out: http://developerlife.com/tutorials/?p=28
What exactly are you trying to accomplish with XML?
You should have a interface to implement the listener in order to notify your UI thread once parsing is over.
import java.util.Vector;
public interface MediaFeedListner {
public void mediaItemParsed(Vector mObject);
public void exception(java.io.IOException ioe);
}
implement your class with MediaFeedListner and then override the mediaItemParsed(Vector mObject) and exception(java.io.IOException ioe) methoods.
mediaItemParsed() method will have the logic for notifying the UI thread and perform required operations.
Here is the XML parser code.
package com.test.net;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Vector;
import net.rim.device.api.xml.parsers.ParserConfigurationException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.span.data.MediaObject;
import com.span.utils.FileManager;
public class MediaHandler extends DefaultHandler {
protected static final String TAG_FEED = "feed";
protected static final String TAG_ENTRY = "entry";
protected static final String TAG_TITLE = "title";
protected static final String TAG_MEDIA_GROUP = "group";
protected static final String TAG_MEDIA_CATEGORY = "category";
protected static final String TAG_MEDIA_CONTENT = "content";
protected static final String TAG_MEDIA_DESCRIPTION = "description";
protected static final String TAG_MEDIA_THUMBNAIL = "thumbnail";
protected static final String ATTR_MEDIA_CONTENT= "url";
protected static final String ATTR_MEDIA_THUMBNAIL = "url";
boolean isEntry = false;
boolean isTitle = false;
boolean isCategory = false;
boolean isDescription = false;
boolean isThumbUrl = false;
boolean isMediaUrl = false;
boolean isMediaGroup = false;
String valueTitle = "";
String valueCategory = "";
String valueDescription = "";
String valueThumbnailUrl = "";
String valueMediaUrl = "";
public static Vector mediaObjects = null;
MediaObject _dataObject = null;
MediaFeedListner listner = null;
public MediaHandler(MediaFeedListner listner) {
this.listner = listner;
mediaObjects = new Vector();
}
public void parseXMLString(String xmlString) {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new ByteArrayInputStream(xmlString.getBytes()), this);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase(TAG_FEED)) {
//return;
}
if(localName.equals(TAG_ENTRY))
{
_dataObject = new MediaObject();
isEntry = true;
}
if(isEntry) {
if(localName.equalsIgnoreCase(TAG_TITLE)) {
isTitle = true;
}
if(localName.equals(TAG_MEDIA_GROUP))
isMediaGroup = true;
if(isMediaGroup) {
if(localName.equalsIgnoreCase(TAG_MEDIA_CONTENT)) {
valueMediaUrl = attributes.getValue(ATTR_MEDIA_CONTENT);
if(valueMediaUrl != null) {
_dataObject.setMediaUrl(valueMediaUrl);
valueMediaUrl = "";
}
}
if(localName.equalsIgnoreCase(TAG_MEDIA_THUMBNAIL)) {
valueThumbnailUrl = attributes.getValue(ATTR_MEDIA_THUMBNAIL);
if(valueThumbnailUrl != null) {
_dataObject.setMediaThumb(valueThumbnailUrl);
valueThumbnailUrl = "";
}
}
if(localName.equalsIgnoreCase(TAG_MEDIA_DESCRIPTION)) {
isDescription = true;
}
if(localName.equalsIgnoreCase(TAG_MEDIA_CATEGORY)) {
isCategory = true;
}
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if(isTitle){
valueTitle = new String(ch, start, length);
_dataObject.setMediaTitle(valueTitle);
System.out.println("Title value " + valueTitle);
valueTitle = "";
}
if(isCategory){
valueCategory = new String(ch, start, length);
_dataObject.setMediaCategory(valueCategory);
System.out.println("category value " + valueCategory);
valueCategory = "";
}
if(isDescription){
valueDescription = new String(ch, start, length);
_dataObject.setMediaDesc(valueDescription);
System.out.println("category value " + valueDescription);
valueDescription = "";
}
}
public void endElement(String uri, String localName, String name) throws SAXException {
if(localName.equalsIgnoreCase(TAG_FEED)) {
listner.mediaItemParsed(mediaObjects);
printMediaInfo(mediaObjects);
}
if(localName.equalsIgnoreCase(TAG_ENTRY)) {
isEntry = false;
isTitle = false;
isCategory = false;
isDescription = false;
mediaObjects.addElement(_dataObject);
}
}
public static void printMediaInfo(Vector v){
int length = v.size();
for(int i = 0 ; i <length ; i++){
MediaObject mediaObj = (MediaObject) v.elementAt(i);
FileManager.getInstance().writeLog("Title: " + mediaObj.getMediaTitle());
FileManager.getInstance().writeLog("Category: " + mediaObj.getMediaCategory());
FileManager.getInstance().writeLog("Desc: " + mediaObj.getMediaDesc());
FileManager.getInstance().writeLog("URL: " + mediaObj.getMediaUrl());
FileManager.getInstance().writeLog("Thumb: " + mediaObj.getMediaThumb());
FileManager.getInstance().writeLog("Fav count: " + mediaObj.getMediaFavCount());
FileManager.getInstance().writeLog("View Count: " + mediaObj.getMediaViewCount());
FileManager.getInstance().writeLog("Ratings: " + mediaObj.getMediaRating());
FileManager.getInstance().writeLog("============================================");
}
}
}
Its done.

Resources