Pre-event handler - IBM Connections - ibm-connections

I would like to trap the file upload event in IBM Connections, and take some actions. If a particular criteria gets satisfied, the file should be stored within the system, or else should be rejected with a message.
For this, I was exploring the IBM Connections SPI ( Pre-Event Handler hooks ). I have followed the necessary steps required as per the document to create the jar, deploy and change the configurations, but it seems that my code doesn't get called, when a file is uploaded into Connections.
Not sure, where lies the issue, as I don't get any errors too.
PS: I tried the Post Event handler hook and it worked successfully.
Following are the snippets
public class PreHandlerEvents implements PreEventHandler{
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void handleEvent(MutableEvent arg0) throws EventHandlerException {
String content = "This is the content to write into file";
File file = new File("filenamePre.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileWriter fw;
try {
fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
events-config.xml
<preHandler enabled="true" name="PreHandlerEvents" class="com.connections.PreHandlerEvents">
<subscriptions>
<subscription source="*" type="*" eventName="*"/>
</subscriptions>
</preHandler>
</preHandlers>

Perhaps rather than a PreEventHandler, you could use an EventHandler instead in your <preHandler .../>?
Example code:
public class CustomEventHandler implements EventHandler {
public void init() throws EventHandlerInitException {}
public void destroy() {}
#Override
public void handleEvent(Event event) throws EventHandlerException {
System.out.println(" +++ Event: " + event.getName());
}
}

Related

"com.jcraft.jsch.JSchException: connection is closed by foreign host" when we are accessing the request using multiple threads(100 requests at a time)

I am using jsch session(along with "exec" channel) to upload content from one server to another remote server, i have implemented scenarios and they are working fine for less number(5 to 10 threads) of requests at a time. If i hit for upload content service using 100 threads at a time i am getting the connection closed by foreign host exception. can anyone help me to resolve this?
I am using jersey client to access the tomcat requests.
Note: i am getting success for all the requests if i used to call the jersey client in "for loop" instead of using threads.
Client which i observed the exceptions for some requests(5 to 10 requests are failing for every 100 requests):
public class MultiThreadsExecution {
public static void main(String args[]) throws ParseException, JSONException, IOException, InterruptedException {
int i = 1;
while (i <= 100) {
Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("inside run method ");
int folderNo = new Random().nextInt(300);
String inputMetadata = "{'path':'/content/dam/en/us/products/collateral/arch/oct06/05'}";
String filePath = "C:\\Users\\sreenu\\Desktop\\testcontent\\documents\\testdoc.pdf";
// code goes here.
try {
//jersey client invoking
new JerseyPostClient().uploadContent(inputMetadata, filePath);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
});
t1.start();
i++;
}
}
}

Creating a Chat client with JavaFX using sockets

I am having trouble coding the socket side of a JavaFX chat client. This is my first time having to deal with socket in any sort of way, so some trouble was expected. I've been following this page to design the server-client side:
http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html
My problem is getting text I enter into the GUI into a DataInputSteam and DataOutputStream so that others on the same server can see the changes. I do
not understand how to convert the text in the UI to something the sockets
can work with.
Here is part of my controller class:
#FXML
private TextArea messageArea;
#FXML
private Button sendButton;
private ChatClient client;
#FXML
public void initialize() {
client = new ChatClient(ChatServer.HOSTNAME, ChatServer.PORT);
sendButton.setOnAction(event -> {
client.handle(messageArea.getText());
});
}
The ChatClient class is a Runnable with a DataInputStream and DataOutputStream field that connects to a Socket. I haven't changed much from the link:
public class ChatClient implements Runnable {
private Socket socket;
private Thread thread;
private DataInputStream streamIn;
private DataOutputStream streamOut;
private ChatClientThread client;
public ChatClient(String serverName, int port) {
System.out.println("Establishing connection...");
try {
socket = new Socket(serverName, port);
System.out.println("Connected: " + socket);
start();
} catch (UnknownHostException e) {
System.out.println("Unknown host: " + e.getMessage());
} catch (IOException e) {
System.out.println("Unexpected: " + e.getMessage());
}
}
#Override
public void run() {
while (thread != null) {
try {
streamOut.writeUTF(streamIn.readUTF());
streamOut.flush();
} catch (IOException e) {
System.out.println("Sending error: " + e.getMessage());
stop();
}
}
}
public void handle(String msg) {
try {
streamOut.writeUTF(msg);
streamOut.flush();
} catch (IOException e) {
System.out.println("Could not handle message: " + e.getMessage());
}
System.out.println(msg);
}
public void start() throws IOException {
streamIn = new DataInputStream(socket.getInputStream());
streamOut = new DataOutputStream(socket.getOutputStream());
if (thread == null) {
client = new ChatClientThread(this, socket);
thread = new Thread(this);
thread.start();
}
}
So in the controller class, I am calling the handle method which deals with the streams. The original code just wrote to the console, so I had to change the line:
streamIn = new DataInputStream(System.in)
to
streamIn = new DataInputStream(socket.getInputStream());
There is also a ChatClientThread class that extends Thread and just calls ChatClient.handle() in its run method.
I guess my question is how to update a GUI whenever writeUTF and readUTF interact with the DataStreams. I understand that streamOut.writeUTF(msg) changes the DataOutputStream to "have" that string, but I'm not sure how I'm supposed to use that datastream to update my gui so that all clients using the application can see the update. The way I have it now, if I run two instances of the JavaFX app, they dont' communicate through the UI or the console. My program just stalls whenever I click the send button

How to call a RESTful Method from Android?

I've tried two different ways to call a simple REST method from Android; said REST method - which works from other clients - simply returns an int val such as 17.
Both of the following attempts were based on code I found online. One is like so:
public void onFetchBtnClicked(View v){
if(v.getId() == R.id.FetchBtn){
Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
new NetworkTask().execute();
}
}
public static class NetworkTask extends AsyncTask {
#Override
protected String doInBackground(Void... params) {
final String TAG;
TAG = "callWebService";
String deviceId = "Android Device";
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:28642/api/Departments/GetCount");
request.addHeader("deviceId", deviceId);
ResponseHandler<String> handler = new BasicResponseHandler();
String result = "";
try
{
result = httpclient.execute(request, handler);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e(TAG, "ClientProtocolException in callWebService(). " + e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, "IOException in callWebService(). " + e.getMessage());
}
httpclient.getConnectionManager().shutdown();
Log.i(TAG, "**callWebService() successful. Result: **");
Log.i(TAG, result);
Log.i(TAG, "*****************************************");
return result;
}
#Override
protected void onPostExecute(String result) {
final String TAG;
TAG = "onPostExecute";
if (null != result)
Log.i(TAG, result);
}
With the code above, after the following line of code fails:
result = httpclient.execute(request, handler) ;
...I get, "*E/callWebService﹕ IOException in callWebService(). Connection to http://localhost:28642 refused*"
This problem may be a threading issue, as I read this in O'Reilly's "Programming Android" book by Mednieks, Dornin, Meike, and Nakamura: "AsyncTask is a convenenient tool for running small, asynchronous tasks. Just remember that the doInBackground method runs on a different thread! It must not write any state visible from another thread or read any state writable from another thread. This includes its parameters."
With my other attempt:
public void onFetchBtnClicked(View v){
if(v.getId() == R.id.FetchBtn){
Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
callWebService("http://localhost:28642/api/Departments/GetCount");
}
}
public String callWebService(String requestUrl)
{
final String TAG;
TAG = "callWebService";
String deviceId = "Android Device";
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(requestUrl);
request.addHeader("deviceId", deviceId);
ResponseHandler<String> handler = new BasicResponseHandler();
String result = "";
try
{
result = httpclient.execute(request, handler);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e(TAG, "ClientProtocolException in callWebService(). " + e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, "IOException in callWebService(). " + e.getMessage());
}
httpclient.getConnectionManager().shutdown();
Log.i(TAG, "**callWebService() successful. Result: **");
Log.i(TAG, result);
Log.i(TAG, "*****************************************");
return result;
}
...the debugger dumps me into View.class after hitting that same problem line (result = httpclient.execute(request, handler)). Why it does that, I don't know*, but I think the crux of the problem, as indicated by err msgs in logcat, is: "Caused by: android.os.NetworkOnMainThreadException"
*Maybe because something untoward is being attempted within the UI (View) thread.
Also (not a big deal, but "interesting," perhaps): the Toast doesn't pop up when a method call is made after it (it works otherwise).
The (Web API) server has a breakpoint set in its corresponding Controller method, but it is never reached. As mentioned, the server is running, and responds just fine to other (Windows app) clients.
There must be a somewhat straightforward way of calling a RESTful method from Android. But what/how?
UPDATE
I tried this, now, too, calling it like so:
RestClient client = new RestClient("http://localhost:28642/api/Departments/GetCount");
try {
client.Execute(RestClient.RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Log.i("CZECH_THIS", response);
...but it also is (or seems, anyway) happy to throw the "NetworkOnMainThread" exception.
UPDATE 2
This is the closest I've gotten so far, I think. Maybe the server is the culprit in this case, because with this code:
public void onFetchBtnClicked(View v){
if(v.getId() == R.id.FetchBtn){
Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
new CallAPI().execute("http://localhost:28642/api/Departments/GetCount");
}
}
public static class CallAPI extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
return resultToDisplay;
}
protected void onPostExecute(String result) {
Log.i("FromOnPostExecute", result);
}
} // end CallAPI
....the exception that is thrown is:
libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
failed to connect to localhost/127.0.0.1 (port 28642): connect failed: ECONNREFUSED (Connection refused)
...and the Android app continues to run (it falls over in the other examples).
Why is my server refusing the connection?
UPDATE 3
I thought for a minute I had it: I forgot to pass the serial Num with the URL. But even after doing so, it fails.
I have a breakpoint in the server app, in the Controller method; also, in the Repository method, but they are never reached.
What could be wrong?
Is "localhost" the wrong thing to use (in the URL)? Should I use the name of the computer instead?
Does the URL (passed literally as "http://localhost:28642/api/Departments/GetCount?serialNum=4242") need to be verbatimized?
UPDATE 4
Changing the "locohost" to the machine name, I get "No address associated with hostname" so that's not the problem...
Oddly, though, this line runs fine:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
...whereas this is the last line before the exception is thrown/caught:
in = new BufferedInputStream(urlConnection.getInputStream());
Looking at this, though, perhaps I need to escape my whacks; but when you already have double-whacks, as in after "http:", do you have to do triple-whacks? Or quadruple whacks? Surely not ceiling wax...?
I've got it working now. There's an article about it here.
This is the code from there without any explanation:
public class MainActivity extends ActionBarActivity {
private GetDepartmentsCount _getDeptsCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getDeptsCountBtn = (Button)findViewById(R.id.DeptsCountBtn);
getDeptsCountBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
_getDeptsCount = new GetDepartmentsCount();
_getDeptsCount.execute("http://10.0.2.2:28642/api/Departments/GetCount?serialNum=4242");
}
});
}
#Override
public void onStop() {
super.onStop();
_getDeptsCount.cancel(true);
}
private class GetDepartmentsCount extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String result = "";
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
if (null != inputStream)
result = IOUtils.toString(inputStream);
} catch (Exception e) {
System.out.println(e.getMessage());
return e.getMessage();
}
return result;
}
#Override
protected void onPostExecute(String result) {
EditText dynCount = (EditText)findViewById(R.id.dynamicCountEdit);
dynCount.setText(result + " records were found");
Log.i("FromOnPostExecute", result);
}
}
}

