Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring to reduce code smells #399

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/net/azib/ipscan/core/ScannerDispatcherThread.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public void run() {

try {
ScanningSubject subject = null;
while(feeder.hasNext() && stateMachine.inState(SCANNING)) {
while(feeder.hasNext() && stateMachine.inCurrentState(SCANNING)) {
// make a small delay between thread creation
Thread.sleep(config.threadDelay);

Expand Down
8 changes: 8 additions & 0 deletions src/net/azib/ipscan/core/ScanningResultList.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ public ScanningResultList(FetcherRegistry fetcherRegistry, StateMachine stateMac
stateMachine.addTransitionListener(new StopScanningListener());
}

public void updateResult(int index, String fetcherId, Object newValue, ScanningResultList scanningResults) {
int fetcherIndex = scanningResults.getFetcherIndex(fetcherId);
if (fetcherIndex >= 0) {
// update the value in the results
scanningResults.getResult(index).setValue(fetcherIndex, newValue);
}
}

/**
* @return selected fetchers that were used for the last scan
* Note: they may be different from {@link FetcherRegistry#getSelectedFetchers()}
Expand Down
10 changes: 7 additions & 3 deletions src/net/azib/ipscan/core/net/WindowsPinger.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,13 @@ private PingResult ping4(ScanningSubject subject, int count) throws IOException
for (int i = 1; i <= count && !currentThread().isInterrupted(); i++) {
int numReplies = dll.IcmpSendEcho(handle, ipaddr, sendData, (short) sendDataSize, null, replyData, replyDataSize, timeout);
IcmpEchoReply echoReply = new IcmpEchoReply(replyData);
if (numReplies > 0 && echoReply.status == 0 && Arrays.equals(echoReply.address.bytes, ipaddr.bytes)) {
result.addReply(echoReply.roundTripTime);
result.setTTL(echoReply.options.ttl & 0xFF);
if (numReplies > 0) {
if (echoReply.status == 0) {
if (Arrays.equals(echoReply.address.bytes, ipaddr.bytes)) {
result.addReply(echoReply.roundTripTime);
result.setTTL(echoReply.options.ttl & 0xFF);
}
}
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/net/azib/ipscan/core/state/StateMachine.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ public enum Transition {INIT, START, STOP, NEXT, COMPLETE, RESET, RESCAN, CONTIN
/**
* @return true if current state is as specified
*/
public boolean inState(ScanningState state) {
public boolean inCurrentState(ScanningState state) {
return this.state == state;
}

/**
* @return current state
*/
public ScanningState getState() {
public ScanningState getCurrentState() {
return state;
}

Expand Down
6 changes: 3 additions & 3 deletions src/net/azib/ipscan/exporters/TXTExporter.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ public void nextAddressResults(Object[] results) throws IOException {
* @param length the total returned length, minimum is 13
*/
String pad(Object o, int length) {
if (length < 16)
length = 16;

int minLength = 16;
if (length < minLength)
length = minLength;
String s;
if (o == null)
s = "";
Expand Down
8 changes: 1 addition & 7 deletions src/net/azib/ipscan/gui/ResultTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,7 @@ public void updateResults() {
* @param newValue
*/
public void updateResult(int index, String fetcherId, Object newValue) {
int fetcherIndex = scanningResults.getFetcherIndex(fetcherId);
if (fetcherIndex >= 0) {
// update the value in the results
scanningResults.getResult(index).setValue(fetcherIndex, newValue);
// update visual representation
clear(index);
}
scanningResults.updateResult(index, fetcherId, newValue, scanningResults);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/net/azib/ipscan/gui/actions/ColumnsActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ public void handleEvent(Event e) {
sortMenuItem.setText(Labels.getLabel("menu.columns.sortBy") + " " + fetcher.getName());

// disable these menu items if scanning
sortMenuItem.setEnabled(stateMachine.inState(ScanningState.IDLE));
sortMenuItem.setEnabled(stateMachine.inCurrentState(ScanningState.IDLE));

preferencesMenuItem.setText(fetcher.getName() + " " + Labels.getLabel("menu.columns.preferences"));
preferencesMenuItem.setEnabled(fetcher.getPreferencesClass() != null && stateMachine.inState(ScanningState.IDLE));
preferencesMenuItem.setEnabled(fetcher.getPreferencesClass() != null && stateMachine.inCurrentState(ScanningState.IDLE));

aboutMenuItem.setText(Labels.getLabel("menu.columns.about") + " " + fetcher.getName());

Expand Down
2 changes: 1 addition & 1 deletion src/net/azib/ipscan/gui/actions/CommandsMenuActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public void handleEvent(Event event) {
// the same listener is used for several events
if (event.type == SWT.KeyDown && event.keyCode != SWT.DEL) return;
// deletion not allowed when scanning
if (!stateMachine.inState(ScanningState.IDLE)) return;
if (!stateMachine.inCurrentState(ScanningState.IDLE)) return;

int firstSelection = resultTable.getSelectionIndex();
if (firstSelection < 0) return;
Expand Down
2 changes: 1 addition & 1 deletion src/net/azib/ipscan/gui/actions/FavoritesMenuActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public void handleEvent(Event event) {
for (String name : favoritesConfig) {
MenuItem menuItem = new MenuItem(favoritesMenu, SWT.CASCADE);
menuItem.setText(name);
menuItem.setEnabled(stateMachine.inState(ScanningState.IDLE));
menuItem.setEnabled(stateMachine.inCurrentState(ScanningState.IDLE));
menuItem.addSelectionListener(favoritesSelectListener);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/net/azib/ipscan/gui/actions/ScanMenuActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public void handleEvent(Event event) {
throw new UserErrorException("commands.noResults");
}

if (!stateMachine.inState(ScanningState.IDLE)) {
if (!stateMachine.inCurrentState(ScanningState.IDLE)) {
// ask the user whether to save incomplete results
MessageBox box = new MessageBox(resultTable.getShell(), SWT.YES | SWT.NO | SWT.ICON_WARNING | SWT.SHEET);
box.setText(Version.NAME);
Expand Down
15 changes: 9 additions & 6 deletions src/net/azib/ipscan/gui/actions/StartStopScanningAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import net.azib.ipscan.core.state.StateTransitionListener;
import net.azib.ipscan.gui.ResultTable;
import net.azib.ipscan.gui.StatusBar;
import net.azib.ipscan.gui.feeders.AbstractFeederGUI;
import net.azib.ipscan.gui.feeders.FeederGUIRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
Expand Down Expand Up @@ -48,6 +49,7 @@ public class StartStopScanningAction implements SelectionListener, ScanningProgr
private ResultTable resultTable;
private FeederGUIRegistry feederRegistry;
private Button button;
private AbstractFeederGUI abstractFeederGUI;

Image[] buttonImages = new Image[ScanningState.values().length];
String[] buttonTexts = new String[ScanningState.values().length];
Expand Down Expand Up @@ -80,7 +82,7 @@ public class StartStopScanningAction implements SelectionListener, ScanningProgr

public StartStopScanningAction(ScannerDispatcherThreadFactory scannerThreadFactory, StateMachine stateMachine, ResultTable resultTable,
StatusBar statusBar, FeederGUIRegistry feederRegistry, PingerRegistry pingerRegistry,
Button startStopButton, GUIConfig guiConfig) {
Button startStopButton, GUIConfig guiConfig, AbstractFeederGUI abstractFeederGUI) {
this(startStopButton.getDisplay());

this.scannerThreadFactory = scannerThreadFactory;
Expand All @@ -92,12 +94,13 @@ public StartStopScanningAction(ScannerDispatcherThreadFactory scannerThreadFacto
this.stateMachine = stateMachine;
this.guiConfig = guiConfig;
this.taskBarItem = getTaskBarItem();
this.abstractFeederGUI = abstractFeederGUI;

// add listeners to all state changes
stateMachine.addTransitionListener(this);

// set the default image
ScanningState state = stateMachine.getState();
ScanningState state = stateMachine.getCurrentState();
button.setImage(buttonImages[state.ordinal()]);
button.setText(buttonTexts[state.ordinal()]);
}
Expand All @@ -124,7 +127,7 @@ public void widgetDefaultSelected(SelectionEvent e) {
*/
public void widgetSelected(SelectionEvent event) {
// ask for confirmation before erasing scanning results
if (stateMachine.inState(IDLE)) {
if (stateMachine.inCurrentState(IDLE)) {
if (!preScanChecks())
return;
}
Expand Down Expand Up @@ -160,7 +163,7 @@ public void transitionTo(final ScanningState state, final Transition transition)
resultTable.removeAll();

try {
scannerThread = scannerThreadFactory.createScannerThread(feederRegistry.createFeeder(), StartStopScanningAction.this, createResultsCallback(state));
scannerThread = scannerThreadFactory.createScannerThread(abstractFeederGUI.createFeeder(), StartStopScanningAction.this, createResultsCallback(state));
stateMachine.startScanning();
mainWindowTitle = statusBar.getShell().getText();
}
Expand Down Expand Up @@ -249,13 +252,13 @@ public void updateProgress(final InetAddress currentAddress, final int runningTh
if (taskBarItem != null) taskBarItem.setProgress(percentageComplete);

// show percentage in main window title
if (!stateMachine.inState(IDLE))
if (!stateMachine.inCurrentState(IDLE))
statusBar.getShell().setText(percentageComplete + "% - " + mainWindowTitle);
else
statusBar.getShell().setText(mainWindowTitle);

// change button image according to the current state
button.setImage(buttonImages[stateMachine.getState().ordinal()]);
button.setImage(buttonImages[stateMachine.getCurrentState().ordinal()]);
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/net/azib/ipscan/gui/actions/ToolsActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public TableSelection(StatusBar statusBar, StateMachine stateMachine) {
}

public void handleEvent(Event event) {
if (stateMachine.inState(ScanningState.IDLE)) {
if (stateMachine.inCurrentState(ScanningState.IDLE)) {
Table resultTable = (Table) event.widget;
int selectionCount = resultTable.getSelectionCount();
if (selectionCount > 1)
Expand Down
4 changes: 4 additions & 0 deletions src/net/azib/ipscan/gui/feeders/AbstractFeederGUI.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ protected void asyncFillLocalHostInfo(final Text hostnameText, final Text ipText
}).start();
}

public Feeder createFeeder() {
return createFeeder();
}

protected void afterLocalHostInfoFilled(InterfaceAddress localInterface) {
}
}
8 changes: 0 additions & 8 deletions src/net/azib/ipscan/gui/feeders/FeederGUIRegistry.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,6 @@ public void select(String feederId) {
throw new FeederException("Feeder not found: " + feederId);
}

/**
* @return new Feeder initialized using the currently selected Feeder GUI
*/
public Feeder createFeeder() {
lastFeeder = current().createFeeder();
return lastFeeder;
}

/**
* @param selection selected table items to derive IP addresses from
* @return initialized instance of RescanFeeder
Expand Down
71 changes: 71 additions & 0 deletions src/net/azib/ipscan/util/NetBIOSName.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package net.azib.ipscan.util;

import java.net.SocketException;

public class NetBIOSName {
private String computerName;
private String userName;
private String groupName;
private String macAddress;

private static final int RESPONSE_BASE_LEN = 57;
private static final int RESPONSE_NAME_LEN = 15;
private static final int RESPONSE_NAME_BLOCK_LEN = 18;

private static final int GROUP_NAME_FLAG = 128;
private static final int NAME_TYPE_DOMAIN = 0x00;
private static final int NAME_TYPE_MESSENGER = 0x03;

public NetBIOSName(String computerName, String userName, String groupName, String macAddress) throws SocketException {
this.computerName = computerName;
this.userName = userName;
this.groupName = groupName;
this.macAddress = macAddress;
}

static String[] extractNames(byte[] response, int nameCount) {
String computerName = nameCount > 0 ? name(response, 0) : null;

String groupName = null;
for (int i = 1; i < nameCount; i++) {
if (nameType(response, i) == NAME_TYPE_DOMAIN && (nameFlag(response, i) & GROUP_NAME_FLAG) > 0) {
groupName = name(response, i);
break;
}
}

String userName = null;
for (int i = nameCount - 1; i > 0; i--) {
if (nameType(response, i) == NAME_TYPE_MESSENGER) {
userName = name(response, i);
break;
}
}

String macAddress = String.format("%02X-%02X-%02X-%02X-%02X-%02X",
nameByte(response, nameCount, 0), nameByte(response, nameCount, 1),
nameByte(response, nameCount, 2), nameByte(response, nameCount, 3),
nameByte(response, nameCount, 4), nameByte(response, nameCount, 5));

return new String[] {computerName, userName, groupName, macAddress};
}

private static String name(byte[] response, int i) {
// as we have no idea in which encoding are the received names,
// assume that local default encoding matches the remote one (they are on the same LAN most probably)
return new String(response, RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i, RESPONSE_NAME_LEN).trim();
}

private static int nameByte(byte[] response, int i, int n) {
return response[RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i + n] & 0xFF;
}

private static int nameFlag(byte[] response, int i) {
return response[RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i + RESPONSE_NAME_LEN + 1] & 0xFF +
(response[RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i + RESPONSE_NAME_LEN + 2] & 0xFF) * 0xFF;
}

private static int nameType(byte[] response, int i) {
return response[RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i + RESPONSE_NAME_LEN] & 0xFF;
}
}
58 changes: 4 additions & 54 deletions src/net/azib/ipscan/util/NetBIOSResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,13 @@ public class NetBIOSResolver implements Closeable {
private static final int RESPONSE_TYPE_POS = 47;
private static final byte RESPONSE_TYPE_NBSTAT = 33;
private static final int RESPONSE_BASE_LEN = 57;
private static final int RESPONSE_NAME_LEN = 15;
private static final int RESPONSE_NAME_BLOCK_LEN = 18;

private static final int GROUP_NAME_FLAG = 128;
private static final int NAME_TYPE_DOMAIN = 0x00;
private static final int NAME_TYPE_MESSENGER = 0x03;

DatagramSocket socket = new DatagramSocket();
private DatagramSocket socket;

public NetBIOSResolver(int timeout) throws SocketException {
socket.setSoTimeout(timeout);
this.socket = new DatagramSocket();
this.socket.setSoTimeout(timeout);
}

public String[] resolve(InetAddress ip) throws IOException {
Expand All @@ -43,53 +39,7 @@ public String[] resolve(InetAddress ip) throws IOException {
return null; // data was truncated or something is wrong
}

return extractNames(response, nameCount);
}

static String[] extractNames(byte[] response, int nameCount) {
String computerName = nameCount > 0 ? name(response, 0) : null;

String groupName = null;
for (int i = 1; i < nameCount; i++) {
if (nameType(response, i) == NAME_TYPE_DOMAIN && (nameFlag(response, i) & GROUP_NAME_FLAG) > 0) {
groupName = name(response, i);
break;
}
}

String userName = null;
for (int i = nameCount - 1; i > 0; i--) {
if (nameType(response, i) == NAME_TYPE_MESSENGER) {
userName = name(response, i);
break;
}
}

String macAddress = String.format("%02X-%02X-%02X-%02X-%02X-%02X",
nameByte(response, nameCount, 0), nameByte(response, nameCount, 1),
nameByte(response, nameCount, 2), nameByte(response, nameCount, 3),
nameByte(response, nameCount, 4), nameByte(response, nameCount, 5));

return new String[] {computerName, userName, groupName, macAddress};
}

private static String name(byte[] response, int i) {
// as we have no idea in which encoding are the received names,
// assume that local default encoding matches the remote one (they are on the same LAN most probably)
return new String(response, RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i, RESPONSE_NAME_LEN).trim();
}

private static int nameByte(byte[] response, int i, int n) {
return response[RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i + n] & 0xFF;
}

private static int nameFlag(byte[] response, int i) {
return response[RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i + RESPONSE_NAME_LEN + 1] & 0xFF +
(response[RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i + RESPONSE_NAME_LEN + 2] & 0xFF) * 0xFF;
}

private static int nameType(byte[] response, int i) {
return response[RESPONSE_BASE_LEN + RESPONSE_NAME_BLOCK_LEN * i + RESPONSE_NAME_LEN] & 0xFF;
return NetBIOSName.extractNames(response, nameCount);
}

public void close() {
Expand Down
Loading