Getting question marks in service response in codenameone - connection

I am calling service using ConnectionRequest class and if i'm getting result in English i'm able to display it but if i'm getting response in Hindi at that time getting as question marks(?) instead of Hindi text. and i'm using Devanagari Font to show the hindi text. is there any solution for this?
here is the code for how we are requesting?
adding parameters using Map like below.
Map<String, Object> map = new HashMap<String, Object>();
map.add("Key","Value");
map.add("Key1","Value1");
etc..
then passing this map object to requestService method.
private static Map<String, Object> requestService(Map<String, Object> data) {
Connection connection = null;
Dialog progress = new InfiniteProgress().showInifiniteBlocking();
try {
connection = new Connection(data);
NetworkManager networkManager = NetworkManager.getInstance();
networkManager.addToQueueAndWait(connection);
networkManager.setTimeout(600000);
if(connection.getResponseData() == null) {
return null;
}
} finally {
progress.dispose();
}
JSONParser jp = new JSONParser();
try {
Map<String, Object> result = jp.parseJSON(new InputStreamReader(new ByteArrayInputStream(connection.getResponseData()), "UTF-8"));
return result;
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
Connection Class:
private static class Connection extends ConnectionRequest {
private final static char escapeS[] = new char[] { '"', '\\', '/', '\b', '\f', '\n', '\r', '\t' };
private final static char escapeR[] = new char[] { '"', '\\', '/', 'b', 'f', 'n', 'r', 't' };
private Map<String, Object> data;
private Connection(Map<String, Object> data) {
this.data = data;
setFailSilently(true);
setPost(true);
setWriteRequest(true);
setContentType("application/json");
setUrl(serverUrl);
}
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
String v = buildJSON(data);
if(shouldWriteUTFAsGetBytes()) {
os.write(v.getBytes("UTF-8"));
} else {
OutputStreamWriter w = new OutputStreamWriter(os, "UTF-8");
w.write(v);
}
}
private static String buildJSON(Map<String, Object> data) {
StringBuilder json = new StringBuilder();
buildJSON(data, json);
return json.toString();
}
#SuppressWarnings("unchecked")
private static void buildJSON(Map<String, Object> data, StringBuilder json) {
json.append('{');
boolean first = true;
Object value;
for(String key: data.keySet()) {
value = data.get(key);
if(value == null) {
continue;
}
if(first) {
first = false;
} else {
json.append(",");
}
json.append('"').append(key).append("\":");
if(value instanceof Map) {
buildJSON((Map<String, Object>) value, json);
} else if(value instanceof Collection) {
buildJSON((Collection<Map<String, Object>>)value, json);
} else {
if(value instanceof Long || value instanceof Integer || value instanceof Double
|| value instanceof Short || value instanceof Float) {
json.append(value);
} else if(value instanceof Boolean) {
json.append((Boolean)value ? "true" : "false");
} else {
json.append('"').append(escape(value)).append('"');
}
}
}
json.append('}');
}
private static void buildJSON(Collection<Map<String, Object>> data, StringBuilder json) {
json.append('[');
boolean first = true;
for(Map<String, Object> e: data) {
if(first) {
first = false;
} else {
json.append(",");
}
buildJSON(e, json);
}
json.append(']');
}
private static String escape(Object any) {
if(any == null) {
return "";
}
String s = any.toString();
if(s == null) {
return "";
}
for(int i = 0; i < escapeS.length; i++) {
s = replace(s, escapeS[i], escapeR[i]);
}
return s;
}
private static String replace(String s, char c, char r) {
int i = s.indexOf(c);
if(i < 0) {
return s;
}
return s.substring(0, i) + "\\" + r + replace(s.substring(i + 1), c, r);
}
}
please guide me to achieve this?

That means the result is encoded in a foreign language encoding and should be read using the correct hindi text encoding.

Related

Vaadin upload with PipedInputStream & PipedOutputStream example

I just started learning Vaadin 8 and my first example is Upload button. I was stuck with an issue where I could not solve the problem for many hours and hours.
Here it is,
I am returning PipedOutputStream in the receiveUpload method,
Here is the code for receiveUpload method,
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
pipedInputStream = new PipedInputStream(pipedOutputStream);
if (filename == null || filename.trim().length() == 0) {
upload.interruptUpload();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return pipedOutputStream;
}
In the uploadSucceeded method, I need to take the pipedinputstream and send it another method to load the stream into the database
public void uploadSucceeded(SucceededEvent event) {
try {
fileUploadOperation.upload(pipedInputStream); --> I need to push all the stream data in one go into a method to generate a file at the business layer
} catch (Exception e) {
e.printStackTrace();
}
}
When I was running the application, it hangs out for a long time and I could not figure out where it is. Later I could notice that both piped input and piped output streams should be created in separate threads or at least one of them in a separate thread but don't know how to handle it.
Any help
I am pasting the complete class for more information,
public class WebCommunityView implements Receiver, FailedListener, SucceededListener, StartedListener, FinishedListener {
private PipedOutputStream pipedOutputStream = null;
private PipedInputStream pipedInputStream = null;
private Upload upload = null;
private String fileName = null, mimeType = null;
private Grid<FileListProperties> fileListGrid = null;
public final static WebCommunityView newInstance(WebContentScreen screen) {
vw.initBody();
return vw;
}
protected void initBody() {
VerticalLayout verticalLayout = new VerticalLayout();
fileListGrid = new Grid<FileListProperties>();
fileListGrid.addColumn(FileListProperties::getCreatedDate).setCaption("Date");
fileListGrid.addColumn(FileListProperties::getFileName).setCaption("File Name");
fileListGrid.addColumn(FileListProperties::getUserName).setCaption("User Name");
fileListGrid.addComponentColumn(this::buildDownloadButton).setCaption("Download");
fileListGrid.setItems(loadGridWithFileInfo());
upload = new Upload("", this);
upload.setImmediateMode(false);
upload.addFailedListener((Upload.FailedListener) this);
upload.addSucceededListener((Upload.SucceededListener) this);
upload.addStartedListener((Upload.StartedListener) this);
upload.addFinishedListener((Upload.FinishedListener) this);
Label fileUploadLabel = new Label("Label"));
verticalLayout.addComponent(currentListLabel);
verticalLayout.addComponent(fileListGrid);
verticalLayout.addComponent(fileUploadLabel);
verticalLayout.addComponent(upload);
mainbody.addComponent(verticalLayout);
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
//Model Layer
fileUploadOperation.upload(pipedInputStream);
fileUploadOperation.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null) {
Notification.show("Upload failed", Notification.Type.HUMANIZED_MESSAGE);
}
try {
//Model Layer
fileUploadOperation.abort();
} catch (Exception e) {
e.printStackTrace();
}
}
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
new Thread() {
public void run() {
try {
System.out.println("pipedInputStream Thread started");
pipedInputStream = new PipedInputStream(pipedOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
if (filename == null || filename.trim().length() == 0) {
screen.displayMessage("Please select a file to upload !", WebContentScreen.MESSAGE_TYPE_WARNING);
upload.interruptUpload();
} else {
Properties properties = new Properties();
properties.setProperty("NAME", fileName);
properties.setProperty("MIME_TYPE", mimeType);
//Model Layer
fileUploadOperation.initialize(properties);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("pipedOutputStream:"+pipedOutputStream);
return pipedOutputStream;
}
private List<FileListProperties> loadGridWithFileInfo() {
List<FileListProperties> list = null;
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
try {
list = new ArrayList<FileListProperties>(1);
Collection<FileInfo> fileInfoList = fileCommandQuery.lstFilesForDownload();
for (Iterator iterator = fileInfoList.iterator(); iterator.hasNext();) {
FileInfo fileInfo = (FileInfo) iterator.next();
Properties properties = fileInfo.getProperties();
Collection<String> mandatoryParameters = fileInfo.getMandatoryProperties();
FileListProperties fileListProperties = new FileListProperties();
for (Iterator iterator2 = mandatoryParameters.iterator(); iterator2.hasNext();) {
String key = (String) iterator2.next();
String value = properties.getProperty(key);
if (key != null && key.equalsIgnoreCase("NAME")) {
fileListProperties.setFileName(value);
} else if (key != null && key.equalsIgnoreCase("USER_NAME")) {
fileListProperties.setUserName(value);
} else if (key != null && key.equalsIgnoreCase("CREATED_DATE")) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1550566760000L);
fileListProperties.setCreatedDate(dateFormat.format(calendar.getTime()));
}
}
if (fileListProperties != null) {
list.add(fileListProperties);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dateFormat = null;
}
return list;
}
private Button buildDownloadButton(FileListProperties fileListProperties) {
Button button = new Button("...");
button.addClickListener(e -> downloadFile(fileListProperties));
return button;
}
private void downloadFile(FileListProperties fileListProperties) {
}
}
The problem in your example is that you need to do the actual file handling in a separate thread. The Viritin add-on contains a component called UploadFileHandler that simplifies this kind of usage a lot. It will provide you InputStream to consume. The integration test for the component contains this kind of usage example.
Also, my recent blog entry about the subject might help.

JSF2.0 multi-language composite component

To internationalize a composite component, you have to put a .properties file that has the exact same name than the component itself and in the same folder.
From the xhtml, you can access these translations through ${cc.resourceBundleMap.key}.
Until now, all is fine and works for me. Where the problems starts is when I add more .properties files for other languages. No matter which local is my computer in, the picked language is the default one (component.properties).
This seems to be a recurrent problem since Ziletka also reports the same problem in How to localize JSF 2 composite components, but remained unanswered.
I have tried all sort of possibilities:
no default .properties file
component_fr.properties
component_fr_CA.properties
component_fr_FR.properties
component_en.properties
component_en_CA.properties
component_en_US.properties
but it results in a:
javax.el.ELException: [...] /resources/component/component.xhtml default="${cc.resourceBundleMap.key}": java.lang.NullPointerException
with default .properties file plus Language specification
component.properties
component_fr.properties
component_en.properties
only the default is loaded.
with default .properties file plus Language and Country specifications
component.properties
component_fr_CA.properties
component_fr_FR.properties
component_en_CA.properties
component_en_US.properties
And again: only the default is loaded.
I would love to avoid having to rely on the backing bean to provide the translations and can't resolve into believing that it is not supported. Can anyone help?
This feature was implemented long time ago in MyFaces Core. See: MYFACES-3308. The test case done can be found here
The locale applied to the composite component depends on the value retrieved from UIViewRoot.getLocale().
Apparently the problem is still there and its root is in the javax.faces.component.UIComponent class particularly in the findComponentResourceBundleLocaleMatch method. The snipped is below
private Resource findComponentResourceBundleLocaleMatch(FacesContext context,
String resourceName, String libraryName) {
Resource result = null;
ResourceBundle resourceBundle = null;
int i;
if (-1 != (i = resourceName.lastIndexOf("."))) {
resourceName = resourceName.substring(0, i) +
".properties"; //THE PROBLEM IS HERE
if (null != context) {
result = context.getApplication().getResourceHandler().
createResource(resourceName, libraryName);
InputStream propertiesInputStream = null;
try {
propertiesInputStream = result.getInputStream();
resourceBundle = new PropertyResourceBundle(propertiesInputStream);
} catch (IOException ex) {
Logger.getLogger(UIComponent.class.getName()).log(Level.SEVERE, null, ex);
} finally{
if(null != propertiesInputStream){
try{
propertiesInputStream.close();
} catch(IOException ioe){
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE, null, ioe);
}
}
}
}
}
}
result = (null != resourceBundle) ? result : null;
return result;
}
You can see it at the line with a comment that states 'THE PROBLEM IS HERE'. Precisely when it looks for a properties file to load it does not respect any language and/or country code. It always loads a default resource.
Possible solution
The 'problematic' method is called from another method getResourceBundleMap of the same class and a part of the code you are interested in is marked with a comment (line #1000)
// Step 2: if this is a composite component, look for a
// ResourceBundle as a Resource
Which is no surprise as you need a composite component. So the solution would be to define a backing component class for your composite component and redefine resourceBundleMap loading. Below you may find the implementation that respects language only which means it would work for files like componentName_en.properties and componentName_de.properties but would not for something like componentName_en_US.properties
Your .properties files should be in the same directory as the definition of your component
testComponent.properties
testComponent_de.properties
testComponent_en.properties
testComponent_fr.properties
in your component testComponent.xhtmlspecify a definition class in componentType attribute.
<cc:interface componentType="test.component">
....
</cc:interface>
The component may look as following. I used the original code mostly with couple changes. The idea is to override the problematic method and withing the code try reading a properties file for a specified language first and if it is not found, read the default one.
#FacesComponent("test.component")
public class TestComponent extends UINamingContainer {
private static final String PROPERTIES_EXT = ".properties";
private Logger LOGGER = <use one you like>;
private Map<String, String> resourceBundleMap = null;
#Override
public Map<String, String> getResourceBundleMap() {
ResourceBundle resourceBundle = null;
if (null == resourceBundleMap) {
FacesContext context = FacesContext.getCurrentInstance();
UIViewRoot root = context.getViewRoot();
Locale currentLocale = null;
if (null != context) {
if (null != root) {
currentLocale = root.getLocale();
}
}
if (null == currentLocale) {
currentLocale = Locale.getDefault();
}
if (this.getAttributes().containsKey(Resource.COMPONENT_RESOURCE_KEY)) {
Resource ccResource = (Resource)
this.getAttributes().get(Resource.COMPONENT_RESOURCE_KEY);
if (null != ccResource) {
InputStream propertiesInputStream = null;
try {
propertiesInputStream = ccResource.getInputStream();
resourceBundle = findComponentResourceBundleLocaleMatch(ccResource.getResourceName(),
ccResource.getLibraryName(), currentLocale.getLanguage());
} catch (IOException ex) {
LOGGER.error(null, ex);
} finally {
if (null != propertiesInputStream) {
try {
propertiesInputStream.close();
} catch (IOException ioe) {
LOGGER.error(null, ioe);
}
}
}
}
}
if (null != resourceBundle) {
final ResourceBundle bundle = resourceBundle;
resourceBundleMap =
new Map() {
// this is an immutable Map
public String toString() {
StringBuffer sb = new StringBuffer();
Iterator<Map.Entry<String, Object>> entries =
this.entrySet().iterator();
Map.Entry<String, Object> cur;
while (entries.hasNext()) {
cur = entries.next();
sb.append(cur.getKey()).append(": ").append(cur.getValue()).append('\n');
}
return sb.toString();
}
// Do not need to implement for immutable Map
public void clear() {
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key) {
boolean result = false;
if (null != key) {
result = (null != bundle.getObject(key.toString()));
}
return result;
}
public boolean containsValue(Object value) {
Enumeration<String> keys = bundle.getKeys();
boolean result = false;
while (keys.hasMoreElements()) {
Object curObj = bundle.getObject(keys.nextElement());
if ((curObj == value) ||
((null != curObj) && curObj.equals(value))) {
result = true;
break;
}
}
return result;
}
public Set<Map.Entry<String, Object>> entrySet() {
HashMap<String, Object> mappings = new HashMap<String, Object>();
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object value = bundle.getObject(key);
mappings.put(key, value);
}
return mappings.entrySet();
}
#Override
public boolean equals(Object obj) {
return !((obj == null) || !(obj instanceof Map))
&& entrySet().equals(((Map) obj).entrySet());
}
public Object get(Object key) {
if (null == key) {
return null;
}
try {
return bundle.getObject(key.toString());
} catch (MissingResourceException e) {
return "???" + key + "???";
}
}
public int hashCode() {
return bundle.hashCode();
}
public boolean isEmpty() {
Enumeration<String> keys = bundle.getKeys();
return !keys.hasMoreElements();
}
public Set keySet() {
Set<String> keySet = new HashSet<String>();
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
keySet.add(keys.nextElement());
}
return keySet;
}
// Do not need to implement for immutable Map
public Object put(Object k, Object v) {
throw new UnsupportedOperationException();
}
// Do not need to implement for immutable Map
public void putAll(Map t) {
throw new UnsupportedOperationException();
}
// Do not need to implement for immutable Map
public Object remove(Object k) {
throw new UnsupportedOperationException();
}
public int size() {
int result = 0;
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
keys.nextElement();
result++;
}
return result;
}
public java.util.Collection values() {
ArrayList<Object> result = new ArrayList<Object>();
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
result.add(
bundle.getObject(keys.nextElement()));
}
return result;
}
};
}
if (null == resourceBundleMap) {
resourceBundleMap = Collections.EMPTY_MAP;
}
}
return resourceBundleMap;
}
private ResourceBundle findComponentResourceBundleLocaleMatch(String resourceName, String libraryName, String lng) {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle resourceBundle = null;
int i;
if (-1 != (i = resourceName.lastIndexOf("."))) {
if (null != context) {
InputStream propertiesInputStream = null;
try {
propertiesInputStream = getResourceInputStream(context, resourceName.substring(0, i), libraryName, lng);
resourceBundle = new PropertyResourceBundle(propertiesInputStream);
} catch (IOException ex) {
LOGGER.error(null, ex);
} finally {
if (null != propertiesInputStream) {
try {
propertiesInputStream.close();
} catch (IOException ioe) {
LOGGER.error(null, ioe);
}
}
}
}
}
return resourceBundle;
}
private InputStream getResourceInputStream(FacesContext context, final String resourceName, String libraryName, String lng) throws IOException {
InputStream propertiesInputStream = null;
propertiesInputStream = getPropertiesResourceInputStream(context, String.format("%s_%s%s", resourceName, lng, PROPERTIES_EXT), libraryName);
if (null == propertiesInputStream) {
propertiesInputStream = getPropertiesResourceInputStream(context, resourceName + PROPERTIES_EXT, libraryName);
}
return propertiesInputStream;
}
private InputStream getPropertiesResourceInputStream(FacesContext context, final String resourceName, String libraryName) throws IOException {
Resource result = context.getApplication().getResourceHandler().createResource(resourceName, libraryName);
if (null == result) {
return null;
}
return result.getInputStream();
}
}
Done.
However that is obviously a bug in the Mojarra and I hope it will be fixed soon. Closer look to the code related to the composite components reveals that the default .properties file for a component is read twice which I guess is not a very good idea too, but this is another story.
PS. You may easily adjust te code to respect country code as well if you wish.