C# - set empty delegate for event

public event EventHandler MyButtonClick = delegate { };
The construction above allows to not check if there is any subscriber:
public virtual void OnMyButtonClick(EventHandler e)
{
this.MyButtonClick(this, e);
}
in stead of
public virtual void OnMyButtonClick(EventHandler e)
{
if (MyButtonClick!=null)
this.MyButtonClick(this, e);
}
But is it really a good idea? Is this the only benefit: to not check if any subscriber exists?
UPDATE: Here is example
namespace ConsoleApplication2
{
public class TestClass
{
public event EventHandler MyButtonClick;
//= delegate { };
public void OnButtonClick(EventArgs e)
{
MyButtonClick(this, e);
}
}
class Program
{
static void Main(string[] args)
{
var testClass = new TestClass();
//it throws an exception
testClass.OnButtonClick(new EventArgs());
// if you add an handler it will call it
testClass.MyButtonClick += myCustomHandler;
testClass.OnButtonClick(new EventArgs()); // myCustomHandler has been invoiked
}
private static void myCustomHandler(object sender, EventArgs e)
{
Console.WriteLine("myCustomHandler has been invoiked");
}
}
}
Well, the code you've given here:
public virtual void OnMyButtonClick(EventHandler e)
{
if (MyButtonClick!=null)
this.MyButtonClick(this, e);
}
isn't thread-safe. If the final subscription is removed after the nullity check but before the invocation, you could end up with a NullReferenceException (depending on whether the "raising" thread sees the change).
So you can change it to this instead:
public virtual void OnMyButtonClick(EventArgs e)
{
var handler = MyButtonClick;
if (handler != null)
{
handler(this, e);
}
}
... but of course you might forget to do that, and even if you don't, it's cumbersome to do that all over the place, IMO. So yes, while the benefit is "only" to avoid the nullity check, I'd say that's not a bad trade-off in many cases. Anything that makes it harder to make mistakes is a good idea, IMO.
Another alternative is to have an extension method:
public static void SafeInvoke(this EventHandler handler, object sender,
EventArgs e)
{
if (handler != null)
{
handler(sender, e);
}
}
Then change your calling code to:
public virtual void OnMyButtonClick(EventArgs e)
{
MyButtonClick.SafeInvoke(this, e);
}
(and use the same code for other events). You'd probably want a generic form for EventHandler<T> as well.
you don't need to do that. If the client that uses you class won't add an handler (subscriber) for MyButtonClick event the code won't throw an exception.
That is how events works (and delegates as there are the same thing) otherwise you would be forced to add an handler to all the events of a class (assuming there are any)
so you can do the below:
public virtual void OnMyButtonClick(EventArgs e)
{
MyButtonClick(this, e);
}
have a look at the example below:
public class TestClass
{
public event EventHandler MyButtonClick = delegate { };
public void ButtonClick(EventArgs e)
{
MyButtonClick(this,e);
}
}
class Program
{
static void Main(string[] args)
{
var testClass=new TestClass();
testClass.ButtonClick(new EventArgs());
// if you add an handler it will call it
testClass.MyButtonClick += myCustomHandler;
testClass.ButtonClick(new EventArgs()); // myCustomHandler has been invoiked
}
private static void myCustomHandler(object sender, EventArgs e)
{
Console.WriteLine("myCustomHandler has been invoiked");
}
}

