use of jcifs.smb.SmbException in project opennms by OpenNMS.
the class JCifsMonitorTest method setUp.
@Before
public void setUp() throws Exception {
mockSmbFileValidPath = createNiceMock(SmbFile.class);
expect(mockSmbFileValidPath.exists()).andReturn(true).anyTimes();
expectNew(SmbFile.class, new Class<?>[] { String.class, NtlmPasswordAuthentication.class }, eq("smb://10.123.123.123/validPath"), isA(NtlmPasswordAuthentication.class)).andReturn(mockSmbFileValidPath).anyTimes();
mockSmbFileInvalidPath = createNiceMock(SmbFile.class);
expect(mockSmbFileInvalidPath.exists()).andReturn(false).anyTimes();
expectNew(SmbFile.class, new Class<?>[] { String.class, NtlmPasswordAuthentication.class }, eq("smb://10.123.123.123/invalidPath"), isA(NtlmPasswordAuthentication.class)).andReturn(mockSmbFileInvalidPath).anyTimes();
mockSmbFolderEmpty = createNiceMock(SmbFile.class);
expect(mockSmbFolderEmpty.exists()).andReturn(true).anyTimes();
expect(mockSmbFolderEmpty.list((SmbFilenameFilter) anyObject())).andReturn(new String[] {}).anyTimes();
expectNew(SmbFile.class, new Class<?>[] { String.class, NtlmPasswordAuthentication.class }, eq("smb://10.123.123.123/folderEmpty"), isA(NtlmPasswordAuthentication.class)).andReturn(mockSmbFolderEmpty).anyTimes();
mockSmbFolderNotEmpty = createNiceMock(SmbFile.class);
expect(mockSmbFolderNotEmpty.exists()).andReturn(true).anyTimes();
expect(mockSmbFolderNotEmpty.list((SmbFilenameFilter) anyObject())).andReturn(new String[] { "ABCD", "ACBD", "DCBA", "DABC" }).anyTimes();
expectNew(SmbFile.class, new Class<?>[] { String.class, NtlmPasswordAuthentication.class }, eq("smb://10.123.123.123/folderNotEmpty"), isA(NtlmPasswordAuthentication.class)).andReturn(mockSmbFolderNotEmpty).anyTimes();
mockSmbFileSmbException = createNiceMock(SmbFile.class);
expect(mockSmbFileSmbException.exists()).andThrow(new SmbException(SmbException.ERROR_ACCESS_DENIED, true));
expectNew(SmbFile.class, new Class<?>[] { String.class, NtlmPasswordAuthentication.class }, eq("smb://10.123.123.123/smbException"), isA(NtlmPasswordAuthentication.class)).andReturn(mockSmbFileSmbException).anyTimes();
mockSmbFileMalformedUrlException = createNiceMock(SmbFile.class);
expect(mockSmbFileMalformedUrlException.exists()).andThrow(new SmbException(SmbException.ERROR_ACCESS_DENIED, true));
expectNew(SmbFile.class, new Class<?>[] { String.class, NtlmPasswordAuthentication.class }, eq("smb://10.123.123.123/malformedUrlException"), isA(NtlmPasswordAuthentication.class)).andReturn(mockSmbFileMalformedUrlException).anyTimes();
mockSmbFileSmbHost = createNiceMock(SmbFile.class);
expect(mockSmbFileSmbHost.exists()).andThrow(new SmbException(SmbException.ERROR_ACCESS_DENIED, true));
expectNew(SmbFile.class, new Class<?>[] { String.class, NtlmPasswordAuthentication.class }, eq("smb://192.168.0.123/smbException"), isA(NtlmPasswordAuthentication.class)).andReturn(mockSmbFileSmbHost).anyTimes();
}
use of jcifs.smb.SmbException in project hudson-2.x by hudson.
the class ManagedWindowsServiceLauncher method launch.
@Override
public void launch(final SlaveComputer computer, final TaskListener listener) throws IOException, InterruptedException {
try {
final PrintStream logger = listener.getLogger();
final String name = determineHost(computer);
logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingTo(name));
InetAddress host = InetAddress.getByName(name);
try {
Socket s = new Socket();
s.connect(new InetSocketAddress(host, 135), 5000);
s.close();
} catch (IOException e) {
logger.println("Failed to connect to port 135 of " + name + ". Is Windows firewall blocking this port? Or did you disable DCOM service?");
// again, let it continue.
}
JIDefaultAuthInfoImpl auth = createAuth();
JISession session = JISession.createSession(auth);
session.setGlobalSocketTimeout(60000);
SWbemServices services = WMI.connect(session, name);
String path = computer.getNode().getRemoteFS();
if (path.indexOf(':') == -1)
throw new IOException("Remote file system root path of the slave needs to be absolute: " + path);
SmbFile remoteRoot = new SmbFile("smb://" + name + "/" + path.replace('\\', '/').replace(':', '$') + "/", createSmbAuth());
if (!remoteRoot.exists())
remoteRoot.mkdirs();
try {
// does Java exist?
logger.println("Checking if Java exists");
WindowsRemoteProcessLauncher wrpl = new WindowsRemoteProcessLauncher(name, auth);
Process proc = wrpl.launch("java -fullversion", "c:\\");
proc.getOutputStream().close();
IOUtils.copy(proc.getInputStream(), logger);
proc.getInputStream().close();
int exitCode = proc.waitFor();
if (exitCode == 1) {
// we'll get this error code if Java is not found
//TODO enable me when JDK installer based on REST API will be ready
logger.println("No JDK found on slave node. Please install JDK");
throw new InterruptedException("No JDK found on slave node. Please install JDK");
// logger.println("No Java found. Downloading JDK");
// JDKInstaller jdki = new JDKInstaller("jdk-6u16-oth-JPR@CDS-CDS_Developer",true);
// URL jdk = jdki.locate(listener, Platform.WINDOWS, CPU.i386);
//
// listener.getLogger().println("Installing JDK");
// copyStreamAndClose(jdk.openStream(), new SmbFile(remoteRoot, "jdk.exe").getOutputStream());
//
// String javaDir = path + "\\jdk"; // this is where we install Java to
//
// WindowsRemoteFileSystem fs = new WindowsRemoteFileSystem(name, createSmbAuth());
// fs.mkdirs(javaDir);
//
// jdki.install(new WindowsRemoteLauncher(listener,wrpl), Platform.WINDOWS,
// fs, listener, javaDir ,path+"\\jdk.exe");
}
} catch (Exception e) {
e.printStackTrace(listener.error("Failed to prepare Java"));
}
String id = WindowsSlaveInstaller.generateServiceId(path);
Win32Service slaveService = services.getService(id);
if (slaveService == null) {
logger.println(Messages.ManagedWindowsServiceLauncher_InstallingSlaveService());
if (!DotNet.isInstalled(2, 0, name, auth)) {
// abort the launch
logger.println(Messages.ManagedWindowsServiceLauncher_DotNetRequired());
return;
}
// copy exe
logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveExe());
copyStreamAndClose(getClass().getResource("/windows-service/hudson.exe").openStream(), new SmbFile(remoteRoot, "hudson-slave.exe").getOutputStream());
copySlaveJar(logger, remoteRoot);
// copy hudson-slave.xml
logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveXml());
String xml = WindowsSlaveInstaller.generateSlaveXml(id, "javaw.exe", "-tcp %BASE%\\port.txt");
copyStreamAndClose(new ByteArrayInputStream(xml.getBytes("UTF-8")), new SmbFile(remoteRoot, "hudson-slave.xml").getOutputStream());
// install it as a service
logger.println(Messages.ManagedWindowsServiceLauncher_RegisteringService());
Document dom = new SAXReader().read(new StringReader(xml));
Win32Service svc = services.Get("Win32_Service").cast(Win32Service.class);
int r = svc.Create(id, dom.selectSingleNode("/service/name").getText() + " at " + path, path + "\\hudson-slave.exe", Win32OwnProcess, 0, "Manual", true);
if (r != 0) {
listener.error("Failed to create a service: " + svc.getErrorMessage(r));
return;
}
slaveService = services.getService(id);
} else {
copySlaveJar(logger, remoteRoot);
}
logger.println(Messages.ManagedWindowsServiceLauncher_StartingService());
slaveService.start();
// wait until we see the port.txt, but don't do so forever
logger.println(Messages.ManagedWindowsServiceLauncher_WaitingForService());
SmbFile portFile = new SmbFile(remoteRoot, "port.txt");
for (int i = 0; !portFile.exists(); i++) {
if (i >= 30) {
listener.error(Messages.ManagedWindowsServiceLauncher_ServiceDidntRespond());
return;
}
Thread.sleep(1000);
}
int p = readSmbFile(portFile);
// connect
logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingToPort(p));
final Socket s = new Socket(name, p);
// ready
computer.setChannel(new BufferedInputStream(new SocketInputStream(s)), new BufferedOutputStream(new SocketOutputStream(s)), listener.getLogger(), new Listener() {
@Override
public void onClosed(Channel channel, IOException cause) {
afterDisconnect(computer, listener);
}
});
} catch (SmbException e) {
e.printStackTrace(listener.error(e.getMessage()));
} catch (JIException e) {
if (e.getErrorCode() == 5)
// access denied error
e.printStackTrace(listener.error(Messages.ManagedWindowsServiceLauncher_AccessDenied()));
else
e.printStackTrace(listener.error(e.getMessage()));
} catch (DocumentException e) {
e.printStackTrace(listener.error(e.getMessage()));
}
}
use of jcifs.smb.SmbException in project opennms by OpenNMS.
the class JCifsMonitor method poll.
/**
* This method queries the CIFS share.
*
* @param svc the monitored service
* @param parameters the parameter map
* @return the poll status for this system
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
final String domain = parameters.containsKey("domain") ? (String) parameters.get("domain") : "";
final String username = parameters.containsKey("username") ? (String) parameters.get("username") : "";
final String password = parameters.containsKey("password") ? (String) parameters.get("password") : "";
String mode = parameters.containsKey("mode") ? ((String) parameters.get("mode")).toUpperCase() : "PATH_EXIST";
String path = parameters.containsKey("path") ? (String) parameters.get("path") : "";
String smbHost = parameters.containsKey("smbHost") ? (String) parameters.get("smbHost") : "";
final String folderIgnoreFiles = parameters.containsKey("folderIgnoreFiles") ? (String) parameters.get("folderIgnoreFiles") : "";
// changing to Ip address of MonitoredService if no smbHost is given
if ("".equals(smbHost)) {
smbHost = svc.getIpAddr();
}
// Filename filter to give user the possibility to ignore specific files in folder for the folder check.
SmbFilenameFilter smbFilenameFilter = new SmbFilenameFilter() {
@Override
public boolean accept(SmbFile smbFile, String s) throws SmbException {
return !s.matches(folderIgnoreFiles);
}
};
// Initialize mode with default as PATH_EXIST
Mode enumMode = Mode.PATH_EXIST;
try {
enumMode = Mode.valueOf(mode);
} catch (IllegalArgumentException exception) {
logger.error("Mode '{}‘ does not exists. Valid candidates are {}", mode, modeCandidates);
return PollStatus.unknown("Mode " + mode + " does not exists. Valid candidates are " + modeCandidates);
}
// Checking path parameter
if (!path.startsWith("/")) {
path = "/" + path;
logger.debug("Added leading / to path.");
}
// Build authentication string for NtlmPasswordAuthentication: syntax: domain;username:password
String authString = "";
// Setting up authenticationString...
if (domain != null && !"".equals(domain)) {
authString += domain + ";";
}
authString += username + ":" + password;
// ... and path
String fullUrl = "smb://" + smbHost + path;
logger.debug("Domain: [{}], Username: [{}], Password: [{}], Mode: [{}], Path: [{}], Authentication: [{}], Full Url: [{}]", new Object[] { domain, username, password, mode, path, authString, fullUrl });
// Initializing TimeoutTracker with default values
TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
// Setting default PollStatus
PollStatus serviceStatus = PollStatus.unknown();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
NtlmPasswordAuthentication ntlmPasswordAuthentication = new NtlmPasswordAuthentication(authString);
try {
// Creating SmbFile object
SmbFile smbFile = new SmbFile(fullUrl, ntlmPasswordAuthentication);
// Setting the defined timeout
smbFile.setConnectTimeout(tracker.getConnectionTimeout());
// Does the file exists?
boolean smbFileExists = smbFile.exists();
switch(enumMode) {
case PATH_EXIST:
if (smbFileExists) {
serviceStatus = PollStatus.up();
} else {
serviceStatus = PollStatus.down("File " + fullUrl + " should exists but doesn't!");
}
break;
case PATH_NOT_EXIST:
if (!smbFileExists) {
serviceStatus = PollStatus.up();
} else {
serviceStatus = PollStatus.down("File " + fullUrl + " should not exists but does!");
}
break;
case FOLDER_EMPTY:
if (smbFileExists) {
if (smbFile.list(smbFilenameFilter).length == 0) {
serviceStatus = PollStatus.up();
} else {
serviceStatus = PollStatus.down("Directory " + fullUrl + " should be empty but isn't!");
}
} else {
serviceStatus = PollStatus.down("Directory " + fullUrl + " should exists but doesn't!");
}
break;
case FOLDER_NOT_EMPTY:
if (smbFileExists) {
if (smbFile.list(smbFilenameFilter).length > 0) {
serviceStatus = PollStatus.up();
} else {
serviceStatus = PollStatus.down("Directory " + fullUrl + " should not be empty but is!");
}
} else {
serviceStatus = PollStatus.down("Directory " + fullUrl + " should exists but doesn't!");
}
break;
default:
logger.warn("There is no implementation for the specified mode '{}'", mode);
break;
}
} catch (MalformedURLException exception) {
logger.error("Malformed URL on '{}' with error: '{}'", smbHost, exception.getMessage());
serviceStatus = PollStatus.down(exception.getMessage());
} catch (SmbException exception) {
logger.error("SMB error on '{}' with error: '{}'", smbHost, exception.getMessage());
serviceStatus = PollStatus.down(exception.getMessage());
}
}
return serviceStatus;
}
use of jcifs.smb.SmbException in project android-toolbox by Knickedi.
the class SmbUtils method listAvailableHosts.
/**
* Get list with available hosts from samba network.<br>
* <br>
* This method is time critical because it will contact the network. You could do that once and
* cache result. Do that on another thread. Be aware of the fact a network request could fail
* and give an empty or incomplete list although host should be available.<br>
* <br>
* <b>Note</b>: Don't forget to request for Internet permission in manifest!
*
* @param withIp
* {@code true} when IP of host should be listed too (does it anyway when found host
* is not a name but an IP)
*
* @return list with all available (found) hosts
*/
public static String[] listAvailableHosts(boolean withIp) {
List<String> hostNames = new ArrayList<String>();
try {
SmbFile[] workgroups = new SmbFile("smb://").listFiles();
for (int i = 0; i < workgroups.length; i++) {
try {
SmbFile[] hosts = workgroups[i].listFiles();
// check hosts in workgroup
for (int j = 0; j < hosts.length; j++) {
String name = hosts[j].getName();
String nameWithoutSlash = name.substring(0, name.length() - 1);
hostNames.add(nameWithoutSlash);
if (withIp && !IP_PATTERN.matcher(nameWithoutSlash).matches()) {
try {
hostNames.add(InetAddress.getByName(nameWithoutSlash).getHostAddress());
} catch (UnknownHostException e) {
// could not resolve IP - skip it
}
}
}
} catch (SmbException e) {
// can't retrieve list of host from workgroup - skip it
}
}
} catch (SmbException e) {
// smb:// should be valid - just skip on error
} catch (MalformedURLException e) {
// should never happen - smb:// is valid
throw new RuntimeException(e);
}
String[] hosts = hostNames.toArray(new String[0]);
return hosts;
}
Aggregations