Invoking an instance method from a REST service method - java

I have a REST service accepting POST requests. Is there any way I can trigger a method inside my running swing GUI from that service? I want to make it possible to refresh the GUI table of posted data after every POST request is made. Is there any event handling mechanism for doing this?
REST service code:
#POST
#Consumes({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
#Produces({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
public Response createServiceRegistration(
#PathParam("serviceProviderId") final String serviceProviderId ,
final ServiceRegistration aServiceRegistration
) throws IOException, ServletException
{
try
{
ServiceRegistration newServiceRegistration = OrchestratorAdaptorManager.createServiceRegistration(httpServletRequest, aServiceRegistration, serviceProviderId);
httpServletResponse.setHeader("ETag", OrchestratorAdaptorManager.getETagFromServiceRegistration(newServiceRegistration));
/////////////////////////////////////////////////////
// Accessing and writing registration data to database
//
try
{
System.out.println("establishing database connection");
Registration registration = new Registration();
registration.createConnection();
registration.insertRegistration(aServiceRegistration.getService().toString(), aServiceRegistration.getTitle(), aServiceRegistration.getLabel());
registration.shutdown();
}
catch(Exception exc)
{
exc.printStackTrace();
throw new RuntimeException("Error inserting ServiceRegistration to the database", exc);
}
//
// Disconnected from the base
///////////////////////////////////////////////////
return Response.created(newServiceRegistration.getAbout()).entity(aServiceRegistration).build();
}
catch (Exception e)
{
e.printStackTrace();
throw new WebApplicationException(e);
}
//Trigger changes in GUI here :/
}
Class which I used to update the table every 10 seconds:
class CheckServices extends TimerTask
{
DefaultTableModel model;
protected CheckServices(DefaultTableModel model)
{
this.model = model;
}
#Override
public void run()
{
Registration reg = new Registration();
try
{
reg.createConnection();
ServiceRegistration[] sr = reg.selectRegistrations();
reg.shutdown();
System.out.println("Adding Registration Resources");
int rows = model.getRowCount();
for(int i = 0; i < rows; i++)
{
model.removeRow(0);
}
for(ServiceRegistration srItem : sr)
{
System.out.println("--> " + srItem.getTitle());
Object[] row = { false , srItem.getService().toString(), srItem.getTitle(), srItem.getLabel()};
model.addRow(row);
}
}
catch (URISyntaxException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Related

Fetching data from Database And Display on the Screen using vaadin

I've written this code, but when run, it shows the error
sql command not properly ended
How can I fix it?
DatabasetableUI
public class DatabasetableUI extends UI {
#Override
protected void init(VaadinRequest request) {
DatabaseTableScreen screen = new DatabaseTableScreen();
try {
JDBCConnectionPool connectionPool = new SimpleJDBCConnectionPool( "oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:#usadc-sdbxt21:1521:GFRWMUAT","user", "password");
screen.populate("case_upload_history", connectionPool);
} catch (SQLException e) {
//System.out.println("Application");;
throw new RuntimeException( e.getMessage());
} enter code here
setContent( screen);
}
}
DatabaseTableScreen
public class DatabaseTableScreen extends VerticalLayout {private SQLContainer container;
private Table table;
public DatabaseTableScreen() {
setMargin( true);
table = new Table();
table.setPageLength( 10);
table.setEditable( true);
table.setSizeFull();
enter code here
//table.addGeneratedColumn("",new RemoveItemColumnGenerator());
addComponent(table);
}
public void populate( String tableName, JDBCConnectionPool connectionPool) {
QueryDelegate query = new TableQuery( tableName, connectionPool);
try {
container=new SQLContainer(query);
table.setContainerDataSource( container);
} catch (SQLException e) {
throw new RuntimeException( e);
}
}
}
Use the third argument to the TableQueryconstructor, like this:
QueryDelegate query = new TableQuery( tableName, connectionPool, new OracleGenerator());

How to retrieve Message and Task body - Exchange Web Services - Java

I am creating a message using JWebServices, but even though all other fields are retrieved successfully, body does not. message.getBody() returns null. Here are the two methods I call subsequently.
private void createMessage(Service service) throws ParseException {
try {
Message message = new Message();
message.setItemClass(ItemClass.MESSAGE);
message.setSubject("Test");
message.setBody(new Body("Body text"));
message.getToRecipients().add(new Mailbox("John#mydomain.com"));
message.getCcRecipients().add(new Mailbox("Mark#mydomain.com"));
ItemId itemId = service.createItem(message,StandardFolder.SENT_ITEMS);
} catch (ServiceException e) {
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}
private void listItemsInSent(Service service) throws ParseException {
try {
FindItemResponse response = service.findItem(StandardFolder.SENT_ITEMS);
Message m = null;
for (int i = 0; i < response.getItems().size(); i++) {
m = (Message)response.getItems().get(i);
System.out.println(m.getSubject());
System.out.println(m.getItemClass());
System.out.println(m.getLastModifiedTime());
System.out.println(m.getBody());
System.out.println(m.getBodyHtmlText());
System.out.println(m.getBodyPlainText());
System.out.println(m.getItemId());
System.out.println(m.toString());
System.out.println();
}
} catch (ServiceException e) {
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}
Try to replace
m = (Message)response.getItems().get(i);
with
m = service.getMessage(response.getItems().get(i).getItemId());

Why does object inside a protected method has implementation?

Its the method invokeBackend(String request, HashMap context) .
Why does it have an object named java.security.PrivilegedAction createController = new java.security.PrivilegedAction()
and it has an implementation ? I see it has a run() method which means its a thread.
Does the run method returns "controller"? It returns "controller" to what?
What kind of an implementation is this? An object having implementation code?
3.Whats the primary use of implmentation of the method invokeBackend
Also the object
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction()
Thanks a lot!
protected static String invokeBackend(String request, HashMap context)
throws CommonModelException {
if (request.equals("")) {
return null;
}
if (logger.isDebugEnabled()) {
logger.debug("request: \r\n" + request);
}
Properties clientAuthenticationEnv = CommonProperties
.getClientAuthenticationProperties();
if (wccClientId == null) {
wccClientId = clientAuthenticationEnv.getProperty(CLIENT_ID);
}
if (wccClientPassword == null) {
wccClientPassword = clientAuthenticationEnv
.getProperty(CLIENT_PASSWORD);
}
controllerHome = getControllerHome();
String response = null;
try {
if (controllerHome == null) {
throw new CommonModelException(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION));
}
if (isWASImpl) {
java.security.PrivilegedAction createController = new java.security.PrivilegedAction() {
public Object run() {
Object controller = null;
try {
controller = controllerHome.create();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
} catch (CreateException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e);
}
return controller;
}
}; // PrivilegedAction
validateSecurityToken();
final DWLServiceController controller = (DWLServiceController) WSSubject
.doAs(subject, createController);
final String req = request;
final HashMap cxt = context;
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction() {
public Object run() {
Object response = null;
try {
response = (String) controller.processRequest(cxt,
req);
} catch (com.dwl.base.exception.DWLResponseException e) {
response = e.getLocalizedMessage();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
}
return response;
}
}; // PrivilegedAction
validateSecurityToken();
response = (String) WSSubject.doAs(subject, processRequest);
} else {
// DWLServiceController controller = controllerHome.create();
// response = (String) controller.processRequest(context,
// request);
java.security.PrivilegedAction createController = new java.security.PrivilegedAction() {
public Object run() {
Object controller = null;
try {
controller = controllerHome.create();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
} catch (CreateException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e);
}
return controller;
}
}; // PrivilegedAction
//reflection invoke to avoid compile dependency on weblogic library
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class securityClazz = cl.getClass().getClassLoader().loadClass("weblogic.security.Security");
Method runAs = securityClazz.getMethod("runAs", new Class[]{Subject.class, java.security.PrivilegedAction.class});
final DWLServiceController controller = (DWLServiceController) runAs.invoke(securityClazz, new Object[]{subject, createController});
//final DWLServiceController controller = (DWLServiceController) Security.runAs(subject, createController);
final String req = request;
final HashMap cxt = context;
java.security.PrivilegedAction processRequest = new java.security.PrivilegedAction() {
public Object run() {
Object response = null;
try {
response = (String) controller.processRequest(cxt,
req);
} catch (com.dwl.base.exception.DWLResponseException e) {
response = e.getLocalizedMessage();
} catch (RemoteException e) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e);
}
return response;
}
}; // PrivilegedAction
response = (String)runAs.invoke(securityClazz, subject, processRequest);
//response = (String) Security.runAs(subject, processRequest);
}
} catch (Exception e) {
response = e.getLocalizedMessage();
// for non IBM WebSphere Server, we have one more chance to redo
// lookup for EJB server restart, clear the session first
controllerHome = getControllerHome();
if (controllerHome == null) {
throw new CommonModelException(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION));
}
try {
DWLServiceController controller = controllerHome.create();
response = (String) controller.processRequest(context, request);
} catch (DWLResponseException e1) {
response = e1.getLocalizedMessage();
} catch (RemoteException e1) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_REMOTE_EXCEPTION), e1);
throw new CommonModelException(e1);
} catch (CreateException e1) {
logger.error(ResourceBundleHelper.resolve(
CommonResourceBundleNames.COMMON_STRINGS,
LOG_FAIL_GET_EJB_INSTANCE), e1);
throw new CommonModelException(e1);
}
}
if (logger.isDebugEnabled()) {
logger.debug("response: \r\n" + response);
}
return response;
}
The declaration you're looking at is a local variable initialized to reference an instance of an anonymous inner class. The class implemented is PrivilegedAction. The syntax is used when you want to create a one-off implementation of an interface or class that you don't intend to use elsewhere, so there's no point in giving it a name. The code implements the run method from the interface and creates an object implementing that interface, that it assigns to the local variable.
The run method returns a controller object to whoever calls run on it. That isn't shown here, it's passed in as one of the arguments to the runAs method call on this line:
final DWLServiceController controller = (DWLServiceController) runAs.invoke(
securityClazz, new Object[]{subject, createController});
where the code used reflection to look up the runAs method on the class weblogic.security.Security.