Android MediaPlayer seek bar current position thread issues

Hi I am new to android and I am learning by example. I am trying to make an activity that has a list view of all songs in my raw folder with media player controls at the bottom. I have everything working so far but I can't seem to get the SeekBar to stop force closing.
Here is the code:
public class music extends ListActivity implements Runnable {
private ArrayList<sound> mSounds = null;
private soundadapter mAdapter = null;
private ImageButton playbtn;
private SeekBar seekbar;
private int total;
private MediaPlayer mp = null;
private TextView selelctedFile = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
selelctedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setProgress(0);
// create a simple list
mSounds = new ArrayList<sound>();
sound s = new sound();
s.setDescription("Rudolph The Red Nosed Reindeer");
s.setSoundResourceId(R.raw.rudolphtherednosereindeer);
mSounds.add(s);
s = new sound();
s.setDescription("Battery");
s.setSoundResourceId(R.raw.battery);
mSounds.add(s);
mAdapter = new soundadapter(this, R.layout.listitem, mSounds);
setListAdapter(mAdapter);
playbtn = (ImageButton) findViewById(R.id.play);
playbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if (mp.isPlaying()) {
mp.pause();
playbtn.setImageResource(android.R.drawable.ic_media_play);
} else {
mp.start();
playbtn.setImageResource(android.R.drawable.ic_media_pause);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
});
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id) {
sound s = (sound) mSounds.get(position);
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, s.getSoundResourceId());
selelctedFile.setText(s.getDescription());
playbtn.setImageResource(android.R.drawable.ic_media_pause);
mp.start();
total = mp.getDuration();
seekbar.setMax(total);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekbar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekbar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp.seekTo(progress);
seekBar.setProgress(progress);
}
}
});
Thread currentThread = new Thread(this);
currentThread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
Thread.sleep(100);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(Message msg) {
// super.handleMessage(msg);
// txt.setText(Integer.toString(msg.what));
seekbar.setProgress(msg.what);
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
mp.stop();
mp.release();
mp = null;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
if(mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
and here is the error i keep getting when i click several times on different songs:
04-14 02:53:00.452: W/dalvikvm(27452): threadid=19: thread exiting with uncaught exception (group=0x40018560)
04-14 02:53:00.466: E/AndroidRuntime(27452): FATAL EXCEPTION: Thread-22
04-14 02:53:00.466: E/AndroidRuntime(27452): java.lang.IllegalStateException
04-14 02:53:00.466: E/AndroidRuntime(27452): at android.media.MediaPlayer.getCurrentPosition(Native Method)
04-14 02:53:00.466: E/AndroidRuntime(27452): at net.cybercore.collapsingfromwithin.music.run(music.java:145)
04-14 02:53:00.466: E/AndroidRuntime(27452): at java.lang.Thread.run(Thread.java:1019)
Line error 145 is :
int currentPosition = mp.getCurrentPosition();
I cannot for the life of me figure out why it works for 3 or 4 times playing and then it kills the app.
Any help is appreciated. I have already looked at several other sites for examples including http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/ and http://www.androiddevblog.net/android/playing-audio-in-android
**
UPDATE
**
I think I fixed it. thanks for your help I found Thread using for seekbar on android mediaplayer so i changed it to
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt exeption" + e);
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("My exeption" + e);
}
}
I still get the errors but they are not killing my app. I don't think this is right way to do it but its working.
You should prepare your media player when instanciating it.
A MediaPlayer object must first enter the Prepared state before playback can be started.
There are two ways (synchronous vs. asynchronous) that the Prepared state can be reached: either a call to prepare() (synchronous) which transfers the object to the Prepared state once the method call returns, or a call to prepareAsync() (asynchronous) which first transfers the object to the Preparing state after the call returns (which occurs almost right way) while the internal player engine continues working on the rest of preparation work until the preparation work completes. When the preparation completes or when prepare() call returns, the internal player engine then calls a user supplied callback method, onPrepared() of the OnPreparedListener interface, if an OnPreparedListener is registered beforehand via setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener).
Read it here
so you should call mp.prepare() after instanciating the player.
also you should make sure the media player in playing to run the run method. I'd start by adding
mp.isPlaying() to the while line.
while (mp != null && mp.isPlaying()) {
...
}
IllegalStateException means that you are on an illegal state to call that method, like for instance, if the player is stopped.
I'm not sure, but I think this will stop the run method when you pause the music. So you should try to avoid this. I create a boolean to identify that the player is playing or paused and use it on the while.

Resources