How to access ehcache mbeans on weblogic server - java

In my weblogic server ehcache is deployed , I need to get ehcahe mbeans from this program through java programming, Through JMX i am not able to connect.how can i get those custom mbeans??
i tried to get mbeans through weblogic t3 protocol
public class Test
{
private String hostName = "";
private String port = "";
private String userName = "";
private String password = "";
private String connectorURL = "service:jmx:rmi:///jndi/rmi://{0}:{1}/jmxrmi";
private JMXConnector jmxc = null;
public static void main(String []args) throws Exception
{
Test t = new Test();
t.hostName = args[0];
System.out.println(args[1]);
t.port = args[1];
t.userName = args[2];
t.password = args[3];
t.jmxc = t.initConnection();
MBeanServerConnection mbsc = t.jmxc.getMBeanServerConnection();
System.out.println(mbsc);
Set<ObjectInstance> st =mbsc.queryMBeans(new ObjectName("net.*:*"), null);
System.out.println(st.toString());
Iterator<ObjectInstance> it = st.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
t.closeConnection();
}
private JMXConnector initConnection()
{
System.out.println("initiate connection");
JMXServiceURL serviceURL = null;
try
{
String jndiroot = "/jndi/";
String mserver = "weblogic.management.mbeanservers.domainruntime";
int port1 = Integer.parseInt(port);
serviceURL = new JMXServiceURL("t3", hostName, port1, jndiroot + mserver);
Hashtable h = new Hashtable();
h.put(Context.SECURITY_PRINCIPAL, userName);
h.put(Context.SECURITY_CREDENTIALS, password);
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
long lngJmxClientWTO = 10000;
h.put("jmx.remote.x.request.waiting.timeout", lngJmxClientWTO );
return JMXConnectorFactory.connect(serviceURL, h);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* This method closes client connection with server
* #throws IOException
*/
public void closeConnection()
{
if(jmxc != null)
{
try
{
jmxc.close();
}
catch (IOException e) {
jmxc = null;
}
}
}

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
CacheManager manager = CacheManager.newInstance();
Ehcache cache = manager.getEhcache("Some cache name here..."); //<-- PLEASE EDIT THE CACHE NAME...
I don't know if this is what you're asking for....
Once you've obtained your cache, you can use it, pretty much like a java Map.
You can follow the Ehcache documentation to see how to programmatically get the remote cache. Essentially, you will need to create a configuration (or configuration file) which the CacheManager can access.

Related

Migration from JBoss 4.2.3 to Wildfly 8. Is it worth the effort?

We have an old client application that is deployed on JBoss 4.2.3 and written in JAVA EJB2. It has classes that depend on JBoss's security libraries, an Oracle DataSource and ANT as build method. Now there is a need of upgrading the application server because JBoss 4 no longer has life support and we are required to upgrade to Wildfly(Version 8.2 in our case). Naturally we are having a lot of problems during the process and working tirelessly just to go no further from where we are.
I just would like to get community's thoughts on this process. Is it worth the effort to upgrade JBoss or should one just re-write the client from scratch with a newer technology e.g Spring? What is the best practice in a situation like this?
By the way this client is not a big application, it is used by only 6 users.
As proposed by Michele Dorigatti, Here are some more details on the project:
I already spent an estimate of 15 m/d on the upgrade proces.
We are required to implement the solution in 3 weeks from now on.
The app itself isn't that large, it consists of 1 login screen and 1 main view. There are several functionalities which would make up to maybe 15-20 use cases.
The team for the project consists of 2 developers (One being me), who have another project on their hand.
The app functions mainly on Oracle stored procedures and works maybe on 5-10 DB tables.
Also here is an example code snippet from the app
package tr.com.splogin;
import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.AbstractServerLoginModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.sql.DataSource;
import java.security.Principal;
import java.security.acl.Group;
import java.sql.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class SPLoginModule extends AbstractServerLoginModule {
private static final int USER_LOCKEDOUT = 23;
private static final int USER_VALFAIL = 24;
private static final int USER_MAXATTEMPTS = 25;
private static final String ROLE_GROUP_NAME = "Roles";
private static final String ID_GROUP_NAME = "Id";
private static Logger logger = LoggerFactory.getLogger(SPLoginModule.class);
private static final SimplePrincipal GUEST = new SimplePrincipal("guest");
private static boolean initialized = false;
private static boolean initFailed = false;
private static Connection conn;
private static CallableStatement cs;
private static PreparedStatement ps;
private static ResultSet rs;
/**
* The principal to use when a null username and password are seen
*/
private static Principal unauthenticatedIdentity;
private static Map options;
/**
* The roles of the authenticated user
*/
private Group[] roleSets;
/**
* The proof of login identity
*/
private char[] credential;
/**
* The login identity
*/
private Principal identity;
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
logger.info("initialize start");
System.out.println("initialize start");
super.initialize(subject, callbackHandler, sharedState, options);
if (!initialized) {
this.options = options;
init(options);
initialized = true;
}
logger.info("initialize stop");
}
private String getUsername() {
String username = null;
if (getIdentity() != null)
username = getIdentity().getName();
return username;
}
public boolean login() throws LoginException {
System.out.println("login is called.");
String[] info = getUsernameAndPassword();
String username = info[0];
String password = info[1];
logger.info(username);
logger.info(password);
super.loginOk = false;
if (username == null && password == null) {
identity = unauthenticatedIdentity;
Group roles = new SimpleGroup(ROLE_GROUP_NAME);
Set groups = new HashSet();
groups.add(roles);
roles.addMember(GUEST);
roleSets = new Group[groups.size()];
groups.toArray(roleSets);
logger.info("Authenticating as unauthenticatedIdentity=" + identity);
}
if (identity == null) {
identity = new SimplePrincipal(username);
login(username, password);
}
super.loginOk = true;
logger.info("User '" + identity + "' authenticated, loginOk=" + loginOk);
return true;
}
public Principal getIdentity() {
return identity;
}
public Group[] getRoleSets() {
return roleSets;
}
private void login(String username, String password) throws LoginException {
System.out.println("login is called.");
try {
int userIdCode = 3;
int resultCode = 4;
int result, userId;
cs.setString(1, username);
cs.setString(2, password);
cs.registerOutParameter(userIdCode, Types.INTEGER);
cs.registerOutParameter(resultCode, Types.INTEGER);
cs.execute();
result = cs.getInt(resultCode);
if (result == 0) {
userId = cs.getInt(userIdCode);
logger.info("Id: " + userId);
Group roles = new SimpleGroup(ROLE_GROUP_NAME);
Group id = new SimpleGroup(ID_GROUP_NAME);
Set groups = new HashSet();
String roleName;
groups.add(roles);
groups.add(id);
ps.setInt(1, userId);
rs = ps.executeQuery();
id.addMember(new SimplePrincipal((new Integer(userId)).toString()));
while (rs.next()) {
roleName = rs.getString(1);
logger.debug("Action: " + roleName);
roles.addMember(new SimplePrincipal(roleName));
}
roles.addMember(GUEST);
roleSets = new Group[groups.size()];
groups.toArray(roleSets);
} else {
String message = new String();
roleSets = new Group[0];
switch (result) {
case USER_VALFAIL:
System.out.println("login is failed.");
message = new String("Login failed");
break;
case USER_LOCKEDOUT:
message = new String("User is locked out");
break;
case USER_MAXATTEMPTS:
message = new String("Max number of attempts reached, user is locked out");
break;
default:
message = new String("Unkown failed login error with code: " + result);
break;
}
logger.info("Error result code: " + result);
logger.info("Error message: " + message);
throw new FailedLoginException(message);
}
} catch (SQLException e) {
logger.error(e.toString());
init(options);
if (!initFailed)
login(username, password);
} finally {
try {
if (rs != null)
rs.close();
} catch (SQLException e1) {
logger.error(e1.toString());
}
}
}
private void init(Map options) {
logger.info("init");
try {
if (cs != null)
cs.close();
if (ps != null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
logger.error(e.toString());
}
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/OracleDS");
conn = ds.getConnection();
String sp_login = "{call admin_pck.pc_login(?,?,?,?)}";
String query_user_action = "select aa.name from admin_user au,admin_role ar,admin_action aa,admin_user_role aur,admin_role_action ara,owner o where au.id=? and aur.id_admin_user=au.id and aa.id=ara.id_admin_action and ara.id_admin_role=ar.id and ar.id=aur.id_role and o.id=aur.id_owner and o.id=au.id_primary_owner order by aa.name";
cs = conn.prepareCall(sp_login);
ps = conn.prepareStatement(query_user_action);
String name = (String) options.get("unauthenticatedIdentity");
if (name != null) {
unauthenticatedIdentity = new SimplePrincipal(name);
logger.info("Saw unauthenticatedIdentity=" + name);
}
initFailed = false;
} catch (NamingException e) {
logger.error(e.toString());
initFailed = true;
} catch (SQLException e) {
logger.error(e.toString());
initFailed = true;
}
}
/**
* Called by login() to acquire the username and password strings for
* authentication. This method does no validation of either.
*
* #return String[], [0] = username, [1] = password
* #throws LoginException thrown if CallbackHandler is not set or fails.
*/
protected String[] getUsernameAndPassword() throws LoginException {
String[] info = {null, null};
// prompt for a username and password
if (callbackHandler == null) {
throw new LoginException("Error: no CallbackHandler available to collect authentication information");
}
NameCallback nc = new NameCallback("User name: ");
PasswordCallback pc = new PasswordCallback("Password: ", false);
Callback[] callbacks = {nc, pc};
String username = null;
String password = null;
try {
callbackHandler.handle(callbacks);
username = nc.getName();
char[] tmpPassword = pc.getPassword();
if (tmpPassword != null) {
credential = new char[tmpPassword.length];
System.arraycopy(tmpPassword, 0, credential, 0, tmpPassword.length);
pc.clearPassword();
password = new String(credential);
}
} catch (java.io.IOException e) {
throw new LoginException(e.toString());
} catch (UnsupportedCallbackException e) {
throw new LoginException("CallbackHandler does not support: " + e.getCallback());
}
info[0] = username;
info[1] = password;
return info;
}
}

WebServiceException: Method beaInvoke is exposed as WebMethod

Below is the code Snippet.. that must call WSDL in other server dynamically
but in the moment of calling
(int i = webServiceModuleService.notificationRecieved("xyz");)
returned exception :(
note: i haven't any beaInvoke method in my service :|
public static void main(String[] args) {
java.sql.Connection conn = null;
InitialContext context;
try {
context = new InitialContext();
DataSource ds = (DataSource) context.lookup("jdbc/dataSourceDS");
conn = ds.getConnection();
} catch (SQLException e) {
} catch (NamingException e) {
}
QueryRunner run = new QueryRunner();
SampleResultSetHandler h = new SampleResultSetHandler();
Object[] res = null;
try {
res = run.query(conn, "select SERVER_IP,SERVER_PORT from SERVER where UPPER(SERVER_NAME)=? ", h, "test");
} catch (SQLException e) {
}
String ip = res[0].toString();
String port = res[1].toString();
String endpointURL = "http://" + ip + ":" + port + "/context-root/WebServiceModuleService";
try {
URL tmpURL = new URL(endpointURL + "?wsdl");
System.err.println(tmpURL);
WebServiceModuleService_Service webServiceModuleService_Service = new WebServiceModuleService_Service(tmpURL,
new QName("/org/parsisys/test/mina/model/services/common/",
"WebServiceModuleService"));
WebServiceModuleService webServiceModuleService = null;
webServiceModuleService = webServiceModuleService_Service.getWebServiceModuleServiceSoapHttpPort();
BindingProvider bp = (BindingProvider) webServiceModuleService;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
// Configure credential providers
Map<String, Object> requestContext = ((BindingProvider) webServiceModuleService).getRequestContext();
try {
setPortCredentialProviderList(requestContext);
} catch (Exception ex) {
ex.printStackTrace();
}
//Call WebService ... ==> Exception :(
int i = webServiceModuleService.notificationRecieved("xyz");
//logp("successfully call the webservice for [ip&port:" + ip + ":" + port + "] [transid : " +transid + "]");
} catch (Exception e) {
//log
//TODO: Clean This
System.err.println(e.getMessage());
e.printStackTrace();
return;
}
}
#Generated("Oracle JDeveloper")
public static void setPortCredentialProviderList(Map<String, Object> requestContext) throws Exception {
// TODO - Provide the required credential values
String username = "";
String password = "";
String clientKeyStore = "";
String clientKeyStorePassword = "";
String clientKeyAlias = "";
String clientKeyPassword = "";
String serverKeyStore = "";
String serverKeyStorePassword = "";
String serverKeyAlias = "";
List<CredentialProvider> credList = new ArrayList<CredentialProvider>();
// Add the necessary credential providers to the list
// Code commented out due to empty username/password value found in the credential.
// credList.add(getUNTCredentialProvider(username, password));
// Code commented out due to empty server keystore value found in the credential.
// credList.add(getBSTCredentialProvider(clientKeyStore, clientKeyStorePassword, clientKeyAlias, clientKeyPassword, serverKeyStore, serverKeyStorePassword, serverKeyAlias, requestContext));
credList.add(getSAMLTrustCredentialProvider());
requestContext.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credList);
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getSAMLTrustCredentialProvider() {
return new SAMLTrustCredentialProvider();
}
daynamic webservice call is generated with jdeveloper and it's works in clien't tester but in my module when i call webservice return exception :/
StackTrace is: ↓
Method beaInvoke is exposed as WebMethod, but there is no corresponding wsdl operation with name {/org/parsisys/test/mina/model/services/common/}beaInvoke in the wsdl:portType{/org/parsisys/test/mina/model/services/common/}WebServiceModuleService
javax.xml.ws.WebServiceException: Method beaInvoke is exposed as WebMethod, but there is no corresponding wsdl operation with name {/org/parsisys/test/mina/model/services/common/}beaInvoke in the wsdl:portType{/org/parsisys/test/mina/model/services/common/}WebServiceModuleService
at com.sun.xml.ws.model.JavaMethodImpl.freeze(JavaMethodImpl.java:382)
at com.sun.xml.ws.model.AbstractSEIModelImpl.freeze(AbstractSEIModelImpl.java:124)
at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:336)
at com.sun.xml.ws.db.DatabindingImpl.(DatabindingImpl.java:99)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:74)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:58)
at com.sun.xml.ws.db.DatabindingFactoryImpl.createRuntime(DatabindingFactoryImpl.java:120)
at com.sun.xml.ws.client.WSServiceDelegate.buildRuntimeModel(WSServiceDelegate.java:882)
at com.sun.xml.ws.client.WSServiceDelegate.createSEIPortInfo(WSServiceDelegate.java:899)
at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:862)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:451)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.internalGetPort(WLSProvider.java:1698)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$PortClientInstanceFactory.createClientInstance(WLSProvider.java:1769)
at weblogic.wsee.jaxws.spi.ClientInstancePool.takeSimpleClientInstance(ClientInstancePool.java:389)
at weblogic.wsee.jaxws.spi.ClientInstancePool.take(ClientInstancePool.java:243)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$3.apply(WLSProvider.java:1555)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl$3.apply(WLSProvider.java:1517)
at weblogic.wsee.jaxws.spi.ClientIdentityRegistry.initClientIdentityFeatureAndCall(ClientIdentityRegistry.java:1456)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.getPort(WLSProvider.java:1513)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:420)
at weblogic.wsee.jaxws.spi.WLSProvider$ServiceDelegateImpl.getPort(WLSProvider.java:1477)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:402)
at javax.xml.ws.Service.getPort(Service.java:119)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service.beaInvokeSuper(WebServiceModuleService_Service.java)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service$beaVersion0_31.getWebServiceModuleServiceSoapHttpPort(WebServiceModuleService_Service.java:51)
at org.parsisys.test.mina.model.service.WebServiceModuleService_Service.getWebServiceModuleServiceSoapHttpPort(WebServiceModuleService_Service.java)
at org.parsisys.test.mina.files.notification.queue.NotificationQueueRecieved$beaVersion0_11.onMessage(NotificationQueueRecieved.java:330)
at org.parsisys.test.mina.files.notification.queue.NotificationQueueRecieved.onMessage(NotificationQueueRecieved.java)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:5107)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:4775)
at weblogic.jms.client.JMSSession.executeMessage(JMSSession.java:4170)
at weblogic.jms.client.JMSSession.access$000(JMSSession.java:127)
at weblogic.jms.client.JMSSession$UseForRunnable.run(JMSSession.java:5627)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:666)
at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:640)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:406)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)
please help me. tnx
For me this occurs when the WSDL does not agree with the generated classes.

