I want all the information associated with jad files in blackberry.how should i get it?
try the following code please note that
this is work on Device only dont test on emulator
import java.util.Enumeration;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.CodeModuleGroup;
import net.rim.device.api.system.CodeModuleGroupManager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class StartUp extends UiApplication{
public static void main(String[] args) {
StartUp up=new StartUp();
up.enterEventDispatcher();
}
public StartUp()
{
MainScreen screen=new MainScreen();
CodeModuleGroup cmg = null;
CodeModuleGroup[] allGroups = CodeModuleGroupManager.loadAll();
String moduleName = ApplicationDescriptor.currentApplicationDescriptor().getModuleName();
for (int i = 0; i < allGroups.length; i++) {
if (allGroups[i].containsModule(moduleName)) {
cmg = allGroups[i];
break;
}
}
if (cmg == null) {
screen.add(new LabelField("not able to fetch properties"));
} else {
double size=0;
for (Enumeration e = cmg.getPropertyNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
String value = cmg.getProperty(name);
System.out.println(name+" : "+value);
screen.add(new LabelField(name+" : "+value,Field.FOCUSABLE));
}
}
UiApplication.getUiApplication().pushScreen(screen);
}
}
Related
I am having an issue when mocking URL and HttpURLConnection class.
TestNG is being used as the testing framework because of a limitation that we have.
The test class looks like the following
package com.ericsson.msran.test.stability.environmentmanager.service.batc.restore;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.entity.ContentType;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.ericsson.msran.test.stability.environmentmanager.service.Service;
import com.ericsson.msran.test.stability.environmentmanager.service.ServiceException;
import com.ericsson.msran.test.stability.environmentmanager.service.batc.BatCConfig;
import com.ericsson.msran.test.stability.environmentmanager.service.batc.BatCServiceException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
#PowerMockIgnore({ "org.apache.logging.log4j.*" })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ BatCConfig.class, Service.class })
public class RestoreSnapshotServiceTest extends PowerMockTestCase {
HttpURLConnection httpURLConnection;
URL mockedURL;
#BeforeClass
public void setUp() throws MalformedURLException, IOException {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(BatCConfig.class);
}
#Test
public void testRestoreSnapshot() throws Exception {
String jsonResponse = "{\"apiVersion\":\"0.1.0\",\"method\":\"restoreCampaignSnapshot\",\"params\":{\"campaignSnapshotId\":3,\"campaignName\":\"testCampaign3\"},\"data\":{\"newCampaignId\":607}}";
JsonObject response = new JsonParser().parse(jsonResponse).getAsJsonObject();
Mockito.when(BatCConfig.getBatCServiceUrl()).thenReturn(new URL("https://lte-iov.rnd.ki.sw.ericsson.se/batc/"));
mockedURL = PowerMockito.mock(URL.class);
httpURLConnection = PowerMockito.mock(HttpURLConnection.class);
PowerMockito.whenNew(URL.class).withArguments("https://lte-iov.rnd.ki.sw.ericsson.se/batc/restoreCampaignSnapshot").thenReturn(mockedURL);
Mockito.when(mockedURL.openConnection()).thenReturn(httpURLConnection);
Mockito.when(httpURLConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_GATEWAY);
Mockito.when(httpURLConnection.getContentType()).thenReturn(ContentType.APPLICATION_JSON.getMimeType());
Mockito.doNothing().when(httpURLConnection).connect();
Mockito.when(httpURLConnection.getOutputStream()).thenReturn(null);
Mockito.when(httpURLConnection.getInputStream()).thenReturn(new ByteArrayInputStream(jsonResponse.getBytes()));
String name = RestoreSnapshotService.restoreSnapshot(3, "testCampaign4");
Assert.assertEquals(name, "testCampaign4");
}
}
When I test the real class (Service) in this case, the mock is not being used but instead the real object. Any help is appreciated!
The sample code under test looks like the following
protected static JsonObject callEndpoint(URL url, ServiceRequestMethod requestMethod, JsonObject requestBody)
throws ServiceException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty(REQUEST_PROP_KEY, REQUEST_PROP_VAL);
connection.setConnectTimeout(REQUEST_TIMEOUT_MILLIS);
connection.setReadTimeout(REQUEST_TIMEOUT_MILLIS);
connection.setRequestMethod(requestMethod.name());
if (requestMethod == ServiceRequestMethod.POST) {
connection.setDoOutput(true);
}
connection.connect();
if (requestMethod == ServiceRequestMethod.POST) {
final OutputStream os = connection.getOutputStream();
os.write(requestBody.toString().getBytes("UTF-8"));
os.close();
}
final int status = connection.getResponseCode();
final String contentType = connection.getContentType();
log("Recieved response with status={} and ContentType={}", status, contentType);
if (HttpURLConnection.HTTP_OK == status && RESPONSE_TYPE_JSON.equals(contentType)) {
return mapResponse(connection.getInputStream());
} else {
throw new ServiceException("Response from service NOK, status=" + status);
}
} catch (IOException e) {
throw new ServiceException("Could not connect to service", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
I'm trying to put a String text to an edge of a JUNG tree graph. See bellow example.
What I tried is to simply add this line:
graph.addEdge("arrow", "Vmain", "Vsecond");
... but without any results (see bellow screenshot). I need some advices please.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.apache.commons.collections15.Factory;
import edu.uci.ics.jung.algorithms.layout.TreeLayout;
import edu.uci.ics.jung.graph.DirectedGraph;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.Forest;
import edu.uci.ics.jung.graph.DelegateForest;
import edu.uci.ics.jung.graph.DelegateTree;
import edu.uci.ics.jung.graph.Tree;
import edu.uci.ics.jung.visualization.GraphZoomScrollPane;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.CrossoverScalingControl;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ScalingControl;
import edu.uci.ics.jung.visualization.decorators.EdgeShape;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
public class TreeVisualiser extends JApplet {
Forest<String, String> graph;
Factory<DirectedGraph<String, String>> graphFactory = new Factory<DirectedGraph<String, String>>() {
public DirectedGraph<String, String> create() {
return new DirectedSparseMultigraph<String, String>();
}
};
Factory<Tree<String, String>> treeFactory = new Factory<Tree<String, String>>() {
public Tree<String, String> create() {
return new DelegateTree<String, String>(graphFactory);
}
};
VisualizationViewer<String, String> vv;
String root;
TreeLayout<String, String> treeLayout;
#SuppressWarnings({"rawtypes", "unchecked"})
public TreeVisualiser() {
// create a simple graph for the demo
graph = new DelegateForest<String, String>();
createTree();
treeLayout = new TreeLayout<String, String>(graph);
vv = new VisualizationViewer<String, String>(treeLayout, new Dimension(600, 600));
vv.setBackground(Color.white);
vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line());
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
// add a listener for ToolTips
vv.setVertexToolTipTransformer(new ToStringLabeller());
Container content = getContentPane();
final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
content.add(panel);
final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
vv.setGraphMouse(graphMouse);
JComboBox modeBox = graphMouse.getModeComboBox();
modeBox.addItemListener(graphMouse.getModeListener());
graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
final ScalingControl scaler = new CrossoverScalingControl();
JButton plus = new JButton("+");
plus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scaler.scale(vv, 1.1f, vv.getCenter());
}
});
JButton minus = new JButton("-");
minus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scaler.scale(vv, 1 / 1.1f, vv.getCenter());
}
});
JPanel scaleGrid = new JPanel(new GridLayout(1, 0));
scaleGrid.setBorder(BorderFactory.createTitledBorder("Zoom"));
JPanel controls = new JPanel();
scaleGrid.add(plus);
scaleGrid.add(minus);
controls.add(scaleGrid);
controls.add(modeBox);
content.add(controls, BorderLayout.SOUTH);
}
private void createTree() {
graph.addEdge("arrow", "Vmain", "Vsecond");
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Container content = frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content.add(new TreeVisualiser());
frame.pack();
frame.setVisible(true);
}
}
Oh, I missed this line of code. Now it is working as I want.
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
How can I lock the keypad in Blackberry application using "lockSystem" method in J2ME ??
And also the brightness of the blackberry should reduce to Zero ??
its really easy. I know the answer. We can just use the method "lockSystem". I have coded as following to lock the keypad. It takes long time for me to find it, but u got this.
package net.asem;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class LockBlackberry extends UiApplication
{
public static void main(String[] args)
{
LockBlackberry lockB = new LockBlackberry();
lockB.enterEventDispatcher();
}
LockBlackberry()
{
pushScreen(new myBlackBerryClass());
}
}
final class myBlackBerryClass extends MainScreen implements FieldChangeListener<br>
{
LabelField title;
ButtonField btn1;
myBlackBerryClass()
{
LabelField title = new LabelField("Title : Locking the Device.",LabelField.USE_ALL_WIDTH | LabelField.USE_ALL_WIDTH);
setTitle(title);
btn1 = new ButtonField("KeyPad Loack ?",ButtonField.CONSUME_CLICK);
btn1.setChangeListener(this);
add(btn1);
}
public void fieldChanged(Field field, int context)
{
if(field == btn1)
{
Click();
}
}
private void Click()
{
ApplicationManager manager = ApplicationManager.getApplicationManager();
manager.lockSystem(true);
}
}
I am trying to validate generated WSDL to be correct. I have tried WS-i test tool downloaded from http://www.ws-i.org/ but it's test tool require all input to go through a config xml and the output is again an output xml file. Is there other easier way of validating a WSDL?
The Woden library/jar provides adequate functionality to be able to do this. If your wsdl isn't valid, the last statement, reader.readWSDL(...), will throw an exception.
import static junit.framework.Assert.fail;
import java.net.URISyntaxException;
import org.apache.woden.WSDLException;
import org.apache.woden.WSDLFactory;
import org.apache.woden.WSDLReader;
import org.apache.woden.wsdl20.Description;
import org.junit.Test;
public class WSDLValidationTest {
String wsdlFileName = "/MyService.wsdl";
#Test
public void validateWSDL2() throws WSDLException {
String wsdlUri = null;
try {
wsdlUri = this.getClass().getResource(wsdlFileName).toURI().toString();
}
catch( URISyntaxException urise) {
urise.printStackTrace();
fail( "Unable to retrieve wsdl: " + urise.getMessage());
}
WSDLFactory factory = WSDLFactory.newInstance("org.apache.woden.internal.OMWSDLFactory");
WSDLReader reader = factory.newWSDLReader();
reader.setFeature(WSDLReader.FEATURE_VALIDATION, true);
reader.readWSDL(wsdlUri);
}
}
And should you need a unit test for WSDL 1.1, see the following:
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.fail;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.stream.XMLStreamException;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.sun.xml.ws.api.model.wsdl.WSDLModel;
import com.sun.xml.ws.api.server.SDDocumentSource;
import com.sun.xml.ws.api.wsdl.parser.WSDLParserExtension;
import com.sun.xml.ws.api.wsdl.parser.XMLEntityResolver;
public class WSDLValidationTest {
String wsdlFileName = "/MyService.wsdl";
String wsdlUri = null;
URL wsdlUrl = null;
#Before
public void before()
{
try {
wsdlUrl = this.getClass().getResource(wsdlFileName);
wsdlUri = wsdlUrl.toURI().toString();
}
catch( URISyntaxException urise) {
urise.printStackTrace();
fail( "Unable to retrieve wsdl: " + urise.getMessage());
}
}
#Test
public void parseAndValidateWSDL1_1WithWSDL4J() throws WSDLException
{
WSDLReader wsdlReader = null;
try {
WSDLFactory factory = WSDLFactory.newInstance();
wsdlReader = factory.newWSDLReader();
}
catch( WSDLException wsdle) {
wsdle.printStackTrace();
fail( "Unable to instantiate wsdl reader: " + wsdle.getMessage());
}
// Read WSDL service interface document
Definition def = wsdlReader.readWSDL(null, wsdlUri);
assertNotNull(def);
}
#Test
public void parseAndValidateWSDL1_1WithJaxWS() throws IOException, XMLStreamException, SAXException
{
final SDDocumentSource doc = SDDocumentSource.create(wsdlUrl);
final XMLEntityResolver.Parser parser = new XMLEntityResolver.Parser(doc);
WSDLModel model = WSDLModel.WSDLParser.parse( parser, null, false, new WSDLParserExtension[] {} );
assertNotNull(model);
}
}
I read Blackberry - How to get the background application process id but I'm not sure I understand it correctly. The following code gets the foreground process id;
ApplicationManager.getApplicationManager().getForegroundProcessId()
I have two processes which execute the same piece of code to make a connection, I want to log the process which made the calls along with all my usual logging data to get a better idea of how the flow is working.
Is it possible to get the id for the process which is currently running the code? One process is in the foreground (UI process) and the other is in the background but both use the same connection library shared via the runtime store.
Thanks in advance!
Gav
So you have three modules: application, library and service.
You need to get descriptor by module name, and then get process id.
UPDATE1
String moduleName = "application";
int handle = CodeModuleManager.getModuleHandle(moduleName);
ApplicationDescriptor[] descriptors = CodeModuleManager
.getApplicationDescriptors(handle);
if (descriptors.length > 0 && descriptors[0] != null) {
ApplicationManager.getApplicationManager().getProcessId(descriptors[0]);
}
Then, to log which module uses library, use
Application.getApplication().getProcessId();
inside library methods. I think its better to implement logging inside library.
When you got process id of application from library code, you can compare it with id's found by module name and then you will know what module uses library code.
UPDATE2
alt text http://img138.imageshack.us/img138/23/eventlog.jpg
library module code:
package library;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.system.CodeModuleManager;
import net.rim.device.api.system.EventLogger;
public class Logger {
// "AppLibSrvc" converted to long
long guid = 0xd4b6b5eeea339daL;
public Logger() {
EventLogger.register(guid, "AppLibSrvc", EventLogger.VIEWER_STRING);
}
public void log(String message) {
EventLogger.logEvent(guid, message.getBytes());
}
public void call() {
log("Library is used by " + getModuleName());
}
private String getModuleName() {
String moduleName = "";
String appModuleName = "application";
int appProcessId = getProcessIdByName(appModuleName);
String srvcModuleName = "service";
int srvcProcessId = getProcessIdByName(srvcModuleName);
int processId = Application.getApplication().getProcessId();
if (appProcessId == processId)
moduleName = appModuleName;
else if (srvcProcessId == processId)
moduleName = srvcModuleName;
return moduleName;
}
protected int getProcessIdByName(String moduleName) {
int processId = -1;
int handle = CodeModuleManager.getModuleHandle(moduleName);
ApplicationDescriptor[] descriptors = CodeModuleManager
.getApplicationDescriptors(handle);
if (descriptors.length > 0 && descriptors[0] != null) {
processId = ApplicationManager.getApplicationManager()
.getProcessId(descriptors[0]);
}
return processId;
}
}
application module code:
package application;
import java.util.Timer;
import java.util.TimerTask;
import library.Logger;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;
public class App extends UiApplication {
public App() {
pushScreen(new Scr());
}
public static void main(String[] args) {
App app = new App();
app.enterEventDispatcher();
}
}
class Scr extends MainScreen {
public Scr() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
Logger logger = new Logger();
logger.call();
}
};
timer.schedule(task, 3000, 3000);
}
}
service module code:
package service;
import java.util.Timer;
import java.util.TimerTask;
import library.Logger;
import net.rim.device.api.system.Application;
public class App extends Application {
public App() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
Logger logger = new Logger();
logger.call();
}
};
timer.schedule(task, 3000, 3000);
}
public static void main(String[] args) {
App app = new App();
app.enterEventDispatcher();
}
}