How to solve javax.naming.NameNotFoundException at this code - java

I make a Ejb project in netbean 7.3 with jboss-7.1.1 Final
In Ejb module i have these:
LibrarySessionBeanRemote.java
package com.tutorialspoint.stateless;
import java.util.List;
import javax.ejb.Remote;
#Remote
public interface LibrarySessionBeanRemote {
void addBook(String bookName);
List getBooks();
}
LibrarySessionBean.java
package com.tutorialspoint.stateless;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
#Stateless
#Remote(LibrarySessionBeanRemote.class)
public class LibrarySessionBean implements LibrarySessionBeanRemote {
List<String> bookSelf;
public LibrarySessionBean() {
this.bookSelf = new ArrayList<String>();
}
#Override
public void addBook(String bookName) {
bookSelf.add(bookName);
}
#Override
public List getBooks() {
return bookSelf;
}
}
and I make a client with java application project type
package client;
import com.tutorialspoint.stateless.LibrarySessionBeanRemote;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class EJBTester {
BufferedReader brConsoleReader = null;
Properties props;
InitialContext ctx;
{
props = new Properties();
props.put(Context.SECURITY_PRINCIPAL, "testuser");
props.put(Context.SECURITY_CREDENTIALS, "test");
props.put(Context.PROVIDER_URL, "remote://localhost:4447");
props.put("jboss.naming.client.ejb.context", true);
props.put(Context.INITIAL_CONTEXT_FACTORY, org.jboss.naming.remote.client.InitialContextFactory.class.getName());
try {
ctx = new InitialContext(props);
} catch (NamingException ex) {
ex.printStackTrace();
}
brConsoleReader =
new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
EJBTester ejbTester = new EJBTester();
ejbTester.testStatelessEjb();
}
private void showGUI() {
System.out.println("**********************");
System.out.println("Welcome to Book Store");
System.out.println("**********************");
System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
}
private void testStatelessEjb() {
try {
int choice = 1;
LibrarySessionBeanRemote libraryBean =
(LibrarySessionBeanRemote) ctx.lookup("LibrarySessionBean/remote");
while (choice != 2) {
String bookName;
showGUI();
String strChoice = brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);
if (choice == 1) {
System.out.print("Enter book name: ");
bookName = brConsoleReader.readLine();
libraryBean.addBook(bookName);
} else if (choice == 2) {
break;
}
}
List<String> booksList = libraryBean.getBooks();
System.out.println("Book(s) entered so far: " + booksList.size());
for (int i = 0; i < booksList.size(); ++i) {
System.out.println((i + 1) + ". " + booksList.get(i));
}
LibrarySessionBeanRemote libraryBean1 =
(LibrarySessionBeanRemote) ctx.lookup("LibrarySessionBean/remote");
List<String> booksList1 = libraryBean1.getBooks();
System.out.println(
"***Using second lookup to get library stateless object***");
System.out.println(
"Book(s) entered so far: " + booksList1.size());
for (int i = 0; i < booksList1.size(); ++i) {
System.out.println((i + 1) + ". " + booksList1.get(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
try {
if (brConsoleReader != null) {
brConsoleReader.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
but i have this exception
javax.naming.NameNotFoundException: LibrarySessionBean/remote -- service jboss.naming.context.java.jboss.exported.LibrarySessionBean.remote
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:97)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:178)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleServerMessage(Protocol.java:127)
at org.jboss.naming.remote.protocol.v1.RemoteNamingServerV1$MessageReciever$1.run(RemoteNamingServerV1.java:73)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

When you call an EJB you should not use the remote-naming project, but the remote EJB-invocation as described in https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI
Your JNDI name will look like:
context.lookup("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName)
appName and distinctName are empty in your case (no EAR).
See the example in the provided link.

JNDI address format has changed significantly on JBoss 7. Related documentation can be found here.
Try replacing LibrarySessionBean/remote with:
app-name/module-name/LibrarySessionBean!com.tutorialspoint.stateless.LibrarySessionBeanRemote`
where:
app-name = the name of the .ear (without the .ear suffix) or the
application name configured via application.xml deployment descriptor.
If the application isn't packaged in a .ear then there will be no
app-name part to the JNDI string.
module-name = the name of the .jar
or .war (without the .jar/.war suffix) in which the bean is deployed
or the module-name configured in web.xml/ejb-jar.xml of the
deployment. The module name is mandatory part in the JNDI string.

The Following code is an Standard a bit adapted to your example. Always Worked. Just remember to change de values in "appName" and "moduleName"
That's it
props = new Properties();
final String appName = "PackageEARProjectName";
final String moduleName = "PackageProjectName";
final String sessionBeanName = "LibrarySessionBean";
final String viewClassName = LibrarySessionBeanRemote.class.getName();
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put(Context.PROVIDER_URL,"remote://localhost:4447");
// username
jndiProps.put(Context.SECURITY_PRINCIPAL, "testuser");
// password
jndiProps.put(Context.SECURITY_CREDENTIALS, "test");
// This is an important property to set if you want to do EJB invocations via the remote-naming project
jndiProps.put("jboss.naming.client.ejb.context", true);
// create a context passing these properties
Context context = new InitialContext(jndiProps);
// lookup the bean
LibrarySessionBeanRemote LibrarySessionBean =(LibrarySessionBeanRemote)context.lookup(appName+"/"+moduleName+"/"+sessionBeanName+"!"+viewClassName);

Related

Using Javamail to get attachments

Good Morning,
I have been working on this project for a few days now and have ground to a halt. Downloading attachments seems to take forever and it would appear to be at the writing file to disk line. I have read about many options (FileChannel, bulk getContent and a few others but can not make this code execute at a reasonable rate) I am not to sure if the only bottle neck is the downloading of the files from O365 however I thought I would ask a question to see if somebody could review this code and hopefully tell me what I have done wrong. The goal of the application is to log into Exchange Online (o365) and download all attachments within a certain mail box. Please note that this code has been modified so many times to see if I could make performance increases by using threading and so on:
As I said I have shifted everything around a lot to try and make this work better so please don't blow me up for some of the code not making too much sense. I am not trying to get somebody else to finish this project, I am looking for guidance with a language that I do not have a great deal of experience with.
package o365connect;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
/**
*
* #author Charlie
*/
public class AttDownload extends Thread {
public static int Lower = 0;
public static int Upper = 0;
public static int Counter = 0;
public static Session session;
public static Store store;
public static Properties props = new Properties();
public static boolean fTest = false;
AttDownload(int i, int ii) {
Lower = i;
Upper = ii;
}
AttDownload() throws UnknownHostException {
super();
}
#Override
public void run() {
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
String pop3Host = "outlook.office365.com";
String mailStoreType = "imap";
String path = "Inbox/Scans to file";
String userName = "XXX#XXX.com";
String password = "XXXXXXX";
Folder emailFolder;
try {
props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
props.put("mail.imaps.host", "outlook.office365.com");
session = Session.getInstance(props);
int Size = functions.MBSize(pop3Host, userName, password, path);
System.out.println(Size);
store = session.getStore("imaps");
store.connect(pop3Host, userName, password);
emailFolder = store.getFolder(path);
emailFolder.open(Folder.READ_ONLY);
try {
Message[] messages;
messages = emailFolder.getMessages(Lower, Upper);
System.out.println("starting thread for - " + Lower + " - " + Upper);
int ASuc = receiveEmail(messages);
} catch (MessagingException | IOException ex) {
Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (NoSuchProviderException ex) {
Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static int receiveEmail(Message messagesarr[]) throws IOException, MessagingException {
for (Message messagesarr1 : messagesarr) {
try {
Message message = messagesarr1;
Object content = message.getContent();
if (content instanceof String) {
} else if (content instanceof Multipart) {
Multipart multipart = (Multipart) message.getContent();
for (int k = 0; k < multipart.getCount(); k++) {
MimeBodyPart bodyPart = (MimeBodyPart) multipart.getBodyPart(k);
if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
long startTime = System.currentTimeMillis();
int ran = (int) startTime;
String fileName;
String fName = bodyPart.getFileName();
if (fName != null && !fName.isEmpty()) {
fileName = fName.replaceAll("\\s+", "");
} else {
continue;
}
if ("ATT00001.txt".equals(fileName)) {
continue;
} else {
System.out.println("starting copy of - " + fileName);
}
String destFilePath = "D:/Scans/";
bodyPart.saveFile(destFilePath + bodyPart.getFileName());
long stopTime = System.currentTimeMillis();
System.out.println("finished copying of - " + fileName + " - " + (stopTime - startTime) + " miliseconds.");
System.out.println(Counter);
Counter++;
} else {
}
}
}
}catch (MessagingException e) {
System.out.println(e);
}
}
return 1;
}
}
Functions.java
package o365connect;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import static o365connect.AttDownload.store;
/**
*
* #author Oliver
*/
public class functions {
public static int TestUser(String pop3host, String Username, String Password) throws NoSuchProviderException, MessagingException {
try {
Session session = Session.getInstance(AttDownload.props);
store = session.getStore("imaps");
store.connect(pop3host, Username, Password);
return 0;
} catch (MessagingException e) {
System.out.println(e + "User Name Invalid");
return 1;
}
}
public static Folder TestFolder(Store store, String Path) throws MessagingException {
Folder emailFolder;
emailFolder = store.getFolder(Path);
emailFolder.open(Folder.READ_ONLY);
AttDownload.fTest = true;
emailFolder.close(false);
return emailFolder;
}
public static int MBSize(String pop3Host, String userName, String password, String Path) {
int Size = 0;
Session session = Session.getInstance(AttDownload.props);
try {
Store store = session.getStore("imaps");
store.connect(pop3Host, userName, password);
Folder emailFolder = store.getFolder(Path);
emailFolder.open(Folder.READ_ONLY);
Size = emailFolder.getMessageCount();
emailFolder.close(false);
store.close();
return Size;
} catch (MessagingException e) {
System.out.println(e + "MBSize");
}
return Size;
}
}
O365Connect.java
package o365connect;
import java.io.IOException;
import javax.mail.MessagingException;
public class O365Connect {
public static void main(String[] args) throws IOException, MessagingException, InterruptedException {
MainScreen ms = new MainScreen();
ms.setVisible(true);
AttDownload dl = new AttDownload(1, 1000);
dl.start();
}
}
Edit:
props.put("mail.imaps.fetchsize", "819200");
props.put("mail.imaps.partialfetch", "false");
sped things up, 128 seconds down to 12 seconds to download a 7mb file.
fetchsize is not used if partialfetch is false; it will download the entire attachment in one request. As long as you have enough memory for the largest possible attachment, that's fine. Otherwise, leave partialfetch set to true (default) and set the fetchsize large enough to give reasonable performance without using excessive memory.
JavaMail properties are described in the javadocs, on the page for each protocol provider. For example, the IMAP provider properties are described on the com.sun.mail.imap package javadoc page.

java.lang.ClassCastException: java.lang.String cannot be cast to com.tutorial.stateful.Book

since I m trying to test a stateful EJB i got the "java.lang.ClassCastException: java.lang.String cannot be cast to com.tutorial.stateful.Book" error.
my client code looks as follow
import com.tutorial.stateful.LibraryStatefulSessionBeanRemote;
import com.tutorial.stateful.Book;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class EJBTesterStateful {
BufferedReader brConsoleReader = null;
Properties props;
InitialContext ctx;
{
props = new Properties();
try {
props.load(new FileInputStream("jndi.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
try {
ctx = new InitialContext(props);
} catch (NamingException ex) {
ex.printStackTrace();
}
brConsoleReader =
new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
EJBTesterStateful ejbTester = new EJBTesterStateful();
ejbTester.testStatefulEjb();
}
private void showGUI(){
System.out.println("**********************");
System.out.println("Welcome to Book Store");
System.out.println("**********************");
System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
}
private void testStatefulEjb(){
try {
int choice = 1;
LibraryStatefulSessionBeanRemote libraryBean =
(LibraryStatefulSessionBeanRemote)ctx.lookup("ejb:/EjbComponent//LibraryStatefulSessionBean!com.tutorial.stateful.LibraryStatefulSessionBeanRemote?stateful");
while (choice != 2) {
String bookName;
showGUI();
String strChoice = brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);
if (choice == 1) {
System.out.print("Enter book name: ");
bookName = brConsoleReader.readLine();
Book book = new Book();
book.setName(bookName);
libraryBean.addBook(book.toString());
} else if (choice == 2) {
break;
}
}
List<Book> booksList = libraryBean.getBooks();
System.out.println("Book(s) entered so far: " + booksList.size());
int i = 0;
// Exception line-trigger
for(Book book:booksList){
System.out.println((i+1)+". " + book.getName());
}
LibraryStatefulSessionBeanRemote libraryBean1 =
(LibraryStatefulSessionBeanRemote)ctx.lookup("ejb:/EjbComponent//LibraryStatefulSessionBean!com.tutorial.stateful.LibraryStatefulSessionBeanRemote?stateful");
List<String> booksList1 = libraryBean1.getBooks();
System.out.println(
"***Using second lookup to get library stateful object***");
System.out.println(
"Book(s) entered so far: " + booksList1.size());
for ( i = 0; i < booksList1.size(); ++i) {
System.out.println((i+1)+". " + booksList1.get(i));
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}finally {
try {
if(brConsoleReader !=null){
brConsoleReader.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
the statefull ejb class looks like:
#Stateful
public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote{
List<String> bookShelf;
public LibraryStatefulSessionBean(){
bookShelf = new ArrayList<String>();
}
public void addBook(String bookName) {
bookShelf.add(bookName);
}
public List<String> getBooks() {
return bookShelf;
}
}
is ther any idea to solve this casting issue.
Many Thanks
thanks, your responses were helpful to avoid the casting problem after some changes in stateful Bean class:
getBooks returns a List of Strings not Books
List<String> booksList = libraryBean.getBooks(); // as you've already done for booksList1
for (String book: booksList){
....
}
If you see the following error message
java.lang.String cannot be cast to com.tutorial.stateful.Book
it is very clear that you are assigning an object which is a String to an object which is a Book. This is impossible because there is no relationship in between these two classes. So, a String class cannot be cast to a Book type.
It will raise a ClassCastException.
The problem occurs in this line of code
List<Book> booksList = libraryBean.getBooks(); //this line will throw an exception, because it returns a List<String> not List<Book>.
// Exception line-trigger
for(Book book: booksList){
System.out.println((i+1) + ". " + book.getName());
}
because
public List<String> getBooks() { //returns a List<String> not List<Book>.
return bookShelf;
}

Commit test with the cvsClient api return false

I have this code :
package fr.cnamts.navigo.cvs;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import org.netbeans.lib.cvsclient.CVSRoot;
import org.netbeans.lib.cvsclient.Client;
import org.netbeans.lib.cvsclient.admin.StandardAdminHandler;
import org.netbeans.lib.cvsclient.command.CommandAbortedException;
import org.netbeans.lib.cvsclient.command.CommandException;
import org.netbeans.lib.cvsclient.command.GlobalOptions;
import org.netbeans.lib.cvsclient.command.commit.CommitCommand;
import org.netbeans.lib.cvsclient.connection.AuthenticationException;
import org.netbeans.lib.cvsclient.connection.PServerConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CvsCommandTest {
private static final Logger LOG = LoggerFactory
.getLogger(CvsCommandTest.class);
private final String cvsroot = ":pserver:name:password#host.fr:2401/cvsdata/BUS-2010";
private final String localPath = "/cvsdata/BUS-2010";
private final File f = new File(
"d:/projets/bus/workspaceJhipster/navigo/src/main/resources/logback.xml");
private final File[] files = new File[1];
#Test
public void test() {
CVSRoot root = CVSRoot.parse(cvsroot);
PServerConnection con = new PServerConnection(root);
// con.setUserName(user);
// con.setEncodedPassword(StandardScrambler.getInstance().scramble(
// password));
GlobalOptions globalOptions = new GlobalOptions();
globalOptions.setCVSRoot(root.toString());
Client client = new Client(con, new StandardAdminHandler());
// this line is important, because otherwise you'll get a
// NullpointerException!
client.setLocalPath(localPath);
files[0] = f;
LOG.info("COMMITING");
CommitCommand commitCmd = new CommitCommand();
commitCmd.setBuilder(null);
commitCmd.setRecursive(true);
for (int i = 0; i < files.length; i++) {
LOG.info("- " + files[i].getAbsolutePath());
}
commitCmd.setFiles(files);
commitCmd.setToRevisionOrBranch("testTag");
try {
client.getConnection().open();
LOG.info("CVS COMMAND: " + commitCmd.getCVSCommand());
boolean success = client.executeCommand(commitCmd, globalOptions);
LOG.info("COMMIT COMPLETED : " + success);
client.getConnection().close();
} catch (CommandAbortedException cae) {
LOG.error("Probleme CommandAbortedException : " + cae.getMessage());
} catch (AuthenticationException ae) {
LOG.error("Probleme AuthenticationException : " + ae.getMessage());
} catch (CommandException ce) {
LOG.error("Probleme CommandException : " + ce.getMessage());
} catch (IOException ioe) {
LOG.error("Probleme IOException : " + ioe.getMessage());
}
}
}
success is false :
[INFO] fr.cnamts.navigo.cvs.CvsCommandTest - COMMITING [INFO]
fr.cnamts.navigo.cvs.CvsCommandTest - -
d:\projets\bus\workspaceJhipster\navigo\src\main\resources\logback.xml
[INFO] fr.cnamts.navigo.cvs.CvsCommandTest - CVS COMMAND: commit -r
testTag logback.xml [INFO] fr.cnamts.navigo.cvs.CvsCommandTest -
COMMIT COMPLETED : false
but I don't know why it fails. Is there a way to find why it fails?
To add a listener follow the steps described here in the "Listening" section. It displays information message from cvs to the user.

How to get list of JNDI Names from Weblogic Server?

I am getting the list of datasources configured in context.xml of Tomcat Server using the method below :
public static List<String> getDataSourcesList() {
List<String> dataSourceList = new ArrayList<String>();
try {
if( initialContext == null ) {
initialContext = new InitialContext();
}
NamingEnumeration<NameClassPair> list = ( ( Context )initialContext.lookup( DATASOURCE_CONTEXT ) ).list( "" );
while( list.hasMore() ) {
dataSourceList.add( list.next().getName() );
}
}
catch( NamingException ex ) {
Logger.getLogger( JDBCUtil.class.getName() ).log( Level.SEVERE, null, ex );
}
return dataSourceList;
}
But this method does not work for Weblogic and Websphere Servers.
How can I get the list of datasource names configured on the Weblogic/WebSphere Servers ?
Is there any method to get the list of datasource names ?
For WebSphere Application Server just use dumpNameSpace command line tool located in PROFILE_ROOT\bin
And your code with small modification is working fine in WAS 8.5.5:
try {
InitialContext initialContext = new InitialContext();
NamingEnumeration<NameClassPair> list = ((Context)initialContext.lookup( "jdbc" ) ).list( "" );
while( list.hasMore() ) {
System.out.println(list.next().getName() );
}
}
catch( NamingException ex ) {
ex.printStackTrace();
}
package jms.queue;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class CheckDB {
public CheckDB() {
super();
}
public static void main(String[] args) {
CheckDB checkDB = new CheckDB();
System.out.println(checkDB.listJDBCContextTable());
}
private Context getContext() throws NamingException {
Hashtable myCtx = new Hashtable();
myCtx.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
// myCtx.put(Context.PROVIDER_URL, "t3://172.30.60.76:7001"); //Admin Server
myCtx.put(Context.PROVIDER_URL, "t3://astpdsoam03.auca.corp:8001"); // SOA Cluster
Context ctx = new InitialContext(myCtx);
return ctx;
}
private String checkDataSource(DataSource ds) {
try {
Connection conn = ds.getConnection();
Statement st = conn.createStatement();
st.execute("select sysdate mydate from dual");
st.getResultSet().next();
Date mydate = st.getResultSet().getDate("mydate");
conn.close();
String date = mydate.toString();
if (date.length() == 10 && date.indexOf("-") == 4 &&
date.lastIndexOf("-") == 7) {
return "OK";
} else {
return "NOK";
}
} catch (Exception e) {
return "NOK"; //getStackTrace(e);
}
}
private static String getStackTrace(Throwable e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
private String listJDBCContextTable() {
String output = "<table>";
ArrayList<String> tab = new ArrayList<String>();
String line = "";
try {
tab = listContext((Context)getContext().lookup("jdbc"), "", tab);
Collections.sort(tab);
for (int i = 0; i < tab.size(); i++) {
output += tab.get(i);
}
output += "</table>";
return output;
} catch (NamingException e) {
return getStackTrace(e);
}
}
private ArrayList<String> listContext(Context ctx, String indent,
ArrayList<String> output) throws NamingException {
String name = "";
try {
NamingEnumeration list = ctx.listBindings("");
while (list.hasMore()) {
Binding item = (Binding)list.next();
String className = item.getClassName();
name = item.getName();
// System.out.println("Name : " + name);
if (!(item.getObject() instanceof DataSource)) {
//output = output+indent + className + " " + name+"\n";
} else {
output.add("<tr><td>" + name + "</td><td>" +
checkDataSource((DataSource)item.getObject()) +
"</td></tr>\n");
}
Object o = item.getObject();
if (o instanceof javax.naming.Context) {
listContext((Context)o, indent + " ", output);
}
}
} catch (NamingException ex) {
output.add("<tr><td>" + name + "</td><td>" + getStackTrace(ex) +
"</td></tr>\n");
}
return output;
}
}

how to solve The import com.atlassian cannot be resolved?

Hello I am trying to develop my web application using jsp. I have 6 jsp pages in it. Pages are registration.jsp, login.jsp, r1.jsp, welcome.jsp, createroom.jsp and showroom.jsp respectivly. My goal is that when i login in login page, page should redirect in openmeeting server. For that i have created webservice like omRestService. For calling this Service i have created two java class omGateWay and OmPluginSettings respectivly. Everything works fine but error occurs in ompluginSetting class.error mention below.
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
(The import com.atlassian cannot be resolved)
Here I am Providing you my OmPluginSeeting.java file which has error. There are many errors occur at PluginSettingsFactory.
package restService;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OmPluginSettings
{
private static final Logger log = (Logger) LoggerFactory.getLogger(OmPluginSettings.class);
final PluginSettingsFactory pluginSettingsFactory;
public OmPluginSettings(PluginSettingsFactory pluginSettingsFactory)
{
this.pluginSettingsFactory = pluginSettingsFactory;
}
public void storeSomeInfo(String key, String value)
{
this.pluginSettingsFactory.createGlobalSettings().put("openmeetings:" + key, value);
}
public Object getSomeInfo(String key)
{
return this.pluginSettingsFactory.createGlobalSettings().get("openmeetings:" + key);
}
public void storeSomeInfo(String projectKey, String key, String value)
{
this.pluginSettingsFactory.createSettingsForKey(projectKey).put("openmeetings:" + key,
value);
}
public Object getSomeInfo(String projectKey, String key) {
return this.pluginSettingsFactory.createSettingsForKey(projectKey).get("openmeetings:"
+ key);
}
}
I also provide my restservice which is Given Below and totally error free.
package restService;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class omRestService
{
private static final Logger log = (Logger)
LoggerFactory.getLogger(omRestService.class);
private URI getURI(String url) {
return UriBuilder.fromUri(
url).build(new Object[0]);
}
private String getEncodetURI(String url) throws MalformedURLException
{
return new URL(url).toString().replaceAll(" ", "%20");
}
public LinkedHashMap<String, Element> call(String request, Object param)
throws Exception
{
HttpClient client = new HttpClient();
GetMethod method = null;
try
{
method = new GetMethod(getEncodetURI(request).toString());
}
catch (MalformedURLException e) {
e.printStackTrace();
}
int statusCode = 0;
try {
statusCode = client.executeMethod(method);
}
catch (HttpException e)
{
throw new Exception("Connection to OpenMeetings refused. Please check your
OpenMeetings configuration.");
}
catch (IOException e)
{
throw new Exception("Connection to OpenMeetings refused. Please check your
OpenMeetings configuration.");
}
switch (statusCode)
{
case 200:
break;
case 400:
throw new Exception("Bad request. The parameters passed to the service did
not match
as expected. The Message should tell you what was missing or incorrect.");
case 403:
throw new Exception("Forbidden. You do not have permission to access this
resource, or
are over your rate limit.");
case 503:
throw new Exception("Service unavailable. An internal problem prevented us
from
returning data to you.");
default:
throw new Exception("Your call to OpenMeetings! Web Services returned an
unexpected
HTTP status of: " + statusCode);
}
InputStream rstream = null;
try
{
rstream = method.getResponseBodyAsStream();
}
catch (IOException e) {
e.printStackTrace();
throw new Exception("No Response Body");
}
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
SAXReader reader = new SAXReader();
Document document = null;
String line;
try
{
// String line;
while ((line = br.readLine()) != null)
{
// String line;
document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
throw new Exception("UnsupportedEncodingException by SAXReader");
}
catch (IOException e) {
e.printStackTrace();
throw new Exception("IOException by SAXReader in REST Service");
}
catch (DocumentException e) {
e.printStackTrace();
throw new Exception("DocumentException by SAXReader in REST Service");
} finally {
br.close();
}
Element root = document.getRootElement();
LinkedHashMap elementMap = new LinkedHashMap();
for (Iterator i = root.elementIterator(); i.hasNext(); )
{
Element item = (Element)i.next();
if (item.getNamespacePrefix() == "soapenv") {
throw new Exception(item.getData().toString());
}
String nodeVal = item.getName();
elementMap.put(nodeVal, item);
}
return elementMap;
}
}
After This RestService i have make OmGateWay class which has many method for integrate with openmeetings. which is given below:
package org.openmeetings.jira.plugin.gateway;
import java.util.LinkedHashMap;
import org.dom j.Element;
import org.openmeetings.jira.plugin.ao.adminconfiguration.OmPluginSettings;
import org.slf j.Logger;
import org.slf j.LoggerFactory;
public class OmGateway
{
private static final Logger log =
LoggerFactory.getLogger(OmGateway.class);
private OmRestService omRestService;
private OmPluginSettings omPluginSettings;
private String sessionId;
public OmGateway(OmRestService omRestService, OmPluginSettings omPluginSettings)
{
this.omRestService = omRestService;
this.omPluginSettings = omPluginSettings;
}
public Boolean loginUser() throws Exception
{
LinkedHashMap result = null;
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String userpass = (String)this.omPluginSettings.getSomeInfo("userpass");
String omusername =
(String)this.omPluginSettings.getSomeInfo("username");
String sessionURL = "http://" + url + ":" + port + "/openmeetings
/services/
UserService/getSession";
LinkedHashMap elementMap = this.omRestService.call(sessionURL, null);
Element item = (Element)elementMap.get("return");
setSessionId(item.elementText("session_id"));
log.info(item.elementText("session_id"));
result = this.omRestService.call("http://" + url + ":" + port +
"/openmeetings/
services/UserService/loginUser?SID=" + getSessionId() + "&username=" +
omusername
+ "&userpass=" + userpass, null);
if
(Integer.valueOf(((Element)result.get("return")).getStringValue()).intValue() >
) {
return Boolean.valueOf(true);
}
return Boolean.valueOf(false);
}
public Long addRoomWithModerationExternalTypeAndTopBarOption(Boolean
isAllowedRecording,
Boolean isAudioOnly, Boolean isModeratedRoom, String name, Long
numberOfParticipent, Long
roomType, String externalRoomType)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String roomId = "";
String restURL = "http://" + url + ":" + port + "/openmeetings/services/
RoomService/addRoomWithModerationExternalTypeAndTopBarOption?" +
"SID=" + getSessionId() +
"&name=" + name +
"&roomtypes_id=" + roomType.toString() +
"&comment=jira" +
"&numberOfPartizipants=" + numberOfParticipent.toString() +
"&ispublic=false" +
"&appointment=false" +
"&isDemoRoom=false" +
"&demoTime=" +
"&isModeratedRoom=" + isModeratedRoom.toString() +
"&externalRoomType=" + externalRoomType +
"&allowUserQuestions=" +
"&isAudioOnly=" + isAudioOnly.toString() +
"&waitForRecording=false" +
"&allowRecording=" + isAllowedRecording.toString() +
"&hideTopBar=false";
LinkedHashMap result = this.omRestService.call(restURL, null);
roomId = ((Element)result.get("return")).getStringValue();
return Long.valueOf(roomId);
}
public Long updateRoomWithModerationAndQuestions(Boolean isAllowedRecording,
Boolean
isAudioOnly, Boolean isModeratedRoom, String roomname, Long
numberOfParticipent, Long
roomType, Long roomId)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String updateRoomId = "";
String restURL = "http://" + url + ":" + port + "/openmeetings/services
/RoomService/
updateRoomWithModerationAndQuestions?" +
"SID=" + getSessionId() +
"&room_id=" + roomId.toString() +
"&name=" + roomname.toString() +
"&roomtypes_id=" + roomType.toString() +
"&comment=" +
"&numberOfPartizipants=" + numberOfParticipent.toString() +
"&ispublic=false" +
"&appointment=false" +
"&isDemoRoom=false" +
"&demoTime=" +
"&isModeratedRoom=" + isModeratedRoom.toString() +
"&allowUserQuestions=";
LinkedHashMap result = this.omRestService.call(restURL, null);
log.info("addRoomWithModerationExternalTypeAndTopBarOption with ID: ",
((Element)result.get("return")).getStringValue());
updateRoomId = ((Element)result.get("return")).getStringValue();
return Long.valueOf(updateRoomId);
}
public String setUserObjectAndGenerateRoomHash(String username, String
firstname, String
lastname, String profilePictureUrl, String email, String externalUserId, String
externalUserType, Long room_id, int becomeModeratorAsInt, int
showAudioVideoTestAsInt)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String roomHash = null;
String restURL = "http://" + url + ":" + port + "/openmeetings/services
/UserService/
setUserObjectAndGenerateRoomHash?" +
"SID=" + getSessionId() +
"&username=" + username +
"&firstname=" + firstname +
"&lastname=" + lastname +
"&profilePictureUrl=" + profilePictureUrl +
"&email=" + email +
"&externalUserId=" + externalUserId +
"&externalUserType=" + externalUserType +
"&room_id=" + room_id +
"&becomeModeratorAsInt=" + becomeModeratorAsInt +
"&showAudioVideoTestAsInt=" + showAudioVideoTestAsInt;
LinkedHashMap result = this.omRestService.call(restURL, null);
roomHash = ((Element)result.get("return")).getStringValue();
return roomHash;
}
public String getSessionId() {
return this.sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
I want to call loginuser method from OmGateway class on Jsp Button Click Event. Kindly help me to solve this Error. And Help To Redirect and Integrate to openmeetings. Thank you In Advance.
Visit Atlassian Developers for help
Have you ever tried the Jira Plugin from the website:
http://openmeetings.apache.org/JiraPlugin.html
or is this actually the plugin code that you are posting here?

Categories

Resources