com.jcraft.jsch.JSchException: connection is closed by foreign host when i use jsch to connect my ftp server

i want to start a Sftp server by embedding it in my java code .
when i start the Sftp server and then start the client , the exception throws .
my server code
public class EmbeddedSftpServer {
public static final String SERVER_BASE_DIR = System.getProperty("user.dir") + File.separator + "src";
// public static final String SERVER_KEYSTORE = SERVER_BASE_DIR + File.separator + "resources" + File.separator + "ftpserver.jks";
public static final String SERVER_KEYSTORE= "C:\\Users\\y73wang\\IdeaProjects\\SFTPServer\\src\\main\\resources\\ftpserver.jks";
//public static final String SERVER_USERS = SERVER_BASE_DIR + File.separator + "resources" + File.separator + "users.properties";
public static final String SERVER_USERS ="C:\\Users\\y73wang\\IdeaProjects\\SFTPServer\\src\\main\\resources\\users.properties";
//public static final String USER_HOME_DIR = SERVER_BASE_DIR + File.separator + "SftpHomeDir" ;
public static final String USER_HOME_DIR = "D:\\TEST";
public static final String SAMPLE_FILE = "test.txt";
public static final String ADMIN = "admin";
public static final String PASSWORD = "password";
public static final int DEFAULT_PORT =8009;
private final FtpServer server;
public static EmbeddedSftpServer createDefaultServer() throws Exception {
return new EmbeddedSftpServer(DEFAULT_PORT,ADMIN,PASSWORD,true);
}
public EmbeddedSftpServer( int port, String username, String password, boolean implicitSsl ) throws Exception {
this.server = createServer( port, username, password, implicitSsl );
}
private FtpServer createServer( int port, String username, String password, boolean implicitSsl ) throws FtpException {
ListenerFactory factory = new ListenerFactory();
factory.setPort( port );
if ( implicitSsl ) {
SslConfigurationFactory ssl = new SslConfigurationFactory();
ssl.setKeystoreFile( new File( SERVER_KEYSTORE ) );
ssl.setKeystorePassword( PASSWORD );
// set the SSL configuration for the listener
factory.setSslConfiguration( ssl.createSslConfiguration() );
factory.setImplicitSsl( true );
}
FtpServerFactory serverFactory = new FtpServerFactory();
// replace the default listener
serverFactory.addListener( "default", factory.createListener() );
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile( new File( SERVER_USERS ) );
UserManager userManager = userManagerFactory.createUserManager();
if ( !userManager.doesExist( username ) ) {
BaseUser user = new BaseUser();
user.setName( username );
user.setPassword( password );
user.setEnabled( true );
user.setHomeDirectory( USER_HOME_DIR );
user.setAuthorities( Collections.<Authority>singletonList( new WritePermission() ) );
userManager.save( user );
}
serverFactory.setUserManager( userManager );
return serverFactory.createServer();
}
public void start() throws FtpException {
server.start();
}
public void stop(){
if (server != null){
server.stop();
}
}
public static void main(String[] args) throws Exception {
EmbeddedSftpServer sftpServer = new EmbeddedSftpServer(DEFAULT_PORT,"admin","admin",true);
sftpServer.start();
}
}
user.properties:
# Password is "admin"
ftpserver.user.admin.userpassword=21232F297A57A5A743894A0E4A801FC3
ftpserver.user.admin.homedirectory=D:/test
ftpserver.user.admin.enableflag=true
ftpserver.user.admin.writepermission=true
ftpserver.user.admin.maxloginnumber=10
ftpserver.user.admin.maxloginperip=10
ftpserver.user.admin.idletime=0
ftpserver.user.admin.uploadrate=0
ftpserver.user.admin.downloadrate=0
ftpserver.user.anonymous.userpassword=
ftpserver.user.anonymous.homedirectory=D:/test
ftpserver.user.anonymous.enableflag=true
ftpserver.user.anonymous.writepermission=false
ftpserver.user.anonymous.maxloginnumber=20
ftpserver.user.anonymous.maxloginperip=2
ftpserver.user.anonymous.idletime=300
ftpserver.user.anonymous.uploadrate=4800
ftpserver.user.anonymous.downloadrate=4800
the Client code :
public class JschClient {
public void sendFile(String filename) throws JSchException, SftpException, FileNotFoundException {
int Port =22;
String sftphost = "127.0.0.1";
String userName = "admin";
String password = "admin";
String HomeDir = "D:\\test";
Session session =null;
Channel channel =null;
ChannelSftp channelSftp = null;
JSch jSch = new JSch();
session =jSch.getSession(userName,sftphost,8009);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking","no");
config.put("PreferredAuthentications", "password");
session.setConfig(config);
session.setPassword(password);
session.connect(60000);
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
((ChannelSftp) channel).cd(HomeDir);
File f = new File(filename);
channelSftp.put(new FileInputStream(f),f.getName());
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
public static void main(String[]agrs) throws FileNotFoundException, JSchException, SftpException {
JschClient jschClient = new JschClient();
jschClient.sendFile("D:\\file1.txt");
}
error log:
Exception in thread "main" com.jcraft.jsch.JSchException: connection is closed by foreign host
at com.jcraft.jsch.Session.connect(Session.java:269)
at client.JschClient.sendFile(JschClient.java:29)
at client.JschClient.main(JschClient.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
is there any wrong in my code ?
May be i am very late to answer your question but still if anyone needs how to connect with SFTP using jsch library.
You can use below method
static Session session = null;
static Channel channel = null;
public Session sftpConnection(final String value, final String sftpUser, final String sftpHost, final int sftpPort,
final String sftpPass) {
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
this.session = jsch.getSession(sftpUser, sftpHost, sftpPort);
if (value.equals("puttyServer")) {
this.session.setProxy(new ProxySOCKS5("proxy need to add", Integer.parseInt("portnumber need to add")));
}
this.session.setPassword(sftpPass);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
this.session.setConfig(config);
this.session.connect();
return this.session;
} catch (Exception ex) {
ex.printStackTrace();
sftpConnection(value, sftpUser, sftpHost, sftpPort, sftpPass);
}
return null;
}
You are starting an FTP server, but connecting to it using an SFTP client.
That cannot work. The FTP and SFTP are two completely different and incompatible protocols.
This could be the issue of whitelisting the servers.
Consider there are two servers named X and Y and You are trying to connect to Y from X using Jsch SFTP.
In that case, server X should be in white list of server Y.
**************CODE BLOCK of SESSION CLASS********
while(true){
i=0;
j=0;
while(i<buf.buffer.length){
**j=io.getByte();** //io.getByte() reads the key which is shared between two servers
if(j<0)break;
buf.buffer[i]=(byte)j; i++;
if(j==10)break;
}
if(j<0){
throw new JSchException("connection is closed by foreign host");
}
just tweak the sshd_config 'MaxStartups' count, for example 'MaxStartups 1000', and restart ssh

Creating thread dumps of a remote jvm programatically

I have been trying to invoke an operation on ThreadMXBean in a remote jvm. The code snippet I used invoke the operation is below
bean = new ObjectName("java.lang:type=Threading");
memoryInfo = RemoteConnector.getRemote().getMBeanInfo(bean);
RemoteConnector.getRemote().getObjectInstance(bean);
MBeanOperationInfo [] mBeanAttributeInfos = memoryInfo.getOperations();
for(MBeanOperationInfo mBeanAttributeInfo : mBeanAttributeInfos){
System.out.println(mBeanAttributeInfo.getName());
}
long [] allThreadIds = (long [])RemoteConnector.getRemote().getAttribute(bean,"AllThreadIds");
Object [] params = new Object[2];
int maxDepth = 100;
params[0] = allThreadIds;
params[1] = maxDepth;
String [] opSigs = {allThreadIds.getClass().getName(),"I"};
RemoteConnector.getRemote().invoke(bean,"getThreadInfo",params,opSigs);
Note that getRemote() method returns a mbeanserverconnection
I can't invoke the method getThreadInfo() on stub. I am getting this message
2016-05-05 00:17:37 ERROR ThreadDumpCreator:67 - Operation getThreadInfo exists but not with this signature: ([J, I)
Please help me resolve this issue :)
Below is the method i used to connect remote mbeanserver
public class RemoteConnector {
private static MBeanServerConnection remote = null;
private static JMXConnector connector = null;
public static void defaultConnector(){
try {
JMXServiceURL target = new JMXServiceURL
("service:jmx:rmi://localhost:11111/jndi/rmi://localhost:9999/jmxrmi");
//for passing credentials for password
Map<String, String[]> env = new HashMap<String, String[]>();
String[] credentials = {"admin", "admin"};
env.put(JMXConnector.CREDENTIALS, credentials);
connector = JMXConnectorFactory.connect(target, env);
remote = connector.getMBeanServerConnection();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static MBeanServerConnection getRemote() {
return remote;
}
public static void setRemote(MBeanServerConnection remote) {
RemoteConnector.remote = remote;
}
public static void closeConnection() throws IOException {
if(connector != null){
connector.close();
}
}
}
Apparently I should have used int.class.getName() as the method signature requires from invoke method

How get access all user attributes available in OID/OAM within Weblogic Security Realm?

We have configured OID/OAM as our security providers in weblogic security.
On checking user attributes, only user id is visible.
How to get all attributes available in OID/OAM to available in Weblogic Security User and Groups?
Short Version: Use JMX as described here to get the configured OID-Authenticator-MBean. You can then use that MBean to get the necessary parameters to establish your own Connection to the OID and traverse the attributes. You might also want to read about Java Naming and Directory Operations here
Sample Implementation:
package test;
import java.util.Hashtable;
import javax.management.Descriptor;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
public class OIDFromWLBean {
// The attribute you want to read (for a specific user)
private static final String ATTRIBUTE_NAME = "pwdChangedTime";
// The Class of the configured Authenticator Provider, here it is OID
// Check the API if you use something else
// API Docs:
// http://docs.oracle.com/cd/E12839_01/apirefs.1111/e13945/weblogic/security/providers/authentication/OracleInternetDirectoryAuthenticatorMBean.html
final String OID_AUTHENTICATOR_MBEAN_NAME = "weblogic.security.providers.authentication.OracleInternetDirectoryAuthenticatorMBean";
// The rest here should be static and stay unchanged
private static final String COM_SUN_JNDI_LDAP_LDAP_CTX_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private static final String INTERFACE_CLASS_NAME = "interfaceClassName";
private static final String AUTHENTICATION_PROVIDERS = "AuthenticationProviders";
private static final String DEFAULT_REALM = "DefaultRealm";
private static final String SECURITY_CONFIGURATION = "SecurityConfiguration";
private static final String DOMAIN_CONFIGURATION = "DomainConfiguration";
final String MBEAN_SERVER = "java:comp/env/jmx/domainRuntime";
final String DOMAIN_MBEAN_NAME = "com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean";
public String getAttribute(String username, String password) {
final MBeanServer connection = getConnection();
final ObjectName defaultAuthenticator = getAuthenticator(connection);
String rest = null;
try {
String host = getHost(defaultAuthenticator, connection);
String port = getPort(defaultAuthenticator, connection);
String userBaseDN = getUserBaseDN(defaultAuthenticator, connection);
DirContext ctx = getConnectionLdapOid(username, password, host, port, userBaseDN);
rest = getAttribute(ctx, "cn=" + username + "," + userBaseDN, username);
} catch (Exception ref) {
// Do something to handle that
}
return rest;
}
private MBeanServer getConnection() {
MBeanServer connection;
try {
InitialContext ctx = new InitialContext();
connection = (MBeanServer) ctx.lookup(MBEAN_SERVER);
} catch (Exception e) {
throw new RuntimeException(e);
}
return connection;
}
private ObjectName getAuthenticator(MBeanServer connection) {
ObjectName authenticator = null;
ObjectName[] authenticationProviders;
try {
ObjectName configurationMBeans = new ObjectName(DOMAIN_MBEAN_NAME);
ObjectName domain = (ObjectName) connection.getAttribute(configurationMBeans, DOMAIN_CONFIGURATION);
ObjectName security = (ObjectName) connection.getAttribute(domain, SECURITY_CONFIGURATION);
ObjectName realm = (ObjectName) connection.getAttribute(security, DEFAULT_REALM);
authenticationProviders = (ObjectName[]) connection.getAttribute(realm, AUTHENTICATION_PROVIDERS);
for (int p = 0; p < authenticationProviders.length; p++) {
ModelMBeanInfo info = (ModelMBeanInfo) connection.getMBeanInfo(authenticationProviders[p]);
Descriptor desc = info.getMBeanDescriptor();
String className = (String) desc.getFieldValue(INTERFACE_CLASS_NAME);
if (className.equals(OID_AUTHENTICATOR_MBEAN_NAME)) {
authenticator = authenticationProviders[p];
break;
}
}
} catch (Exception e) {
// Do something to handle that
}
return authenticator;
}
private DirContext getConnectionLdapOid(String username, String password, String host, String port, String userBaseDN) throws NamingException {
Hashtable<String, String> jndiProps = new Hashtable<String, String>();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, COM_SUN_JNDI_LDAP_LDAP_CTX_FACTORY);
jndiProps.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);
jndiProps.put(Context.SECURITY_AUTHENTICATION, "simple");
jndiProps.put(Context.SECURITY_PRINCIPAL, "cn=" + username + "," + userBaseDN);
jndiProps.put(Context.SECURITY_CREDENTIALS, password);
DirContext ctx = new InitialDirContext(jndiProps);
return ctx;
}
private String getHost(ObjectName defaultAuthenticator, MBeanServer connection) throws Exception {
String result = (String) connection.getAttribute(defaultAuthenticator, "Host");
return result;
}
private String getPort(ObjectName defaultAuthenticator, MBeanServer connection) throws Exception {
String result = ((Integer) connection.getAttribute(defaultAuthenticator, "Port")).toString();
return result;
}
private String getUserBaseDN(ObjectName defaultAuthenticator, MBeanServer connection) throws Exception {
String result = (String) connection.getAttribute(defaultAuthenticator, "UserBaseDN");
return result;
}
#SuppressWarnings("rawtypes")
public static String getAttribute(DirContext ctx, String DN, String user) {
String attrName, attrValue = "";
String result = null;
try {
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
ctls.setReturningAttributes(new String[0]);
NamingEnumeration sre = null;
sre = ctx.search(DN, "cn=" + user, ctls);
if (!(sre != null && sre.hasMoreElements())) {
return null;
}
Attributes attrs = null;
String returnAttrs[] = { ATTRIBUTE_NAME };
attrs = ctx.getAttributes(DN, returnAttrs);
NamingEnumeration enu = attrs.getAll();
if ((enu != null) && enu.hasMore()) {
Attribute attr = (Attribute) enu.next();
attrName = attr.getID();
NamingEnumeration attrValues = attr.getAll();
if (attrValues.hasMore()) {
attrValue = (String) attrValues.next();
}
}
result = attrValue;
} catch (NamingException e) {
// Do something to handle that
}
return result;
}
}

Categories