How pass these new messages to another class

Now basically I have created three classes.
public void run() {
int seqId = 0;
while(true) {
List<KamMessage> list = null;
try {
list = fullPoll(seqId);
} catch (Exception e1) {
e1.printStackTrace();
}
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingMessages.addAll(list);
System.out.println("waiting 3 seconds");
System.out.println("new incoming message");
}
try {
Thread.sleep(3000);
System.out.println("new incoming message");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public List<KamMessage> fullPoll(int lastSeq) throws Exception {
Statement st = dbConnection.createStatement();
ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 and SEQ >" +
lastSeq + "order by SEQ DESC");
List<KamMessage> pojoCol = new ArrayList<KamMessage>();
while (rs.next()) {
KamMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KamMessage pojoClass : pojoCol) {
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + pojoClass.getKeyInfo1());
System.out.print(" " + pojoClass.getKeyInfo2());
System.out.println(" " + pojoClass.getEntryTime());
}
return pojoCol;
}
The following are the classes:
1.Poller- does the Polling and Passes the new data from db to controller
2.Controller- this class has a thread Pool, which simultaneously calls the Poller and has the new data to be requested from processor
3.Processor- this class has to look for new data, process it and return it to controller.
So now my problem is how to implement the third phase...
Here is my controller class:
public class RunnableController {
/** Here This Queue initializes the DB and have the collection of incoming message
*
*/
private static Collection<KpiMessage> incomingQueue = new ArrayList<KpiMessage>();
private Connection dbConncetion;
public ExecutorService threadExecutor;
private void initializeDb()
{
//catching exception must be adapted - generic type Exception prohibited
DBhandler conn = new DBhandler();
try {
dbConncetion = conn.initializeDB();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initialiseThreads()
{
try {
threadExecutor = Executors.newFixedThreadPool(10);
PollingSynchronizer read = new PollingSynchronizer(incomingQueue, dbConncetion);
threadExecutor.submit(read);
}catch (Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unused")
private void shutDownThreads()
{
try {
threadExecutor.shutdown();
//DB handling should be moved to separate DB class
dbConncetion.close();
}catch (Exception e){
e.printStackTrace();
}
}
/** Here This Queue passes the messages and have the collection of outgoing message
*
*/
//private Collection<KpiMessage> outgingQueue = new ArrayList<KpiMessage>();
//have to implement something here for future
public static void main(String[] args) throws InterruptedException {
RunnableController controller = new RunnableController();
System.out.println(incomingQueue.size());
controller.initializeDb();
controller.initialiseThreads();
Thread.sleep(3000);
System.out.println("Polling");
}
}
I would recommend using a BlockingQueue for doing so, instead of a simple ArrayList. Just change the type of your incomingQueue variable. Then you can have another thread (or a thread pool) doing something like
//pseudocode
while (true) {
// it polls data from the incomingQueue that shares with the producers
KpiMessage message = this.incomingQueue.take()
//Then process the message and produces an output... you can put that output in a different queue as well for other part of the code to pick it up
}
A good example on BlockingQueues can be found here http://www.javamex.com/tutorials/blockingqueue_example.shtml

Provisioning Api using Java

Hello I tried one application which is used to store First 100 users in my domain to the table using JPA.But its returning Server Error. Pealse Help me.
This is the code i tried..
public class AppsProvisioning {
public String m[]=new String[1000];
public int a;
final EntityManager em = EMFService.get().createEntityManager();
//public static void main(String[] args)
public void calluser() throws AppsForYourDomainException, ServiceException,
{
try {
// Create a new Apps Provisioning service
UserService myService = new UserService("My Application");
myService.setUserCredentials("admin#xxxx.edu.in","xxxxxxxx");
// Get a list of all entries
URL metafeedUrl = new URL("https://www.google.com/a/feeds/domain/user/2.0/");
System.out.println("Getting user entries...\n");
UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);
List<UserEntry> entries = resultFeed.getEntries();
for(int i=0; i<entries.size(); i++) {
UserEntry entry = entries.get(i);
m[i]=entry.getTitle().getPlainText();
table greeting1 = new table(m[i]);
em.persist(greeting1);
System.out.println("\t" + entry.getTitle().getPlainText());
}
a=entries.size();
System.out.println("\nTotal Entries: "+entries.size());
}
catch(AuthenticationException e) {
e.printStackTrace();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(ServiceException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
finally
{
em.close();
}
}
}
I think error in em.close()
Error is:Server Error
The server encountered an error and could not complete your request.
Regards
Sharun
Replace "domain" in the feed url (https://www.google.com/a/feeds/domain/user/2.0/) with your domain "xxxx.edu.in".
As an alternative, use AppsForYourDomainClient.retrieveAllUsers() as explained in the reference guide http://code.google.com/googleapps/domain/gdata_provisioning_api_v2.0_reference_java.html

Categories