Background Application unable to display UI when receive push notification

Here is my full push notification listener.
public class MyApp extends UiApplication {
public static void main(String[] args) {
PushAgent pa = new PushAgent();
pa.enterEventDispatcher();
}
}
Is this class extended correctly?
public class PushAgent extends Application {
private static final String PUSH_PORT = "32023";
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = "2727-c55087eR3001rr475448i013212a56shss2";
private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=mds-public";
public static final long ID = 0x749cb23a75c60e2dL;
private MessageReadingThread messageReadingThread;
public PushAgent() {
if (!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) {
return;
}
if (DeviceInfo.isSimulator()) {
return;
}
messageReadingThread = new MessageReadingThread();
messageReadingThread.start();
registerBpas();
}
private static class MessageReadingThread extends Thread {
private boolean running;
private ServerSocketConnection socket;
private HttpServerConnection conn;
private InputStream inputStream;
private PushInputStream pushInputStream;
public MessageReadingThread() {
this.running = true;
}
public void run() {
String url = "http://:" + PUSH_PORT + CONNECTION_SUFFIX;
try {
socket = (ServerSocketConnection) Connector.open(url);
} catch (IOException ex) {
}
while (running) {
try {
Object o = socket.acceptAndOpen();
conn = (HttpServerConnection) o;
inputStream = conn.openInputStream();
pushInputStream = new MDSPushInputStream(conn, inputStream);
PushMessageReader.process(pushInputStream, conn);
} catch (Exception e) {
if (running) {
running = false;
}
} finally {
close(conn, pushInputStream, null);
}
}
}
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
private String formRegisterRequest(String bpasUrl, String appId,
String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
private void registerBpas() {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null)
+ CONNECTION_SUFFIX;
Object theSource = new Object() {
public String toString() {
return "Oriental Daily";
}
};
NotificationsManager.registerSource(ID, theSource,
NotificationsConstants.IMPORTANT);
new Thread() {
public void run() {
try {
HttpConnection httpConnection = (HttpConnection) Connector
.open(registerUrl);
InputStream is = httpConnection.openInputStream();
String response = new String(IOUtilities.streamToBytes(is));
close(httpConnection, is, null);
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID,
response) + CONNECTION_SUFFIX;
HttpConnection nextHttpConnection = (HttpConnection) Connector
.open(nextUrl);
InputStream nextInputStream = nextHttpConnection
.openInputStream();
response = new String(
IOUtilities.streamToBytes(nextInputStream));
close(nextHttpConnection, is, null);
} catch (IOException e) {
}
}
}.start();
}
}
}
This is the process;
public class PushMessageReader {
private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
private static final String MESSAGE_TYPE_TEXT = "text";
private static final String MESSAGE_TYPE_IMAGE = "image";
private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
private static byte historyIndex;
private static byte[] buffer = new byte[15 * 1024];
private static byte[] imageBuffer = new byte[10 * 1024];
public static final long ID = 0x749cb23a75c60e2dL;
public static Bitmap popup = Bitmap.getBitmapResource("icon_24.png");
private PushMessageReader() {
}
public static void process(PushInputStream pis, Connection conn) {
try {
HttpServerConnection httpConn;
if (conn instanceof HttpServerConnection) {
httpConn = (HttpServerConnection) conn;
} else {
throw new IllegalArgumentException(
"Can not process non-http pushes, expected HttpServerConnection but have "
+ conn.getClass().getName());
}
String msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
String msgType = httpConn.getType();
String encoding = httpConn.getEncoding();
if (!alreadyReceived(msgId)) {
byte[] binaryData;
if (msgId == null) {
msgId = String.valueOf(System.currentTimeMillis());
}
if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
int size = pis.read(buffer);
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
NotificationsManager.triggerImmediateEvent(ID, 0, null,
null);
processTextMessage(buffer);
} else if (msgType.indexOf(MESSAGE_TYPE_IMAGE) >= 0) {
int size = pis.read(buffer);
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
Base64InputStream bis = new Base64InputStream(
new ByteArrayInputStream(buffer, 0, size));
size = bis.read(imageBuffer);
}
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
}
}
pis.accept();
} catch (Exception e) {
} finally {
PushAgent.close(conn, pis, null);
}
}
private static boolean alreadyReceived(String id) {
if (id == null) {
return false;
}
if (Arrays.contains(messageIdHistory, id)) {
return true;
}
messageIdHistory[historyIndex++] = id;
if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
historyIndex = 0;
}
return false;
}
private static void processTextMessage(final byte[] data) {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
GlobalDialog screen = new GlobalDialog("New Notification",
"Article ID : " + new String(data), new String(data));
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
static class GlobalDialog extends PopupScreen implements
FieldChangeListener {
ButtonField mOKButton = new ButtonField("OK", ButtonField.CONSUME_CLICK
| FIELD_HCENTER);
String data = "";
public GlobalDialog(String title, String text, String data) {
super(new VerticalFieldManager());
this.data = data;
add(new LabelField(title));
add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
add(new LabelField(text, DrawStyle.HCENTER));
mOKButton.setChangeListener(this);
add(mOKButton);
}
public void fieldChanged(Field field, int context) {
if (mOKButton == field) {
try {
ApplicationManager.getApplicationManager().launch(
"OrientalDailyBB");
ApplicationManager.getApplicationManager().postGlobalEvent(
ID, 0, 0, data, null);
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
reg.unregister();
close();
} catch (ApplicationManagerException e) {
}
}
}
}
}
In this project, I checked Auto-run on startup so that this background app listener will run all the time and set the start tier to 7 in the BB App Descriptor.
However, it cannot display the popup Dialog, but I can see the device has received the push notification.
After the dialog popup and user click OK will start the OrientalDailyBB project and display the particular MainScreen.
FYI: The listener priority is higher than the OrientalDailyBB project because it is a background application. So when I install OrientalDailyBB, it will install this listener too. It happened because this listener is not in the OrientalDailyBB project folder, but is in a different folder. I did separate them to avoid the background application being terminated when the user quits from OrientalDailyBB.
I believe that this is a threading problem. pushGlobalScreen is a message you could try to use with invokeLater.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
});
you could try to push the application to the foreground too.

