went I am running following code. the IP-adresse is not 192.168.1.99 but 192.168.1.45.
I hav change the IP-adresse, but it is still 192.168.1.45
Help and thanks.
namespace WeatherStation
{
public class Program
{
private static readonly string _mySsid = "network";
private static readonly string _myPassword = "password";
private static readonly IPConfiguration _configuration = new IPConfiguration("192.168.1.99", "255.255.255.0", "192.168.1.1");
public static void Main()
{
Debug.WriteLine("Starting weather statiom!");
try
{
Debug.WriteLine("Waiting for network up and IP address...");
CancellationTokenSource cs = new(60000);
bool success = WifiNetworkHelper.ConnectFixAddress(_mySsid, _myPassword, _configuration, requiresDateTime: true, token: cs.Token);
if (!success)
{
Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {WifiNetworkHelper.Status}.");
if (WifiNetworkHelper.HelperException != null)
{
Debug.WriteLine($"Exception: {WifiNetworkHelper.HelperException}");
}
return;
}
Debug.WriteLine("Network is up and running");
Thread.Sleep(Timeout.Infinite);
}
catch (Exception ex)
{
Debug.WriteLine($"{ex}");
}
}
}
}
Related
I'm trying to upgrade a Windows desktop application from .Net Framework to .Net (Core) 6.0. As part of that, I need to use NetMQ instead of the old clrzmq. But every reference I find for how to do a simple request-response using the new API has been obsoleted by subsequent updates. I found working code at this question, but again, some of the methods used no longer exist. I attempted to convert the source reasonably and arrived at the below.
The server prints nothing; the client claims to be sending messages; Wireshark sees no messages on "port 5556". (I tagged Wireshark in case I'm using it wrong.)
I think if I can find out how this code should work I can properly convert my original application. Any help would be much appreciated.
Program.cs (by itself in its own solution, for the server):
using NetMQ;
using NetMQ.Sockets;
using NLog;
class Program
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
try
{
using (var responseSocket = new ResponseSocket())
{
responseSocket.Connect("tcp://localhost:5556");
var poller = new NetMQPoller();
responseSocket.ReceiveReady += RouterSocketOnReceiveReady;
poller.Add(responseSocket);
poller.Run();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
}
private static void RouterSocketOnReceiveReady(object? sender, NetMQSocketEventArgs netMqSocketEventArgs)
{
NetMQMessage? clientMessage = new();
bool result = netMqSocketEventArgs.Socket.TryReceiveMultipartMessage(new TimeSpan(0, 0, 0, 5),
ref clientMessage, 5);
if (result == false || clientMessage == null)
{
Console.WriteLine("Something went wrong?!");
return;
}
var address = clientMessage[0];
var address2 = clientMessage[1];
var clientMessageString = clientMessage[3].ConvertToString();
//_logger.Debug("Message from client received: '{0}'", clientMessageString);
Console.WriteLine(String.Format("Message from client received: '{0}'", clientMessageString));
netMqSocketEventArgs
.Socket.SendMoreFrame(address.Buffer)
.SendMoreFrame(address2.Buffer)
.SendMoreFrameEmpty()
.SendFrame("I have received your message");
}
}
CollectorDevice.cs (in the client project and solution):
using NetMQ;
using NetMQ.Sockets;
using NLog;
public class CollectorDevice : IDisposable
{
private NetMQPoller _poller;
private RouterSocket _frontendSocket;
private DealerSocket _backendSocket;
private readonly string _backEndAddress;
private readonly string _frontEndAddress;
private readonly int _expectedFrameCount;
private readonly ManualResetEvent _startSemaphore = new(false);
private readonly Thread _localThread;
private static Logger _logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Constructor
/// </summary>
/// <param name="backEndAddress"></param>
/// <param name="frontEndAddress"></param>
/// <param name="expectedFrameCount"></param>
public CollectorDevice(string backEndAddress, string frontEndAddress, int expectedFrameCount)
{
_expectedFrameCount = expectedFrameCount;
_backEndAddress = backEndAddress;
_frontEndAddress = frontEndAddress;
_frontendSocket = new RouterSocket(_frontEndAddress);
_backendSocket = new DealerSocket(_backEndAddress);
_backendSocket.ReceiveReady += OnBackEndReady;
_frontendSocket.ReceiveReady += OnFrontEndReady;
_poller = new NetMQPoller { _frontendSocket, _backendSocket };
_localThread = new Thread(DoWork) { Name = "IPC Collector Device Thread" };
}
public void Start()
{
_localThread.Start();
_startSemaphore.WaitOne();
}
public void Stop()
{
_poller.Stop();
}
#region Implementation of IDisposable
public void Dispose()
{
Stop();
}
#endregion
#region Private Methods
private void DoWork()
{
try
{
_startSemaphore.Set();
_poller.Run();
}
catch (Exception e)
{
_logger.Error(e);
}
}
private void OnBackEndReady(object? sender, NetMQSocketEventArgs e)
{
NetMQMessage message = _backendSocket.ReceiveMultipartMessage(_expectedFrameCount);
_frontendSocket.SendMultipartMessage(message);
}
private void OnFrontEndReady(object? sender, NetMQSocketEventArgs e)
{
NetMQMessage message = _frontendSocket.ReceiveMultipartMessage(_expectedFrameCount);
_backendSocket.SendMultipartMessage(message);
}
#endregion
}
Program.cs (also in the client project and solution):
using NetMQ;
using NetMQ.Sockets;
using NLog;
using System.Text;
class Program
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
private static void Main(string[] args)
{
Console.WriteLine("Client. Please enter message for server. Enter 'QUIT' to turn off server");
Console.ReadKey();
var encoding = Encoding.ASCII;
using (var collectorDevice = new CollectorDevice("tcp://localhost:5556", "inproc://broker", 3))
{
collectorDevice.Start();
var tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
int j = i;
Task t = Task.Factory.StartNew(() =>
{
try
{
using (var requestSocket = new RequestSocket("inproc://broker"))
{
requestSocket.SendFrame(encoding.GetBytes(String.Format("Request client: {0} id: {1}", j, Task.CurrentId)));
_logger.Debug(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));
Console.WriteLine(String.Format("Request client: {0} id: {1}", j, Task.CurrentId));
string responseMessage = requestSocket.ReceiveFrameString();
_logger.Debug(String.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
Console.WriteLine(String.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
}
}
catch (Exception e)
{
Console.WriteLine(e);
_logger.Error(e);
}
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
}
}
}
I got my answer at the GitHub issue I opened. The updated code successfully exchanges messages and terminates with 0, but the messages are out of order; additional logic would be required to put the messages in order, but the point of this question was just to exchange messages.
The necessary changes are mostly in the server's Program.cs:
using NetMQ;
using NetMQ.Sockets;
using NLog;
Logger _logger = LogManager.GetCurrentClassLogger();
try
{
using (var responseSocket = new ResponseSocket())
{
responseSocket.Bind("tcp://localhost:5556");
var poller = new NetMQPoller();
responseSocket.ReceiveReady += RouterSocketOnReceiveReady;
poller.Add(responseSocket);
poller.Run();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadKey();
void RouterSocketOnReceiveReady(object? sender, NetMQSocketEventArgs netMqSocketEventArgs)
{
NetMQMessage? clientMessage = new();
bool result = netMqSocketEventArgs.Socket.TryReceiveMultipartMessage(new TimeSpan(0, 0, 0, 5),
ref clientMessage, 5);
if (result == false || clientMessage == null)
{
Console.WriteLine("Something went wrong?!");
return;
}
var clientMessageString = clientMessage.Single().ToByteArray();
//_logger.Debug("Message from client received: '{0}'", clientMessageString);
Console.WriteLine(string.Format("Message from client received: '{0}'", string.Join(", ", clientMessageString)));
netMqSocketEventArgs
.Socket
.SendFrame("I have received your message");
}
Here's the client's Program.cs:
using NetMQ;
using NetMQ.Sockets;
using NLog;
using System.Text;
Logger _logger = LogManager.GetCurrentClassLogger();
Console.WriteLine("Client. Please enter message for server. Enter 'QUIT' to turn off server");
Console.ReadKey();
var encoding = Encoding.ASCII;
using var collectorDevice = new CollectorDevice("tcp://localhost:5556", "inproc://broker", 3);
collectorDevice.Start();
var tasks = new List<Task>();
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
int j = i;
Task t = Task.Factory.StartNew(() =>
{
try
{
using (var requestSocket = new RequestSocket("inproc://broker"))
{
requestSocket.SendFrame(encoding.GetBytes(string.Format("Request client: {0} id: {1}", j, Task.CurrentId)));
_logger.Debug(string.Format("Request client: {0} id: {1}", j, Task.CurrentId));
Console.WriteLine(string.Format("Request client: {0} id: {1}", j, Task.CurrentId));
string responseMessage = requestSocket.ReceiveFrameString();
_logger.Debug(string.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
Console.WriteLine(string.Format("Response from server: {0} id: {1} message: {2}", j, Task.CurrentId, responseMessage));
}
}
catch (Exception e)
{
Console.WriteLine(e);
_logger.Error(e);
}
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
And the client's CollectorDevice.cs:
using NetMQ;
using NetMQ.Sockets;
using NLog;
public class CollectorDevice : IDisposable
{
private NetMQPoller _poller;
private RouterSocket _frontendSocket;
private DealerSocket _backendSocket;
private readonly string _backEndAddress;
private readonly string _frontEndAddress;
private readonly int _expectedFrameCount;
private readonly ManualResetEvent _startSemaphore = new(false);
private readonly Thread _localThread;
private static Logger _logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Constructor
/// </summary>
/// <param name="backEndAddress"></param>
/// <param name="frontEndAddress"></param>
/// <param name="expectedFrameCount"></param>
public CollectorDevice(string backEndAddress, string frontEndAddress, int expectedFrameCount)
{
_expectedFrameCount = expectedFrameCount;
_backEndAddress = backEndAddress;
_frontEndAddress = frontEndAddress;
_frontendSocket = new RouterSocket(_frontEndAddress);
_backendSocket = new DealerSocket(_backEndAddress);
_backendSocket.ReceiveReady += OnBackEndReady;
_frontendSocket.ReceiveReady += OnFrontEndReady;
_poller = new NetMQPoller { _frontendSocket, _backendSocket };
_localThread = new Thread(DoWork) { Name = "IPC Collector Device Thread" };
}
public void Start()
{
_localThread.Start();
_startSemaphore.WaitOne();
}
public void Stop()
{
_poller.Stop();
}
#region Implementation of IDisposable
public void Dispose()
{
Stop();
}
#endregion
#region Private Methods
private void DoWork()
{
try
{
_startSemaphore.Set();
_poller.Run();
}
catch (Exception e)
{
_logger.Error(e);
}
}
private void OnBackEndReady(object? sender, NetMQSocketEventArgs e)
{
NetMQMessage message = _backendSocket.ReceiveMultipartMessage(_expectedFrameCount);
_frontendSocket.SendMultipartMessage(message);
}
private void OnFrontEndReady(object? sender, NetMQSocketEventArgs e)
{
NetMQMessage message = _frontendSocket.ReceiveMultipartMessage(_expectedFrameCount);
_backendSocket.SendMultipartMessage(message);
}
#endregion
}
I have a Tcp Server by TcpListener.
Everything is OK in Visual Studio (Asp.net MVC), but when I publish my app and run using iis, TcpListener.acceptSocket don't accept connections. What is the problem?
Update:
I Create a TCPServer thet use TcpListener. When server is started, a thread is running to accept pending connections. Accepted sockets are stored in a list for other purposes. Each accepted socket receive relative packets and use of them.
My code is as follow:
public class TCPServer
{
public static Dictionary<EndPoint, Socket> acceptedSockets = new Dictionary<EndPoint, Socket>();
public TcpListener server { get; set; }
public int port { get; set; }
public TCPServer(int port)
{
this.port = port;
try
{
server = new TcpListener(IPAddress.Any, port);
}
catch (Exception e)
{
server = null;
}
}
static TCPSocketListener socketListener;
private Thread serverThread { get; set; }
private bool stopServer { get; set; }
public void StartServer()
{
if (server != null)
{
acceptedSockets = new Dictionary<EndPoint, Socket>();
server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
server.Start();
stopServer = false;
serverThread = new Thread(new ThreadStart(ServerThreadStart));
serverThread.Start();
}
else
{
NotificationHub.showMessage("Error in server connection.");
}
}
private void ServerThreadStart()
{
Socket clientSocket = null;
while (!stopServer)
{
try
{
if (!server.Pending())
{
Thread.Sleep(500);
continue;
}
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
clientSocket = server.AcceptSocket();
socketListener = new TCPSocketListener(clientSocket);
if (!acceptedSockets.ContainsKey(clientSocket.RemoteEndPoint))
acceptedSockets.Add(clientSocket.RemoteEndPoint, clientSocket);
socketListener.OnPacketReceive += GetReceivedData;
socketListener.StartSocketListener();
}
catch (SocketException se)
{
stopServer = true;
}
}
}
public delegate void DataEventHandler(object sender, DataEventArgs e);
public event DataEventHandler OnPacketReceive;
private void GetReceivedData(object sender, DataEventArgs args)
{
PacketReceive(args);
}
protected virtual void PacketReceive(DataEventArgs e)
{
OnPacketReceive?.Invoke(this, e);
}
public void StopServer()
{
if (server != null)
{
stopServer = true;
if (socketListener != null)
socketListener.StopReceive();
server.Stop();
// Wait for one second for the the thread to stop.
serverThread.Join(1000);
if (serverThread.IsAlive)
{
serverThread.Abort();
}
serverThread = null;
server = null;
foreach (var item in acceptedSockets)
{
try
{
item.Value.Shutdown(SocketShutdown.Both);
item.Value.Dispose();
item.Value.Close();
}
catch { }
}
acceptedSockets.Clear();
}
}
public class TCPSocketListener
{
public Socket socket { get; set; }
private Thread thread { get; set; }
private bool stopReceive { get; set; }
public TCPSocketListener(Socket socket)
{
this.socket = socket;
}
public void StartSocketListener()
{
stopReceive = false;
thread = new Thread(new ThreadStart(ReceiveThread));
thread.Start();
}
private void ReceiveThread()
{
byte[] bytes = null;
while (!stopReceive)
{
try
{
bytes = new byte[1024000];
int bytesRec = socket.Receive(bytes);
string data = Encoding.Default.GetString(bytes);
if (data.Length == 0)
{
break;
}
AddPacket(data, (socket.RemoteEndPoint as IPEndPoint).Address.ToString());
new string[] { data });
}
catch (Exception ex)
{
break;
}
}
}
public void StopReceive()
{
acceptedSockets.Remove(socket.RemoteEndPoint);
stopReceive = true;
thread.Abort();
socket.Shutdown(SocketShutdown.Receive);
socket.Close();
}
public delegate void DataEventHandler(object sender, DataEventArgs e);
public event DataEventHandler OnPacketReceive;
public void AddPacket(string data, string sourceIp)
{
DataEventArgs args = new DataEventArgs();
args.data = data;
args.sourceIp = sourceIp;
PacketReceive(args);
}
protected virtual void PacketReceive(DataEventArgs e)
{
OnPacketReceive?.Invoke(this, e);
}
}
}
The most possible reason causing the issue doesn't relate to IIS, more related to the firewall/network issue. Please close the firewall on the webserver and the client, and then try it again.
Feel free to let me know if the problem persists.
I would like to validate user is signed in or not to achieve it i found something called VaadinServiceInitListener in vaadin 13.0.2 This class is used to listen to BeforeEnter event of all UIs in order to check whether a user is signed in or not before allowing entering any page.
I have created an vaadin 13.0.2 project with app-layout-addon by appreciated implemented login functionality and VaadinServiceInitListener to check whether a user is signed in or not.
public class AAACATInitListener implements VaadinServiceInitListener {
private static final long serialVersionUID = 1L;
private static InAppSessionContextImpl appContextImpl;
#Override
public void serviceInit(ServiceInitEvent event) {
System.out.println("in service init event");
event.getSource().addUIInitListener(new UIInitListener() {
private static final long serialVersionUID = 1L;
#Override
public void uiInit(UIInitEvent event) {
event.getUI().addBeforeEnterListener(new BeforeEnterListener() {
private static final long serialVersionUID = 1L;
#Override
public void beforeEnter(BeforeEnterEvent event) {
appContextImpl = (InAppSessionContextImpl)VaadinSession.getCurrent().getAttribute("context");
if (appContextImpl == null) {
WebBrowser webBrowser = UI.getCurrent().getSession().getBrowser();
String address = webBrowser.getAddress();
if(RememberAuthService.isAuthenticated(address) != null && !RememberAuthService.isAuthenticated(address).isEmpty()) {
//System.out.println("Found Remembered User....");
IBLSessionContext iblSessionContext = null;
try {
iblSessionContext = new UserBLManager().doRememberedStaffUserLogin(RememberAuthService.isAuthenticated(address), "");
if(iblSessionContext != null) {
InAppSessionContextImpl localAppContextImpl = new InAppSessionContextImpl();
localAppContextImpl.setBLSessionContext(iblSessionContext);
localAppContextImpl.setModuleGroupList(iblSessionContext.getSessionAccessControl().getPermittedModuleGroups());
appContextImpl = localAppContextImpl;
event.rerouteTo(ApplicationMainView.class);
}else {
Notification.show("Your access has been expired, Please contact your administrator", 5000, Position.BOTTOM_CENTER);
}
} catch (AuthenticationFailedException e) {
Notification.show("Authentication Failed, Please Reset Cookies And Try Again", 5000, Position.BOTTOM_CENTER);
} catch (Exception e){
e.printStackTrace();
Notification.show("Unexpected Error Occurred, Please Reset Cookies And Try Again", 5000, Position.BOTTOM_CENTER);
}
}else {
System.out.println("Session context is null, creating new context");
appContextImpl = new InAppSessionContextImpl();
VaadinSession.getCurrent().setAttribute("context", appContextImpl);
event.rerouteTo(LoginView.class);
}
} else {
System.out.println("Session context is not null");
InAppSessionContextImpl localAppContextImpl = new InAppSessionContextImpl();
localAppContextImpl.setBLSessionContext(appContextImpl.getBLSessionContext());
localAppContextImpl.setModuleGroupList(appContextImpl.getModuleGroupList());
appContextImpl = localAppContextImpl;
event.rerouteTo(ApplicationMainView.class);
}
}
});
}
});
}
public static void setBLSessionContext(IBLSessionContext iblSessionContext) {
appContextImpl.setBLSessionContext(iblSessionContext);
}
public static void setModuleGroupList(List<ModuleGroupVO> moduleGroupList) {
appContextImpl.setModuleGroupList(moduleGroupList);
}
private class InAppSessionContextImpl implements InAppSessionContext {
private static final long serialVersionUID = 1L;
private List<ModuleGroupVO> moduleGroupList;
private IBLSessionContext iblSessionContext;
private Map<String, Object> attributeMap;
public InAppSessionContextImpl() {
this.attributeMap = new HashMap<String, Object>();
}
#Override
public List<ModuleGroupVO> getModuleGroupList() {
return moduleGroupList;
}
public void setModuleGroupList(List<ModuleGroupVO> moduleGroupList) {
this.moduleGroupList = moduleGroupList;
}
#Override
public IBLSessionContext getBLSessionContext() {
return iblSessionContext;
}
public void setBLSessionContext(IBLSessionContext iblSessionContext) {
this.iblSessionContext = iblSessionContext;
}
#Override
public IBLSession getBLSession() {
if(iblSessionContext != null)
return iblSessionContext.getBLSession();
return null;
}
#Override
public boolean isPermittedAction(String actionAlias) {
if (getBLSessionContext() != null) {
if (getBLSessionContext().getSessionAccessControl() != null) {
return getBLSessionContext().getSessionAccessControl().isPermittedAction(actionAlias);
}
}
return false;
}
#Override
public void setAttribute(String key, Object attribute) {
attributeMap.put(key, attribute);
}
#Override
public Object getAttribute(String key) {
return attributeMap.get(key);
}
}
}
Expected results redirect to login page if user not signed in or else to main application page but AAACATInitListener is not listening.
If you are using Spring, simply add a #Component annotation to the class and it should work. If youre not using Spring, follow #codinghaus' answer.
To make Vaadin recognize the VaadinServiceInitListener you have to create a file called com.vaadin.flow.server.VaadinServiceInitListener and put it under src/main/resources/META-INF/services. Its content should be the full path to the class that implements the VaadinServiceInitListener interface. Did you do that?
You can also find a description on that in the tutorial.
The correct pattern to use beforeEnter(..) is not do it via VaadinServiceInitListener , instead you should implement BeforeEnterObserver interface in the view where you need use it and override beforeEnter(..) method with your implementation.
public class MainView extends VerticalLayout implements RouterLayout, BeforeEnterObserver {
...
#Override
public void beforeEnter(BeforeEnterEvent event) {
...
}
}
I tried to read a json string loading from an URL, but I could not find complete code sample. Can any one provide or point me to a complete client code. I'm newer to BB development.
this is what I have done but still can't get it work please help me.
Thanks!
To read and parse data from an URL you need to implement two routines. First one of them will handle reading data from the specified URL over HTTP connection, and the second one will parse the data.
Check the following application HttpUrlReaderDemoApp, which will first read the data from specified URL and then parse the retrieved data.
URL used to retrieve data: http://codeincloud.tk/json_android_example.php
Sample data format: {"name":"Froyo", "version":"Android 2.2"}
Classes:
HttpUrlReaderDemoApp - UiApplication instance
HttpResponseListener - Interface used to notify other classes about HTTP request status
HttpUrlReader - Reads the data from given url
AppMainScreen - MainScreen instance
DataParser - Parse data
DataModel - Data definition
Screenshots:
Request for data
When data retrieved successfully
Parsed data
Implementation:
HttpUrlReaderDemoApp
public class HttpUrlReaderDemoApp extends UiApplication {
public static void main(String[] args) {
HttpUrlReaderDemoApp theApp = new HttpUrlReaderDemoApp();
theApp.enterEventDispatcher();
}
public HttpUrlReaderDemoApp() {
pushScreen(new AppMainScreen("HTTP Url Reader Demo Application"));
}
}
HttpResponseListener
public interface HttpResponseListener {
public void onHttpResponseFail(String message, String url);
public void onHttpResponseSuccess(byte bytes[], String url);
}
HttpUrlReader
public class HttpUrlReader implements Runnable {
private String url;
private HttpResponseListener listener;
public HttpUrlReader(String url, HttpResponseListener listener) {
this.url = url;
this.listener = listener;
}
private String getConncetionDependentUrlSuffix() {
// Not implemented
return "";
}
private void notifySuccess(byte bytes[], String url) {
if (listener != null) {
listener.onHttpResponseSuccess(bytes, url);
}
}
private void notifyFailure(String message, String url) {
if (listener != null) {
listener.onHttpResponseFail(message, url);
}
}
private boolean isValidUrl(String url) {
return (url != null && url.length() > 0);
}
public void run() {
if (!isValidUrl(url) || listener == null) {
String message = "Invalid parameters.";
message += !isValidUrl(url) ? " Invalid url." : "";
message += (listener == null) ? " Invalid HttpResponseListerner instance."
: "";
notifyFailure(message, url);
return;
}
// update URL depending on connection type
url += DeviceInfo.isSimulator() ? ";deviceside=true"
: getConncetionDependentUrlSuffix();
// Open the connection and retrieve the data
try {
HttpConnection httpConn = (HttpConnection) Connector.open(url);
int status = httpConn.getResponseCode();
if (status == HttpConnection.HTTP_OK) {
InputStream input = httpConn.openInputStream();
byte[] bytes = IOUtilities.streamToBytes(input);
input.close();
notifySuccess(bytes, url);
} else {
notifyFailure("Failed to retrieve data, HTTP response code: "
+ status, url);
return;
}
httpConn.close();
} catch (Exception e) {
notifyFailure("Failed to retrieve data, Exception: ", e.toString());
return;
}
}
}
AppMainScreen
public class AppMainScreen extends MainScreen implements HttpResponseListener {
private final String URL = "http://codeincloud.tk/json_android_example.php";
public AppMainScreen(String title) {
setTitle(title);
}
private MenuItem miReadData = new MenuItem("Read data", 0, 0) {
public void run() {
requestData();
}
};
protected void makeMenu(Menu menu, int instance) {
menu.add(miReadData);
super.makeMenu(menu, instance);
}
public void close() {
super.close();
}
public void showDialog(final String message) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(message);
}
});
}
private void requestData() {
Thread urlReader = new Thread(new HttpUrlReader(URL, this));
urlReader.start();
showDialog("Request for data from\n \"" + URL + "\"\n started.");
}
public void onHttpResponseFail(String message, String url) {
showDialog("Failure Mesage:\n" + message + "\n\nUrl:\n" + url);
}
public void onHttpResponseSuccess(byte bytes[], String url) {
showDialog("Data retrived from:\n" + url + "\n\nData:\n"
+ new String(bytes));
// now parse response
DataModel dataModel = DataParser.getData(bytes);
if (dataModel == null) {
showDialog("Failed to parse data: " + new String(bytes));
} else {
showDialog("Parsed Data:\nName: " + dataModel.getName()
+ "\nVersion: " + dataModel.getVersion());
}
}
}
DataParser
public class DataParser {
private static final String NAME = "name";
private static final String VERSION = "version";
public static DataModel getData(byte data[]) {
String rawData = new String(data);
DataModel dataModel = new DataModel();
try {
JSONObject jsonObj = new JSONObject(rawData);
if (jsonObj.has(NAME)) {
dataModel.setName(jsonObj.getString(NAME));
}
if (jsonObj.has(VERSION)) {
dataModel.setVersion(jsonObj.getString(VERSION));
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dataModel;
}
}
DataModel
public class DataModel {
private String name;
private String version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String model) {
this.version = model;
}
}
I'm having a problem with Flash Scope when I try to set a flash scope variable and then do a redirect. In the console, I get the following trace...
com.sun.faces.context.flash.ELFlash setCookie
WARNING: JSF1095: The response was already committed by the time we tried to set the outgoing
cookie for the flash. Any values stored to the flash will not be available on the next request.
The idea is pass an id from the first page (search page) to the second page, but if I cancel using immediate, I get the mentioned log, and the flash counter is not incremented anymore.
The code:
(Search bean)
#ManagedBean
#ViewScoped
public class ConsultarPaisBean implements Serializable {
private static final long serialVersionUID = 7947494818704255376L;
#ManagedProperty("#{flash}")
private Flash flash;
#ManagedProperty("#{paisService}")
private PaisService paisService;
private List<Pais> paises;
private PaisFilter paisFilter;
private Pais paisSelected;
#PostConstruct
public void init() {
this.paisFilter = new PaisFilter();
this.paisSelected = null;
this.paises = null;
}
public String irRegistrarPais() {
return MappingUrlConstants.PAIS;
}
public String irModificarPais() {
String respuesta = null;
if (this.paisSelected != null && this.paisSelected.getId() != null) {
flash.put("paisId", this.paisSelected.getId());
respuesta = MappingUrlConstants.PAIS;
}
return respuesta;
}
public String buscarPaises() {
this.paisSelected = null;
this.paises = this.paisService.getPaisByParams(this.paisFilter);
return null;
}
public String limpiarFiltros() {
this.paisFilter = new PaisFilter();
return null;
}
public List<Pais> getPaises() {
return paises;
}
public void setPaises(List<Pais> paises) {
this.paises = paises;
}
public PaisFilter getPaisFilter() {
return paisFilter;
}
public void setPaisFilter(PaisFilter paisFilter) {
this.paisFilter = paisFilter;
}
public Pais getPaisSelected() {
return paisSelected;
}
public void setPaisSelected(Pais paisSelected) {
this.paisSelected = paisSelected;
}
public void setPaisService(PaisService paisService) {
this.paisService = paisService;
}
public void setFlash(Flash flash) {
this.flash = flash;
}
}
(Add/Update bean)
#ManagedBean
#ViewScoped
public class PaisBean implements Serializable {
private static final long serialVersionUID = 3604521826400240955L;
#ManagedProperty("#{paisService}")
private PaisService paisService;
#ManagedProperty("#{flash}")
private Flash flash;
private Pais pais;
#PostConstruct
public void init() {
if (this.flash.get("paisId") != null) {
Long id = (Long) this.flash.get("paisId");
this.pais = this.paisService.getPaisById(id);
} else {
this.pais = new Pais();
}
}
public String registrarPais() {
String mensajeExito = null;
if (this.pais.getId() == null) {
this.paisService.save(this.pais);
mensajeExito = MessageUtils.getMessage("org.siae.commons.messages.general", "pais.registrar.exito",
new Object[] { this.pais.getNombre() });
} else {
this.paisService.update(this.pais);
mensajeExito = MessageUtils.getMessage("org.siae.commons.messages.general", "pais.modificar.exito",
new Object[] { this.pais.getNombre() });
}
FacesUtils.addInfoMessage(mensajeExito);
return MappingUrlConstants.CONSULTAR_PAIS;
}
public String irConsultarPais() {
return MappingUrlConstants.CONSULTAR_PAIS;
}
public void setPaisService(PaisService paisService) {
this.paisService = paisService;
}
public void setFlash(Flash flash) {
this.flash = flash;
}
public Pais getPais() {
return pais;
}
public void setPais(Pais pais) {
this.pais = pais;
}
}
I appreciate your help.