Blackberry: Multiline ListView

I have made list view with checkboxes. I have read similar articles n many people have suggested to do changes in drawlistRow but it is not happening. Can u suggest me where should i change to make it a multi line list.The code snippet is :
Updated: I updated my code and it is still not working
public class CheckboxListField extends MainScreen implements ListFieldCallback, FieldChangeListener {
int mCheckBoxesCount = 5;
private Vector _listData = new Vector();
private ListField listField;
private ContactList blackBerryContactList;
private BlackBerryContact blackBerryContact;
private Vector blackBerryContacts;
private MenuItem _toggleItem;
ButtonField button;
BasicEditField mEdit;
CheckboxField cb;
CheckboxField[] chk_service;
HorizontalFieldManager hm4;
CheckboxField[] m_arrFields;
boolean mProgrammatic = false;
public static StringBuffer sbi = new StringBuffer();
VerticalFieldManager checkBoxGroup = new VerticalFieldManager();
LabelField task;
//A class to hold the Strings in the CheckBox and it's checkbox state (checked or unchecked).
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData()
{
_stringVal = "";
_checked = false;
}
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
private void setStringVal(String stringVal)
{
_stringVal = stringVal;
}
private void setChecked(boolean checked)
{
_checked = checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
CheckboxListField()
{
_toggleItem = new MenuItem("Change Option", 200, 10)
{
public void run()
{
//Get the index of the selected row.
int index = listField.getSelectedIndex();
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index);
//Invalidate the modified row of the ListField.
listField.invalidate(index);
if (index != -1 && !blackBerryContacts.isEmpty())
{
blackBerryContact =
(BlackBerryContact)blackBerryContacts.
elementAt(listField.getSelectedIndex());
ContactDetailsScreen contactDetailsScreen =
new ContactDetailsScreen(blackBerryContact);
UiApplication.getUiApplication().pushScreen(contactDetailsScreen);
}
}
};
listField = new ListField();
listField.setRowHeight(getFont().getHeight() * 2);
listField.setCallback(this);
reloadContactList();
//CheckboxField[] cb = new CheckboxField[blackBerryContacts.size()];
for(int count = 0; count < blackBerryContacts.size(); ++count)
{
BlackBerryContact item =
(BlackBerryContact)blackBerryContacts.elementAt(count);
String displayName = getDisplayName(item);
CheckboxField cb = new CheckboxField(displayName, false);
cb.setChangeListener(this);
add(cb);
listField.insert(count);
}
blackBerryContacts.addElement(cb);
add(checkBoxGroup);
}
protected void makeMenu(Menu menu, int instance)
{
menu.add(new MenuItem("Get", 2, 2) {
public void run() {
for (int i = 0; i < checkBoxGroup.getFieldCount(); i++) {
//for(int i=0; i<blackBerryContacts.size(); i++) {
CheckboxField checkboxField = (CheckboxField)checkBoxGroup
.getField(i);
if (checkboxField.getChecked()) {
sbi.append(checkboxField.getLabel()).append("\n");
}
}
Dialog.inform("Selected checkbox text::" + sbi);
}
});
super.makeMenu(menu, instance);
}
private boolean reloadContactList()
{
try {
blackBerryContactList =
(ContactList)PIM.getInstance().openPIMList
(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration allContacts = blackBerryContactList.items();
blackBerryContacts = enumToVector(allContacts);
listField.setSize(blackBerryContacts.size());
return true;
} catch (PIMException e)
{
return false;
}
}
//Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list, Graphics graphics, int index, int y, int w)
{
ChecklistData currentRow = (ChecklistData)this.get(list, index);
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked())
{
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else
{
rowString.append(Characters.BALLOT_BOX);
}
//Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
//graphics.drawText("ROW", 0, y, 0, w);
//String rowNumber = "one";
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*graphics.drawText("ROW " + rowNumber, y, 0, w);
graphics.drawText("ROW NAME", y, 20, w);
graphics.drawText("row details", y + getFont().getHeight(), 20, w); */
}
public void drawRow(Graphics g, int x, int y, int width, int height) {
// Arrange the cell fields within this row manager.
layout(width, height);
// Place this row manager within its enclosing list.
setPosition(x, y);
// Apply a translating/clipping transformation to the graphics
// context so that this row paints in the right area.
g.pushRegion(getExtent());
// Paint this manager's controlled fields.
subpaint(g);
g.setColor(0x00CACACA);
g.drawLine(0, 0, getPreferredWidth(), 0);
// Restore the graphics context.
g.popContext();
}
public static String getDisplayName(Contact contact)
{
if (contact == null)
{
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " " + displayName;
}
return displayName;
}
}
return displayName;
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
/*if (listField == list)
{
//If index is out of bounds an exception will be thrown,
//but that's the behaviour we want in that case.
//return blackBerryContacts.elementAt(index);
_listData = (Vector) blackBerryContacts.elementAt(index);
return _listData.elementAt(index);
}
return null;*/
}
//Returns the first occurence of the given String, bbeginning the search at index,
//and testing for equality using the equals method.
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
//return _listData.indexOf(p, s);
return -1;
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Graphics.getScreenWidth();
//return Display.getWidth();
}
public void fieldChanged(Field field, int context) {
boolean mProgrammatic = false;
if (!mProgrammatic) {
mProgrammatic = true;
CheckboxField cbField = (CheckboxField) field;
int index = blackBerryContacts.indexOf(cbField);
if (cbField.getChecked())
{
for(int i=0;i<blackBerryContacts.size();i++)
{
Dialog.inform("Selected::" + cbField.getLabel());
sbi=new StringBuffer();
sbi.append(cbField.getLabel());
}
}
mProgrammatic = false;
}
}
This code may be improved with:
Using ListField instead of VerticalFieldManager + CheckboxField array (ListField is much more faster, 100+ controls may slow down UI)
Using simple array instead of vector in list data (it's faster)
Moving contacts load from UI thread (we should aware of blocking UI thread with heavy procedures like IO, networking or work with contact list)
Actually using ListField with two line rows has one issue: we have to set the same height for all rows in ListField. So there always will be two lines per row, no matter if we will use second line or not. But it's really better than UI performance issues.
See code:
public class CheckboxListField extends MainScreen implements
ListFieldCallback {
private ChecklistData[] mListData = new ChecklistData[] {};
private ListField mListField;
private Vector mContacts;
private MenuItem mMenuItemToggle = new MenuItem(
"Change Option", 0, 0) {
public void run() {
toggleItem();
};
};
private MenuItem mMenuItemGet = new MenuItem("Get", 0,
0) {
public void run() {
StringBuffer sbi = new StringBuffer();
for (int i = 0; i < mListData.length; i++) {
ChecklistData checkboxField = mListData[i];
if (checkboxField.isChecked()) {
sbi.append(checkboxField.getStringVal())
.append("\n");
}
}
Dialog.inform("Selected checkbox text::\n"
+ sbi);
}
};
// A class to hold the Strings in the CheckBox and it's checkbox state
// (checked or unchecked).
private class ChecklistData {
private String _stringVal;
private boolean _checked;
ChecklistData(String stringVal, boolean checked) {
_stringVal = stringVal;
_checked = checked;
}
// Get/set methods.
private String getStringVal() {
return _stringVal;
}
private boolean isChecked() {
return _checked;
}
// Toggle the checked status.
private void toggleChecked() {
_checked = !_checked;
}
}
CheckboxListField() {
// toggle list field item on navigation click
mListField = new ListField() {
protected boolean navigationClick(int status,
int time) {
toggleItem();
return true;
};
};
// set two line row height
mListField.setRowHeight(getFont().getHeight() * 2);
mListField.setCallback(this);
add(mListField);
// load contacts in separate thread
loadContacts.run();
}
protected Runnable loadContacts = new Runnable() {
public void run() {
reloadContactList();
// fill list field control in UI event thread
UiApplication.getUiApplication().invokeLater(
fillList);
}
};
protected Runnable fillList = new Runnable() {
public void run() {
int size = mContacts.size();
mListData = new ChecklistData[size];
for (int i = 0; i < mContacts.size(); i++) {
BlackBerryContact item = (BlackBerryContact) mContacts
.elementAt(i);
String displayName = getDisplayName(item);
mListData[i] = new ChecklistData(
displayName, false);
}
mListField.setSize(size);
}
};
protected void toggleItem() {
// Get the index of the selected row.
int index = mListField.getSelectedIndex();
if (index != -1) {
// Get the ChecklistData for this row.
ChecklistData data = mListData[index];
// Toggle its status.
data.toggleChecked();
// Invalidate the modified row of the ListField.
mListField.invalidate(index);
BlackBerryContact contact = (BlackBerryContact) mContacts
.elementAt(mListField
.getSelectedIndex());
// process selected contact here
}
}
protected void makeMenu(Menu menu, int instance) {
menu.add(mMenuItemToggle);
menu.add(mMenuItemGet);
super.makeMenu(menu, instance);
}
private boolean reloadContactList() {
try {
ContactList contactList = (ContactList) PIM
.getInstance()
.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
Enumeration allContacts = contactList.items();
mContacts = enumToVector(allContacts);
mListField.setSize(mContacts.size());
return true;
} catch (PIMException e) {
return false;
}
}
// Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list,
Graphics graphics, int index, int y, int w) {
Object obj = this.get(list, index);
if (obj != null) {
ChecklistData currentRow = (ChecklistData) obj;
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked()) {
rowString
.append(Characters.BALLOT_BOX_WITH_CHECK);
} else {
rowString.append(Characters.BALLOT_BOX);
}
// Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
// Draw the text.
graphics.drawText(rowString.toString(), 0, y,
0, w);
String secondLine = "Lorem ipsum dolor sit amet, "
+ "consectetur adipiscing elit.";
graphics.drawText(secondLine, 0, y
+ getFont().getHeight(),
DrawStyle.ELLIPSIS, w);
} else {
graphics.drawText("No rows available.", 0, y,
0, w);
}
}
public static String getDisplayName(Contact contact) {
if (contact == null) {
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(
Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " "
+ displayName;
}
return displayName;
}
}
return displayName;
}
// Returns the object at the specified index.
public Object get(ListField list, int index) {
Object result = null;
if (mListData.length > index) {
result = mListData[index];
}
return result;
}
// Returns the first occurrence of the given String,
// beginning the search at index, and testing for
// equality using the equals method.
public int indexOfList(ListField list, String p, int s) {
return -1;
}
// Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list) {
return Graphics.getScreenWidth();
// return Display.getWidth();
}
}
Have a nice coding!

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