rem
stringlengths
0
477k
add
stringlengths
0
313k
context
stringlengths
6
599k
okButton.setEnabled(true); return;
return Boolean.FALSE;
public void actionPerformed(ActionEvent e) { // // OK button event handler // // disable the OK button while we are in the // working thread (i.e. prohibit re-entrance) okButton.setEnabled(false); // since we are performing a validation // that could take some time we need to warn the user about it. // However updating the gui while the task is progressing, // requires us to run the validation in a new thread that will // give the chance of the swing thread to update the GUI new Thread("Preferences saver/validator") { public void run() { // validate the user input and check the result boolean succes = validateSettings(); if (!succes) { okButton.setEnabled(true); return; } // Save settings saveSettings(); if (needsRestart()) { handleRestartRequest(); } close(); } // end run }.start(); // start the working thread }
close();
return Boolean.TRUE; }
public void actionPerformed(ActionEvent e) { // // OK button event handler // // disable the OK button while we are in the // working thread (i.e. prohibit re-entrance) okButton.setEnabled(false); // since we are performing a validation // that could take some time we need to warn the user about it. // However updating the gui while the task is progressing, // requires us to run the validation in a new thread that will // give the chance of the swing thread to update the GUI new Thread("Preferences saver/validator") { public void run() { // validate the user input and check the result boolean succes = validateSettings(); if (!succes) { okButton.setEnabled(true); return; } // Save settings saveSettings(); if (needsRestart()) { handleRestartRequest(); } close(); } // end run }.start(); // start the working thread }
} }.start();
@Override public void finished() { if (get() == Boolean.TRUE) { setVisible(false); } okButton.setEnabled(true); } }; worker.start();
public void actionPerformed(ActionEvent e) { // // OK button event handler // // disable the OK button while we are in the // working thread (i.e. prohibit re-entrance) okButton.setEnabled(false); // since we are performing a validation // that could take some time we need to warn the user about it. // However updating the gui while the task is progressing, // requires us to run the validation in a new thread that will // give the chance of the swing thread to update the GUI new Thread("Preferences saver/validator") { public void run() { // validate the user input and check the result boolean succes = validateSettings(); if (!succes) { okButton.setEnabled(true); return; } // Save settings saveSettings(); if (needsRestart()) { handleRestartRequest(); } close(); } // end run }.start(); // start the working thread }
if (!StringUtils.isBlank((String) mydnsndsModel.getValue())) { dynDnsSettingsTab = new DynDnsSettingsTab(getController(), mydnsndsModel); showDynDNSTab(true); }
showDynDNSTab(!StringUtils.isBlank((String) mydnsndsModel.getValue()));
public void initComponents() { mydnsndsModel = new ValueHolder(ConfigurationEntry.DYNDNS_HOSTNAME .getValue(getController())); mydnsndsModel.addValueChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { String dyndns = (String) evt.getNewValue(); // show tab when dyndns host is set showDynDNSTab(!StringUtils.isBlank(dyndns)); } }); tabbedPane = new JTabbedPane(JTabbedPane.LEFT); GeneralSettingsTab generalSettingsTab = new GeneralSettingsTab( getController()); preferenceTabs.add(generalSettingsTab); tabbedPane.addTab(" " + generalSettingsTab.getTabName() + " ", null, generalSettingsTab.getUIPanel(), null); NetworkSettingsTab networkSettingsTab = new NetworkSettingsTab( getController(), mydnsndsModel); preferenceTabs.add(networkSettingsTab); tabbedPane.addTab(networkSettingsTab.getTabName(), null, networkSettingsTab.getUIPanel(), null); DialogsSettingsTab dialogsSettingsTab = new DialogsSettingsTab( getController()); preferenceTabs.add(dialogsSettingsTab); tabbedPane.addTab(dialogsSettingsTab.getTabName(), null, dialogsSettingsTab.getUIPanel(), null); PluginSettingsTab pluginSettingsTab = new PluginSettingsTab( getController(), this); if (getController().getPluginManager().countPlugins() > 0) { preferenceTabs.add(pluginSettingsTab); tabbedPane.addTab(pluginSettingsTab.getTabName(), null, pluginSettingsTab.getUIPanel(), null); } if (!StringUtils.isBlank((String) mydnsndsModel.getValue())) { dynDnsSettingsTab = new DynDnsSettingsTab(getController(), mydnsndsModel); showDynDNSTab(true); } advangedSettingsTab = new AdvancedSettingsTab(getController()); if ("true".equals(getController().getConfig().get( GeneralSettingsTab.SHOWADVANGEDSETTINGS))) { preferenceTabs.add(advangedSettingsTab); tabbedPane.addTab(advangedSettingsTab.getTabName(), null, advangedSettingsTab.getUIPanel(), null); } // Behavior for advanced settings panel generalSettingsTab.getShowAdvancedSettingsModel() .addValueChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { showAdvangedTab(Boolean.TRUE.equals(evt.getNewValue())); } }); showAdvangedTab(Boolean.TRUE.equals(generalSettingsTab .getShowAdvancedSettingsModel().getValue())); tabbedPane.setSelectedIndex(0); tabbedPane.setBorder(Borders.createEmptyBorder("3dlu,0,0,3dlu")); // Buttons okButton = createOKButton(); cancelButton = createCancelButton(); }
if (enable && dynDnsSettingsTab != null || !enable && dynDnsSettingsTab == null) return; if (enable) dynDnsSettingsTab = new DynDnsSettingsTab(getController(), mydnsndsModel); else dynDnsSettingsTab = null;
boolean wasShown = dynDnsSettingsTab != null; System.err.println("showing dyndns tab: " + enable); if (dynDnsSettingsTab == null) { dynDnsSettingsTab = new DynDnsSettingsTab(getController(), mydnsndsModel); }
void showDynDNSTab(boolean enable) { // Don't add or remove it twice if (enable && dynDnsSettingsTab != null || !enable && dynDnsSettingsTab == null) return; if (enable) dynDnsSettingsTab = new DynDnsSettingsTab(getController(), mydnsndsModel); else dynDnsSettingsTab = null; showTab(enable, dynDnsSettingsTab, DYNDNS_TAB_INDEX); }
preferenceTabs.add(tab);
if (!preferenceTabs.contains(tab)) { preferenceTabs.add(tab); }
private void showTab(boolean enable, PreferenceTab tab, int tabindex) { if (enable) { preferenceTabs.add(tab); //calculate a valid insert index before inserting int currentNumberOfTabs = tabbedPane.getTabCount(); int newTabindex = Math.min(tabindex, currentNumberOfTabs); tabbedPane.insertTab(tab.getTabName(), null, tab.getUIPanel(), null, newTabindex); } else { preferenceTabs.remove(tab); tabbedPane.remove(tab.getUIPanel()); } rePack(); }
System.err.println("preferenceTabs: " + preferenceTabs);
private void showTab(boolean enable, PreferenceTab tab, int tabindex) { if (enable) { preferenceTabs.add(tab); //calculate a valid insert index before inserting int currentNumberOfTabs = tabbedPane.getTabCount(); int newTabindex = Math.min(tabindex, currentNumberOfTabs); tabbedPane.insertTab(tab.getTabName(), null, tab.getUIPanel(), null, newTabindex); } else { preferenceTabs.remove(tab); tabbedPane.remove(tab.getUIPanel()); } rePack(); }
log().debug("storeFolderDB " + getFiles().length);
log().debug("storeFolderDB. " + getFiles().length + " Files in db");
private void storeFolderDB() { if (logVerbose) { log().debug("storeFolderDB " + getFiles().length); } if (!shutdown) { if (!getController().isStarted()) { // Not storing return; } } synchronized (scanLock) { File dbFile = new File(getSystemSubDir(), DB_FILENAME); File dbFileBackup = new File(getSystemSubDir(), DB_BACKUP_FILENAME); try { FileInfo[] files = getFiles(); if (dbFile.exists()) { dbFile.delete(); } dbFile.createNewFile(); OutputStream fOut = new BufferedOutputStream( new FileOutputStream(dbFile)); ObjectOutputStream oOut = new ObjectOutputStream(fOut); // Store files oOut.writeObject(files); // Store members oOut.writeObject(Convert.asMemberInfos(getMembers())); // Store blacklist if (blacklist != null) { List<FileInfo> ignored = blacklist.getExplicitIgnored(); if (logEnabled) { log().verbose("write blacklist: " + ignored.size()); } oOut.writeObject(ignored); } oOut.close(); fOut.close(); log().debug("Successfully wrote folder database file"); // Make backup FileUtils.copyFile(dbFile, dbFileBackup); // TODO Remove this in later version // Cleanup for older versions File oldDbFile = new File(localBase, DB_FILENAME); oldDbFile.delete(); File oldDbFileBackup = new File(localBase, DB_BACKUP_FILENAME); oldDbFileBackup.delete(); } catch (IOException e) { // TODO: if something failed shoudn't we try to restore the // backup (if backup exists and bd file not after this? log().error( this + ": Unable to write database file " + dbFile.getAbsolutePath(), e); log().verbose(e); } } }
MessageBundleManager.registerCoreMessageBundle();
public Object run(Object args) throws Exception { FIXDataDictionaryManager.setFIXVersion(FIXDataDictionaryManager.FIX_4_2_BEGIN_STRING); fixMessageHistory = new FIXMessageHistory(); jmsConnector = new JMSConnector(); orderManager = new OrderManager(idFactory, fixMessageHistory); Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) { return IPlatformRunnable.EXIT_RESTART; } return IPlatformRunnable.EXIT_OK; } finally { display.dispose(); } }
if (getController().getPreferences().getBoolean(GeneralSettingsTab.SHOWADVANCEDSETTINGS, false))
if (PreferencesEntry.SHOWADVANCEDSETTINGS.getValueBoolean(getController()))
public void initComponents() { mydnsndsModel = new ValueHolder(ConfigurationEntry.DYNDNS_HOSTNAME .getValue(getController())); mydnsndsModel.addValueChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { String dyndns = (String) evt.getNewValue(); // show tab when dyndns host is set showDynDNSTab(!StringUtils.isBlank(dyndns)); } }); tabbedPane = new JTabbedPane(JTabbedPane.LEFT); GeneralSettingsTab generalSettingsTab = new GeneralSettingsTab( getController()); preferenceTabs.add(generalSettingsTab); tabbedPane.addTab(" " + generalSettingsTab.getTabName() + " ", null, generalSettingsTab.getUIPanel(), null); NetworkSettingsTab networkSettingsTab = new NetworkSettingsTab( getController(), mydnsndsModel); preferenceTabs.add(networkSettingsTab); tabbedPane.addTab(networkSettingsTab.getTabName(), null, networkSettingsTab.getUIPanel(), null); DialogsSettingsTab dialogsSettingsTab = new DialogsSettingsTab( getController()); preferenceTabs.add(dialogsSettingsTab); tabbedPane.addTab(dialogsSettingsTab.getTabName(), null, dialogsSettingsTab.getUIPanel(), null); PluginSettingsTab pluginSettingsTab = new PluginSettingsTab( getController(), this); if (getController().getPluginManager().countPlugins() > 0) { preferenceTabs.add(pluginSettingsTab); tabbedPane.addTab(pluginSettingsTab.getTabName(), null, pluginSettingsTab.getUIPanel(), null); } showDynDNSTab(!StringUtils.isBlank((String) mydnsndsModel.getValue())); advancedSettingsTab = new AdvancedSettingsTab(getController()); if (getController().getPreferences().getBoolean(GeneralSettingsTab.SHOWADVANCEDSETTINGS, false)) { preferenceTabs.add(advancedSettingsTab); tabbedPane.addTab(advancedSettingsTab.getTabName(), null, advancedSettingsTab.getUIPanel(), null); } // Behavior for advanced settings panel generalSettingsTab.getShowAdvancedSettingsModel() .addValueChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { showAdvancedTab(Boolean.TRUE.equals(evt.getNewValue())); } }); showAdvancedTab(Boolean.TRUE.equals(generalSettingsTab .getShowAdvancedSettingsModel().getValue())); tabbedPane.setSelectedIndex(0); tabbedPane.setBorder(Borders.createEmptyBorder("3dlu,0,0,3dlu")); // Buttons okButton = createOKButton(); cancelButton = createCancelButton(); }
File detailLogsDir = new File(debugDir, "detaillogs"); System.out.println("detailLogsDir: " + detailLogsDir.getAbsolutePath());
File detailLogsDir = new File(debugDir, "detaillogs");
public static final void setLogFile(String logFilename) { File debugDir = getDebugDir(); File detailLogsDir = new File(debugDir, "detaillogs"); System.out.println("detailLogsDir: " + detailLogsDir.getAbsolutePath()); debugDir.mkdir(); detailLogsDir.mkdirs(); logFile = new File(debugDir, logFilename); System.out.println("logFile: " + logFile.getAbsolutePath()); try { if (logFile.exists()) { logFile.delete(); } logFile.createNewFile(); } catch (IOException e) { System.err.println("Unable to create logfile '" + logFile.getAbsolutePath() + "'"); e.printStackTrace(); logFile = null; } }
System.out.println("logFile: " + logFile.getAbsolutePath());
public static final void setLogFile(String logFilename) { File debugDir = getDebugDir(); File detailLogsDir = new File(debugDir, "detaillogs"); System.out.println("detailLogsDir: " + detailLogsDir.getAbsolutePath()); debugDir.mkdir(); detailLogsDir.mkdirs(); logFile = new File(debugDir, logFilename); System.out.println("logFile: " + logFile.getAbsolutePath()); try { if (logFile.exists()) { logFile.delete(); } logFile.createNewFile(); } catch (IOException e) { System.err.println("Unable to create logfile '" + logFile.getAbsolutePath() + "'"); e.printStackTrace(); logFile = null; } }
log().warn("Initalizing plugins: " + pluginsStr);
log().info("Initalizing plugins: " + pluginsStr);
private void initializePlugins() { String pluginsStr = ConfigurationEntry.PLUGINS .getValue(getController()); if (StringUtils.isBlank(pluginsStr)) { return; } log().warn("Initalizing plugins: " + pluginsStr); StringTokenizer nizer = new StringTokenizer(pluginsStr, ","); while (nizer.hasMoreElements()) { String pluginClassName = nizer.nextToken(); Plugin plugin = initalizePlugin(pluginClassName); if (plugin != null) { plugin.start(); log().info("Started plugin: " + plugin.getName()); plugins.add(plugin); } } }
WorkbenchAdapterBuilder.registerAdapters();
public void initialize(IWorkbenchConfigurer configurer) { configurer.setSaveAndRestore(true); ConsolePlugin.getDefault().getConsoleManager().addConsoles( new IConsole[] { new MainConsole() }); }
.error( getController().getMySelf().getNick() + " rare size change (modification date the same?!): from "
.error("rare size change (modification date the same?!): from "
private final boolean scanFile(File fileToScan, String currentDirName) { if (!fileToScan.exists()) { // hardware no longer available return false; } // this is a incomplete fileinfo just find one fast in the remaining // list // log().verbose( // "scanFile: " + fileToScan + " curdirname: " + currentDirName); totalFilesCount++; String filename; if (currentDirName.length() == 0) { filename = fileToScan.getName(); } else { filename = currentDirName + "/" + fileToScan.getName(); } FileInfo fInfo = new FileInfo(currentScanningFolder.getInfo(), filename); FileInfo exists; synchronized (remaining) { exists = remaining.remove(fInfo); } if (exists != null) {// file was known if (exists.isDeleted()) { // file restored synchronized (restoredFiles) { restoredFiles.add(exists); } } else { boolean changed = false; long modification = fileToScan.lastModified(); if (exists.getModifiedDate().getTime() < modification) { // disk file = newer changed = true; } long size = fileToScan.length(); if (exists.getSize() != size) { // size changed log() .error( getController().getMySelf().getNick() + " rare size change (modification date the same?!): from " + exists.getSize() + " to: " + size); changed = true; } if (changed) { synchronized (changedFiles) { changedFiles.add(exists); } } } } else {// file is new if (logEnabled) { log().verbose( "NEW file found: " + fInfo.getName() + " hash: " + fInfo.hashCode()); } FileInfo info = new FileInfo(currentScanningFolder, fileToScan); info.setFolder(currentScanningFolder); info.setSize(fileToScan.length()); info.setModifiedInfo(getController().getMySelf().getInfo(), new Date(fileToScan.lastModified())); synchronized (newFiles) { newFiles.add(info); } } return true; }
getController().getMySelf().getNick() + " scan folder: "
"scan folder: "
public ScanResult scanFolder(Folder folder) { Reject.ifNull(folder, "folder cannot be null"); if (currentScanningFolder != null) { throw new IllegalStateException( "Not allowed to start another scan while scanning is in process"); } if (logEnabled) { log().info( getController().getMySelf().getNick() + " scan folder: " + folder.getName() + " start"); } long started = System.currentTimeMillis(); currentScanningFolder = folder; File base = currentScanningFolder.getLocalBase(); remaining = currentScanningFolder.getKnownFiles(); if (!scan(base) || failure) { // if false there was an IOError reset(); ScanResult result = new ScanResult(); result.setResultState(ScanResult.ResultState.HARDWARE_FAILURE); return result; } if (abort) { reset(); ScanResult result = new ScanResult(); result.setResultState(ScanResult.ResultState.USER_ABORT); return result; } List<FileInfo> moved = tryFindMovements(remaining, newFiles); Map<FileInfo, List<String>> problemFiles = tryFindProblems(newFiles); ScanResult result = new ScanResult(); result.setChangedFiles(changedFiles); result.setNewFiles(newFiles); result.setDeletedFiles(new ArrayList<FileInfo>(remaining.keySet())); result.setMovedFiles(moved); result.setProblemFiles(problemFiles); result.setRestoredFiles(restoredFiles); result.setTotalFilesCount(totalFilesCount); result.setResultState(ScanResult.ResultState.SCANNED); reset(); if (logEnabled) { log().info( getController().getMySelf().getNick() + " scan folder " + folder.getName() + " done in " + (System.currentTimeMillis() - started)); } return result; }
log().info( getController().getMySelf().getNick() + " scan folder "
log().info("scan folder "
public ScanResult scanFolder(Folder folder) { Reject.ifNull(folder, "folder cannot be null"); if (currentScanningFolder != null) { throw new IllegalStateException( "Not allowed to start another scan while scanning is in process"); } if (logEnabled) { log().info( getController().getMySelf().getNick() + " scan folder: " + folder.getName() + " start"); } long started = System.currentTimeMillis(); currentScanningFolder = folder; File base = currentScanningFolder.getLocalBase(); remaining = currentScanningFolder.getKnownFiles(); if (!scan(base) || failure) { // if false there was an IOError reset(); ScanResult result = new ScanResult(); result.setResultState(ScanResult.ResultState.HARDWARE_FAILURE); return result; } if (abort) { reset(); ScanResult result = new ScanResult(); result.setResultState(ScanResult.ResultState.USER_ABORT); return result; } List<FileInfo> moved = tryFindMovements(remaining, newFiles); Map<FileInfo, List<String>> problemFiles = tryFindProblems(newFiles); ScanResult result = new ScanResult(); result.setChangedFiles(changedFiles); result.setNewFiles(newFiles); result.setDeletedFiles(new ArrayList<FileInfo>(remaining.keySet())); result.setMovedFiles(moved); result.setProblemFiles(problemFiles); result.setRestoredFiles(restoredFiles); result.setTotalFilesCount(totalFilesCount); result.setResultState(ScanResult.ResultState.SCANNED); reset(); if (logEnabled) { log().info( getController().getMySelf().getNick() + " scan folder " + folder.getName() + " done in " + (System.currentTimeMillis() - started)); } return result; }
declareIdeWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT, PATH_OBJECT + "prj_obj.gif", true); declareIdeWorkbenchImage(ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT + "cprj_obj.gif", true);
private void declareIdeWorkbenchImages() { final String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$ final String PATH_ETOOL = ICONS_PATH + "etool16/"; // Enabled toolbar icons.//$NON-NLS-1$ final String PATH_OBJECT = ICONS_PATH + "obj16/"; // Model object icons//$NON-NLS-1$ Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH); declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_ETOOL_PROBLEM_CATEGORY, PATH_ETOOL + "problem_category.gif", true); //$NON-NLS-1$ declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_OBJS_ERROR_PATH, PATH_OBJECT + "error_tsk.gif", true); //$NON-NLS-1$ declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_OBJS_WARNING_PATH, PATH_OBJECT + "warn_tsk.gif", true); //$NON-NLS-1$ declareIdeWorkbenchImage(ideBundle, IDEInternalWorkbenchImages.IMG_OBJS_INFO_PATH, PATH_OBJECT + "info_tsk.gif", true); //$NON-NLS-1$ }
try { Application.initIDFactory(); } catch (IOException e) { Application.getMainConsoleLogger().error("Exeption connecting to web app", e); }
public void postWindowOpen() { initStatusLine(); IConsole[] consoles = ConsolePlugin.getDefault().getConsoleManager() .getConsoles(); for (IConsole console : consoles) { if (console instanceof MainConsole) { MainConsole mainConsole = (MainConsole) console; PhotonConsoleAppender appender = new PhotonConsoleAppender( mainConsole); appender.setLayout(new SimpleLayout()); Application.getMainConsoleLogger().addAppender(appender); } } IWorkbenchPage page = this.getWindowConfigurer().getWindow().getActivePage(); IStatusLineManager statusLineManager = getWindowConfigurer().getActionBarConfigurer().getStatusLineManager(); IContributionItem item = statusLineManager.find(CommandStatusLineContribution.ID); if (item instanceof CommandStatusLineContribution) { CommandStatusLineContribution cslc = (CommandStatusLineContribution) item; cslc.setIDFactory(Application.getIDFactory()); } try { Application.initJMSConnector(); Application.initQuoteFeed(); } catch (Exception ex){ Application.getMainConsoleLogger().error("Exeption making network connections ", ex); } Application.getMainConsoleLogger().info( "Application initialized: " + new Date()); }
JPanel buttons = ButtonBarFactory.buildRightAlignedBar(cancel, ok);
JPanel buttons = ButtonBarFactory.buildCenteredBar(ok, cancel);
private JPanel createToolbar() { JButton cancel = new JButton(Translation .getTranslation("general.cancel")); cancel.setMnemonic(Translation.getTranslation("general.cancel.key") .trim().charAt(0)); JButton ok = new JButton(Translation.getTranslation("general.ok")); ok.setMnemonic(Translation.getTranslation("general.ok.key").trim() .charAt(0)); JPanel buttons = ButtonBarFactory.buildRightAlignedBar(cancel, ok); buttons.setBorder(Borders.createEmptyBorder("7dlu, 7dlu, 7dlu, 7dlu")); buttons.setOpaque(false); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { option = CANCEL; dialog.setVisible(false); dialog.dispose(); dialog = null; } }); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSolutions(); option = OK; dialog.setVisible(false); dialog.dispose(); dialog = null; } }); return buttons; }
case Wavelet.BIGPACKHEADER:
case CompassMote.BIGPACKHEADER:
public void messageReceived(int to, Message m) { UnicastPack pack = (UnicastPack) m; int id = pack.get_data_src(); if (!busy || id != owner.getID()) return; switch (pack.get_data_type()) { case Wavelet.BIGPACKHEADER: if (curPackNum == HEADER_PACK_NUM && pack.get_data_data_bpHeader_requestType() == type) { // Store specific details of the request storeRequestData(pack); System.out.println("Got BP header (0/" + numPacks + ") from mote " + id); curPackNum++; sendAck(pack); // Send an ACK } break; case Wavelet.BIGPACKDATA: if (pack.get_data_data_bpData_curPack() == curPackNum) { newData(pack); // Store new data System.out.println("Got BP data (" + (curPackNum + 1) + "/" + numPacks + ") from mote " + id); if (morePacksExist()) { curPackNum++; } else { System.out.println("BP rcvd from mote " + id + " complete"); busy = false; // Done! owner.unpackerDone(new MoteStats(stream, numBlocks, numPtrs)); } sendAck(pack); // Send an ACK } break; } }
case Wavelet.BIGPACKDATA:
case CompassMote.BIGPACKDATA:
public void messageReceived(int to, Message m) { UnicastPack pack = (UnicastPack) m; int id = pack.get_data_src(); if (!busy || id != owner.getID()) return; switch (pack.get_data_type()) { case Wavelet.BIGPACKHEADER: if (curPackNum == HEADER_PACK_NUM && pack.get_data_data_bpHeader_requestType() == type) { // Store specific details of the request storeRequestData(pack); System.out.println("Got BP header (0/" + numPacks + ") from mote " + id); curPackNum++; sendAck(pack); // Send an ACK } break; case Wavelet.BIGPACKDATA: if (pack.get_data_data_bpData_curPack() == curPackNum) { newData(pack); // Store new data System.out.println("Got BP data (" + (curPackNum + 1) + "/" + numPacks + ") from mote " + id); if (morePacksExist()) { curPackNum++; } else { System.out.println("BP rcvd from mote " + id + " complete"); busy = false; // Done! owner.unpackerDone(new MoteStats(stream, numBlocks, numPtrs)); } sendAck(pack); // Send an ACK } break; } }
public void newRequest(BigPack msg) {
public void newRequest(short mType) {
public void newRequest(BigPack msg) { if (!busy) { busy = true; type = msg.getType(); curPackNum = HEADER_PACK_NUM; sendRequest(); } }
type = msg.getType();
type = mType;
public void newRequest(BigPack msg) { if (!busy) { busy = true; type = msg.getType(); curPackNum = HEADER_PACK_NUM; sendRequest(); } }
} catch (Exception ex) {
} catch (Throwable ex) {
public void handleCounterpartyMessage(Message aMessage) { fixMessageHistory.addIncomingMessage(aMessage); try { if (FIXMessageUtil.isExecutionReport(aMessage)) { handleExecutionReport(aMessage); } else if (FIXMessageUtil.isCancelReject(aMessage)) { handleCancelReject(aMessage); } } catch (Exception ex) { internalMainLogger.error( "Error decoding incoming message "+ex.getMessage(), ex); ex.printStackTrace(); } }
if (isFiltering) { stopFiltering = true; while (stopFiltering) { synchronized (this) { try { wait(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public List filter(Folder folder, List filelist) { if (isFiltering) { stopFiltering = true; while (stopFiltering) { synchronized (this) { try { wait(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } this.folder = folder; this.filelist = filelist; filter(); return filteredFilelist; }
isFiltering = true; filteredFilelist = filter0(); fireFileFilterChanged(); isFiltering = false;
int tmpExpectedCount = 0; int tmpDeletedCount = 0; int tmpNormalCount = 0; for (int i = 0; i < filelist.size(); i++) { Object obj = filelist.get(i); if (obj instanceof FileInfo) { FileInfo fInfo = (FileInfo) obj; boolean isDeleted = fInfo.isDeleted(); boolean isExpected = fInfo.isExpected(getController() .getFolderRepository()); boolean isNormal = !isDeleted && !isExpected; tmpDeletedCount += isDeleted && folder != null && folder.isKnown(fInfo) ? 1 : 0; tmpExpectedCount += isExpected ? 1 : 0; tmpNormalCount += isNormal ? 1 : 0;
public void run() { isFiltering = true; filteredFilelist = filter0(); fireFileFilterChanged(); isFiltering = false; }
} expectedCount = tmpExpectedCount; deletedCount = tmpDeletedCount; normalCount = tmpNormalCount; fireFileCountChanged(); }
public void run() { isFiltering = true; filteredFilelist = filter0(); fireFileFilterChanged(); isFiltering = false; }
if (filteredFilelist != null && !stopFiltering) {
if (filteredFilelist != null) {
private void fireFileCountChanged() { synchronized (this) { if (filteredFilelist != null && !stopFiltering) { FilterChangedEvent event = new FilterChangedEvent(this, filteredFilelist); for (int i = 0; i < listeners.size(); i++) { FileFilterChangeListener listener = (FileFilterChangeListener) listeners .get(i); listener.countChanged(event); } } } }
if (filteredFilelist != null && !stopFiltering) {
if (filteredFilelist != null) {
private void fireFileFilterChanged() { synchronized (this) { if (filteredFilelist != null && !stopFiltering) { FilterChangedEvent event = new FilterChangedEvent(this, filteredFilelist); for (int i = 0; i < listeners.size(); i++) { FileFilterChangeListener listener = (FileFilterChangeListener) listeners .get(i); listener.filterChanged(event); } } } }
private boolean matches(Directory directory, String[] keywords) {
private static final boolean matches(Directory directory, String[] keywords) {
private boolean matches(Directory directory, String[] keywords) { if (keywords == null || keywords.length == 0) { return true; } for (int i = 0; i < keywords.length; i++) { String keyword = keywords[i]; if (keyword == null) { throw new NullPointerException("Keyword empty at index " + i); } if (keyword.startsWith("-")) { // negative search: // remove the "-" keyword = keyword.substring(1); // must be something left if (keyword.length() != 0) { // Match for directoryname String directoryname = directory.getName().toLowerCase(); if (directoryname.indexOf(keyword) >= 0) { // matches nagative search return false; } // does not match negative search continue; } //only a minus sign in the keyword ignore continue; } // Match for directoryname String directoryname = directory.getName().toLowerCase(); if (directoryname.indexOf(keyword) >= 0) { // Match by name. Ok, continue continue; } // keyword did not match return false; }// all keywords matched! return true; }
private boolean matchesMP3(MP3FileInfo file, String[] keywords) {
private static final boolean matchesMP3(MP3FileInfo file, String[] keywords) {
private boolean matchesMP3(MP3FileInfo file, String[] keywords) { for (int i = 0; i < keywords.length; i++) { String keyword = keywords[i]; if (keyword == null) { throw new NullPointerException("Keyword empty at index " + i); } // Match for title if (file.getTitle() != null && file.getTitle().toLowerCase().indexOf(keyword) >= 0) { // Match by title. Ok, continue continue; } // Match for album if (file.getAlbum() != null && file.getAlbum().toLowerCase().indexOf(keyword) >= 0) { // Match by album. Ok, continue continue; } // Match for artist if (file.getArtist() != null && file.getArtist().toLowerCase().indexOf(keyword) >= 0) { // Match by artist. Ok, continue continue; } // Keyword does not match file, break return false; } // all keywords match! return true; }
private boolean matchesMeta(FileInfo file, String[] keywords) {
private static final boolean matchesMeta(FileInfo file, String[] keywords) {
private boolean matchesMeta(FileInfo file, String[] keywords) { if (keywords == null || keywords.length == 0) { return true; } if (file instanceof MP3FileInfo) { return matchesMP3((MP3FileInfo) file, keywords); } return false; }
AccessViolator violator = new AccessViolator(SessionSettings.class); SessionID defaultSessionID = (SessionID) violator.getField("DEFAULT_SESSION_ID", null); SessionSettings settings = new SessionSettings(); settings.setString(defaultSessionID, "ConnectionType","initiator"); settings.setLong(defaultSessionID, "HeartBtInt",30); settings.setString(defaultSessionID, "FileStorePath","store"); settings.setString(defaultSessionID, "StartTime","00:00:00"); settings.setString(defaultSessionID, "EndTime","00:00:00"); settings.setString(defaultSessionID, Session.SETTING_DATA_DICTIONARY, dataDictionary); settings.setString(defaultSessionID, "UseDataDictionary",useDataDictionary); settings.setLong(defaultSessionID, "ReconnectInterval",15); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_LOGOUT, resetOnLogout); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_DISCONNECT, resetOnDisconnect); settings.setString(defaultSessionID, Session.SETTING_RESET_WHEN_INITIATING_LOGON, sendResetSeqNumFlag);
Map<String, Object> defaults = new HashMap<String, Object>(); defaults.put("ConnectionType","initiator"); defaults.put("HeartBtInt",Long.toString(30)); defaults.put("FileStorePath","store"); defaults.put("StartTime","00:00:00"); defaults.put("EndTime","00:00:00"); defaults.put(Session.SETTING_DATA_DICTIONARY, dataDictionary); defaults.put("UseDataDictionary",useDataDictionary); defaults.put("ReconnectInterval",Long.toString(15)); defaults.put(Session.SETTING_RESET_ON_LOGOUT, resetOnLogout); defaults.put(Session.SETTING_RESET_ON_DISCONNECT, resetOnDisconnect); defaults.put(Session.SETTING_RESET_WHEN_INITIATING_LOGON, sendResetSeqNumFlag);
public void init(ConfigData config) throws Exception { mCurFixVersion = config.get(ConnectionConstants.FIX_VERSION_KEY, FIX_VERSION_DEFAULT); FIXDataDictionaryManager.setFIXVersion(mCurFixVersion); String senderCompID = config.get(ConnectionConstants.FIX_SENDER_COMP_ID, ""); String targetCompID = config.get(ConnectionConstants.FIX_TARGET_COMP_ID, ""); mFixServerAddress = config.get(ConnectionConstants.FIX_SERVER_ADDRESS, ""); String dataDictionary = config.get(Session.SETTING_DATA_DICTIONARY, ""); String useDataDictionary = config.get(Session.SETTING_USE_DATA_DICTIONARY, "N"); long fixServerPort = config.getLong(ConnectionConstants.FIX_SERVER_PORT, 0); String resetOnLogout = config.get(Session.SETTING_RESET_ON_LOGOUT, "Y"); String resetOnDisconnect = config.get(Session.SETTING_RESET_ON_DISCONNECT, "Y"); String sendResetSeqNumFlag = config.get(Session.SETTING_RESET_WHEN_INITIATING_LOGON, "Y"); QuickFIXDescriptor descriptor = sFIXVersionMap.get(mCurFixVersion); if (descriptor == null) { throw new ClassNotFoundException( "Could not find class for fix version " + mCurFixVersion); } mMessageFactory = descriptor.getMessageFactory(); // populate the default FIX session settings AccessViolator violator = new AccessViolator(SessionSettings.class); SessionID defaultSessionID = (SessionID) violator.getField("DEFAULT_SESSION_ID", null); SessionSettings settings = new SessionSettings(); settings.setString(defaultSessionID, "ConnectionType","initiator"); settings.setLong(defaultSessionID, "HeartBtInt",30); settings.setString(defaultSessionID, "FileStorePath","store"); settings.setString(defaultSessionID, "StartTime","00:00:00"); settings.setString(defaultSessionID, "EndTime","00:00:00"); settings.setString(defaultSessionID, Session.SETTING_DATA_DICTIONARY, dataDictionary); settings.setString(defaultSessionID, "UseDataDictionary",useDataDictionary); settings.setLong(defaultSessionID, "ReconnectInterval",15); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_LOGOUT, resetOnLogout); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_DISCONNECT, resetOnDisconnect); settings.setString(defaultSessionID, Session.SETTING_RESET_WHEN_INITIATING_LOGON, sendResetSeqNumFlag); settings.setString(defaultSessionID, SOCKET_CONNECT_HOST,mFixServerAddress); settings.setLong(defaultSessionID, SOCKET_CONNECT_PORT,fixServerPort); String [] keys = config.keys(); for (String key : keys) { if (key.startsWith(ConnectionConstants.FIX_SERVER_ADDRESS) && key.length() > ConnectionConstants.FIX_SERVER_ADDRESS.length() + 1) { String suffix = key.substring(ConnectionConstants.FIX_SERVER_ADDRESS.length() + 1); String newKey = SOCKET_CONNECT_HOST + suffix; settings.setString(defaultSessionID, newKey, config.get(key, "")); } } for (String key : keys) { if (key.startsWith(ConnectionConstants.FIX_SERVER_PORT) && key.length() > ConnectionConstants.FIX_SERVER_PORT.length()) { String suffix = key.substring(ConnectionConstants.FIX_SERVER_PORT.length() + 1); String newKey = SOCKET_CONNECT_PORT + suffix; settings.setString(defaultSessionID, newKey, config.get(key, "")); } } SessionID id = new SessionID(mCurFixVersion, senderCompID, targetCompID, ""); settings.setString(id, "BeginString", mCurFixVersion); settings.setString(id, "SenderCompID", senderCompID); settings.setString(id, "TargetCompID", targetCompID); settings.setString(id, "SessionQualifier", ""); MessageStoreFactory storeFactory = new FileStoreFactory(settings); LogFactory logFactory = new ScreenLogFactory(false, false, true); mSocketInitiator = new SocketInitiator(this, storeFactory, settings, logFactory, getMessageFactory()); mDefaultSessionID = new SessionID(mCurFixVersion, senderCompID, targetCompID, null); mSessionMap.put(mDefaultSessionID, sessionAdapter); startSocketInitiator(mSocketInitiator); }
settings.setString(defaultSessionID, SOCKET_CONNECT_HOST,mFixServerAddress); settings.setLong(defaultSessionID, SOCKET_CONNECT_PORT,fixServerPort);
defaults.put(SOCKET_CONNECT_HOST,mFixServerAddress); defaults.put(SOCKET_CONNECT_PORT,Long.toString(fixServerPort));
public void init(ConfigData config) throws Exception { mCurFixVersion = config.get(ConnectionConstants.FIX_VERSION_KEY, FIX_VERSION_DEFAULT); FIXDataDictionaryManager.setFIXVersion(mCurFixVersion); String senderCompID = config.get(ConnectionConstants.FIX_SENDER_COMP_ID, ""); String targetCompID = config.get(ConnectionConstants.FIX_TARGET_COMP_ID, ""); mFixServerAddress = config.get(ConnectionConstants.FIX_SERVER_ADDRESS, ""); String dataDictionary = config.get(Session.SETTING_DATA_DICTIONARY, ""); String useDataDictionary = config.get(Session.SETTING_USE_DATA_DICTIONARY, "N"); long fixServerPort = config.getLong(ConnectionConstants.FIX_SERVER_PORT, 0); String resetOnLogout = config.get(Session.SETTING_RESET_ON_LOGOUT, "Y"); String resetOnDisconnect = config.get(Session.SETTING_RESET_ON_DISCONNECT, "Y"); String sendResetSeqNumFlag = config.get(Session.SETTING_RESET_WHEN_INITIATING_LOGON, "Y"); QuickFIXDescriptor descriptor = sFIXVersionMap.get(mCurFixVersion); if (descriptor == null) { throw new ClassNotFoundException( "Could not find class for fix version " + mCurFixVersion); } mMessageFactory = descriptor.getMessageFactory(); // populate the default FIX session settings AccessViolator violator = new AccessViolator(SessionSettings.class); SessionID defaultSessionID = (SessionID) violator.getField("DEFAULT_SESSION_ID", null); SessionSettings settings = new SessionSettings(); settings.setString(defaultSessionID, "ConnectionType","initiator"); settings.setLong(defaultSessionID, "HeartBtInt",30); settings.setString(defaultSessionID, "FileStorePath","store"); settings.setString(defaultSessionID, "StartTime","00:00:00"); settings.setString(defaultSessionID, "EndTime","00:00:00"); settings.setString(defaultSessionID, Session.SETTING_DATA_DICTIONARY, dataDictionary); settings.setString(defaultSessionID, "UseDataDictionary",useDataDictionary); settings.setLong(defaultSessionID, "ReconnectInterval",15); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_LOGOUT, resetOnLogout); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_DISCONNECT, resetOnDisconnect); settings.setString(defaultSessionID, Session.SETTING_RESET_WHEN_INITIATING_LOGON, sendResetSeqNumFlag); settings.setString(defaultSessionID, SOCKET_CONNECT_HOST,mFixServerAddress); settings.setLong(defaultSessionID, SOCKET_CONNECT_PORT,fixServerPort); String [] keys = config.keys(); for (String key : keys) { if (key.startsWith(ConnectionConstants.FIX_SERVER_ADDRESS) && key.length() > ConnectionConstants.FIX_SERVER_ADDRESS.length() + 1) { String suffix = key.substring(ConnectionConstants.FIX_SERVER_ADDRESS.length() + 1); String newKey = SOCKET_CONNECT_HOST + suffix; settings.setString(defaultSessionID, newKey, config.get(key, "")); } } for (String key : keys) { if (key.startsWith(ConnectionConstants.FIX_SERVER_PORT) && key.length() > ConnectionConstants.FIX_SERVER_PORT.length()) { String suffix = key.substring(ConnectionConstants.FIX_SERVER_PORT.length() + 1); String newKey = SOCKET_CONNECT_PORT + suffix; settings.setString(defaultSessionID, newKey, config.get(key, "")); } } SessionID id = new SessionID(mCurFixVersion, senderCompID, targetCompID, ""); settings.setString(id, "BeginString", mCurFixVersion); settings.setString(id, "SenderCompID", senderCompID); settings.setString(id, "TargetCompID", targetCompID); settings.setString(id, "SessionQualifier", ""); MessageStoreFactory storeFactory = new FileStoreFactory(settings); LogFactory logFactory = new ScreenLogFactory(false, false, true); mSocketInitiator = new SocketInitiator(this, storeFactory, settings, logFactory, getMessageFactory()); mDefaultSessionID = new SessionID(mCurFixVersion, senderCompID, targetCompID, null); mSessionMap.put(mDefaultSessionID, sessionAdapter); startSocketInitiator(mSocketInitiator); }
settings.setString(defaultSessionID, newKey, config.get(key, ""));
defaults.put(newKey, config.get(key, ""));
public void init(ConfigData config) throws Exception { mCurFixVersion = config.get(ConnectionConstants.FIX_VERSION_KEY, FIX_VERSION_DEFAULT); FIXDataDictionaryManager.setFIXVersion(mCurFixVersion); String senderCompID = config.get(ConnectionConstants.FIX_SENDER_COMP_ID, ""); String targetCompID = config.get(ConnectionConstants.FIX_TARGET_COMP_ID, ""); mFixServerAddress = config.get(ConnectionConstants.FIX_SERVER_ADDRESS, ""); String dataDictionary = config.get(Session.SETTING_DATA_DICTIONARY, ""); String useDataDictionary = config.get(Session.SETTING_USE_DATA_DICTIONARY, "N"); long fixServerPort = config.getLong(ConnectionConstants.FIX_SERVER_PORT, 0); String resetOnLogout = config.get(Session.SETTING_RESET_ON_LOGOUT, "Y"); String resetOnDisconnect = config.get(Session.SETTING_RESET_ON_DISCONNECT, "Y"); String sendResetSeqNumFlag = config.get(Session.SETTING_RESET_WHEN_INITIATING_LOGON, "Y"); QuickFIXDescriptor descriptor = sFIXVersionMap.get(mCurFixVersion); if (descriptor == null) { throw new ClassNotFoundException( "Could not find class for fix version " + mCurFixVersion); } mMessageFactory = descriptor.getMessageFactory(); // populate the default FIX session settings AccessViolator violator = new AccessViolator(SessionSettings.class); SessionID defaultSessionID = (SessionID) violator.getField("DEFAULT_SESSION_ID", null); SessionSettings settings = new SessionSettings(); settings.setString(defaultSessionID, "ConnectionType","initiator"); settings.setLong(defaultSessionID, "HeartBtInt",30); settings.setString(defaultSessionID, "FileStorePath","store"); settings.setString(defaultSessionID, "StartTime","00:00:00"); settings.setString(defaultSessionID, "EndTime","00:00:00"); settings.setString(defaultSessionID, Session.SETTING_DATA_DICTIONARY, dataDictionary); settings.setString(defaultSessionID, "UseDataDictionary",useDataDictionary); settings.setLong(defaultSessionID, "ReconnectInterval",15); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_LOGOUT, resetOnLogout); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_DISCONNECT, resetOnDisconnect); settings.setString(defaultSessionID, Session.SETTING_RESET_WHEN_INITIATING_LOGON, sendResetSeqNumFlag); settings.setString(defaultSessionID, SOCKET_CONNECT_HOST,mFixServerAddress); settings.setLong(defaultSessionID, SOCKET_CONNECT_PORT,fixServerPort); String [] keys = config.keys(); for (String key : keys) { if (key.startsWith(ConnectionConstants.FIX_SERVER_ADDRESS) && key.length() > ConnectionConstants.FIX_SERVER_ADDRESS.length() + 1) { String suffix = key.substring(ConnectionConstants.FIX_SERVER_ADDRESS.length() + 1); String newKey = SOCKET_CONNECT_HOST + suffix; settings.setString(defaultSessionID, newKey, config.get(key, "")); } } for (String key : keys) { if (key.startsWith(ConnectionConstants.FIX_SERVER_PORT) && key.length() > ConnectionConstants.FIX_SERVER_PORT.length()) { String suffix = key.substring(ConnectionConstants.FIX_SERVER_PORT.length() + 1); String newKey = SOCKET_CONNECT_PORT + suffix; settings.setString(defaultSessionID, newKey, config.get(key, "")); } } SessionID id = new SessionID(mCurFixVersion, senderCompID, targetCompID, ""); settings.setString(id, "BeginString", mCurFixVersion); settings.setString(id, "SenderCompID", senderCompID); settings.setString(id, "TargetCompID", targetCompID); settings.setString(id, "SessionQualifier", ""); MessageStoreFactory storeFactory = new FileStoreFactory(settings); LogFactory logFactory = new ScreenLogFactory(false, false, true); mSocketInitiator = new SocketInitiator(this, storeFactory, settings, logFactory, getMessageFactory()); mDefaultSessionID = new SessionID(mCurFixVersion, senderCompID, targetCompID, null); mSessionMap.put(mDefaultSessionID, sessionAdapter); startSocketInitiator(mSocketInitiator); }
SessionSettings settings = new SessionSettings(); settings.set(defaults);
public void init(ConfigData config) throws Exception { mCurFixVersion = config.get(ConnectionConstants.FIX_VERSION_KEY, FIX_VERSION_DEFAULT); FIXDataDictionaryManager.setFIXVersion(mCurFixVersion); String senderCompID = config.get(ConnectionConstants.FIX_SENDER_COMP_ID, ""); String targetCompID = config.get(ConnectionConstants.FIX_TARGET_COMP_ID, ""); mFixServerAddress = config.get(ConnectionConstants.FIX_SERVER_ADDRESS, ""); String dataDictionary = config.get(Session.SETTING_DATA_DICTIONARY, ""); String useDataDictionary = config.get(Session.SETTING_USE_DATA_DICTIONARY, "N"); long fixServerPort = config.getLong(ConnectionConstants.FIX_SERVER_PORT, 0); String resetOnLogout = config.get(Session.SETTING_RESET_ON_LOGOUT, "Y"); String resetOnDisconnect = config.get(Session.SETTING_RESET_ON_DISCONNECT, "Y"); String sendResetSeqNumFlag = config.get(Session.SETTING_RESET_WHEN_INITIATING_LOGON, "Y"); QuickFIXDescriptor descriptor = sFIXVersionMap.get(mCurFixVersion); if (descriptor == null) { throw new ClassNotFoundException( "Could not find class for fix version " + mCurFixVersion); } mMessageFactory = descriptor.getMessageFactory(); // populate the default FIX session settings AccessViolator violator = new AccessViolator(SessionSettings.class); SessionID defaultSessionID = (SessionID) violator.getField("DEFAULT_SESSION_ID", null); SessionSettings settings = new SessionSettings(); settings.setString(defaultSessionID, "ConnectionType","initiator"); settings.setLong(defaultSessionID, "HeartBtInt",30); settings.setString(defaultSessionID, "FileStorePath","store"); settings.setString(defaultSessionID, "StartTime","00:00:00"); settings.setString(defaultSessionID, "EndTime","00:00:00"); settings.setString(defaultSessionID, Session.SETTING_DATA_DICTIONARY, dataDictionary); settings.setString(defaultSessionID, "UseDataDictionary",useDataDictionary); settings.setLong(defaultSessionID, "ReconnectInterval",15); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_LOGOUT, resetOnLogout); settings.setString(defaultSessionID, Session.SETTING_RESET_ON_DISCONNECT, resetOnDisconnect); settings.setString(defaultSessionID, Session.SETTING_RESET_WHEN_INITIATING_LOGON, sendResetSeqNumFlag); settings.setString(defaultSessionID, SOCKET_CONNECT_HOST,mFixServerAddress); settings.setLong(defaultSessionID, SOCKET_CONNECT_PORT,fixServerPort); String [] keys = config.keys(); for (String key : keys) { if (key.startsWith(ConnectionConstants.FIX_SERVER_ADDRESS) && key.length() > ConnectionConstants.FIX_SERVER_ADDRESS.length() + 1) { String suffix = key.substring(ConnectionConstants.FIX_SERVER_ADDRESS.length() + 1); String newKey = SOCKET_CONNECT_HOST + suffix; settings.setString(defaultSessionID, newKey, config.get(key, "")); } } for (String key : keys) { if (key.startsWith(ConnectionConstants.FIX_SERVER_PORT) && key.length() > ConnectionConstants.FIX_SERVER_PORT.length()) { String suffix = key.substring(ConnectionConstants.FIX_SERVER_PORT.length() + 1); String newKey = SOCKET_CONNECT_PORT + suffix; settings.setString(defaultSessionID, newKey, config.get(key, "")); } } SessionID id = new SessionID(mCurFixVersion, senderCompID, targetCompID, ""); settings.setString(id, "BeginString", mCurFixVersion); settings.setString(id, "SenderCompID", senderCompID); settings.setString(id, "TargetCompID", targetCompID); settings.setString(id, "SessionQualifier", ""); MessageStoreFactory storeFactory = new FileStoreFactory(settings); LogFactory logFactory = new ScreenLogFactory(false, false, true); mSocketInitiator = new SocketInitiator(this, storeFactory, settings, logFactory, getMessageFactory()); mDefaultSessionID = new SessionID(mCurFixVersion, senderCompID, targetCompID, null); mSessionMap.put(mDefaultSessionID, sessionAdapter); startSocketInitiator(mSocketInitiator); }
getConfigCPS(ConfigurationEntry.UPLOADLIMIT_WAN); getConfigCPS(ConfigurationEntry.DOWNLOADLIMIT_WAN); getConfigCPS(ConfigurationEntry.UPLOADLIMIT_LAN); getConfigCPS(ConfigurationEntry.DOWNLOADLIMIT_LAN);
checkConfigCPS(ConfigurationEntry.UPLOADLIMIT_WAN, 0); checkConfigCPS(ConfigurationEntry.DOWNLOADLIMIT_WAN, 0); checkConfigCPS(ConfigurationEntry.UPLOADLIMIT_LAN, 0); checkConfigCPS(ConfigurationEntry.DOWNLOADLIMIT_LAN, 0);
public TransferManager(Controller controller) { super(controller); this.started = false; this.queuedUploads = Collections .synchronizedList(new LinkedList<Upload>()); this.activeUploads = Collections .synchronizedList(new LinkedList<Upload>()); this.downloads = new ConcurrentHashMap<FileInfo, Download>(); this.pendingDownloads = Collections .synchronizedList(new LinkedList<Download>()); this.completedDownloads = Collections .synchronizedList(new LinkedList<Download>()); this.uploadCounter = new TransferCounter(); this.downloadCounter = new TransferCounter(); // Create listener support this.listenerSupport = (TransferManagerListener) ListenerSupportFactory .createListenerSupport(TransferManagerListener.class); // maximum concurrent uploads allowedUploads = ConfigurationEntry.UPLOADS_MAX_CONCURRENT.getValueInt( getController()).intValue(); if (allowedUploads <= 0) { throw new NumberFormatException("Illegal value for max uploads: " + allowedUploads); } bandwidthProvider = new BandwidthProvider(); sharedWANOutputHandler = new BandwidthLimiter(); sharedWANInputHandler = new BandwidthLimiter(); // FIXME: This is a hack to create valid entries getConfigCPS(ConfigurationEntry.UPLOADLIMIT_WAN); getConfigCPS(ConfigurationEntry.DOWNLOADLIMIT_WAN); getConfigCPS(ConfigurationEntry.UPLOADLIMIT_LAN); getConfigCPS(ConfigurationEntry.DOWNLOADLIMIT_LAN); // bandwidthProvider.setLimitBPS(sharedWANOutputHandler, maxCps); // set ul limit setAllowedUploadCPSForWAN(getConfigCPS(ConfigurationEntry.UPLOADLIMIT_WAN)); setAllowedDownloadCPSForWAN(getConfigCPS(ConfigurationEntry.DOWNLOADLIMIT_WAN)); sharedLANOutputHandler = new BandwidthLimiter(); sharedLANInputHandler = new BandwidthLimiter(); // bandwidthProvider.setLimitBPS(sharedLANOutputHandler, maxCps); // set ul limit setAllowedUploadCPSForLAN(getConfigCPS(ConfigurationEntry.UPLOADLIMIT_LAN)); setAllowedDownloadCPSForLAN(getConfigCPS(ConfigurationEntry.DOWNLOADLIMIT_LAN)); }
entry.setValue(getController(), Long.toString(maxCps));
private long getConfigCPS(ConfigurationEntry entry) { String cps = entry.getValue(getController()); long maxCps = 0; if (cps != null) { try { maxCps = (long) Double.parseDouble(cps) * 1024; if (maxCps < 0) { throw new NumberFormatException(); } } catch (NumberFormatException e) { log().warn( "Illegal value for KByte." + entry + " '" + cps + "'"); } } entry.setValue(getController(), Long.toString(maxCps)); return maxCps; }
synchronized (activeUploads) { synchronized (queuedUploads) {
synchronized (queuedUploads) { synchronized (activeUploads) {
public Upload queueUpload(Member from, RequestDownload dl) { if (dl == null || dl.file == null) { throw new NullPointerException("Downloadrequest/File is null"); } // Never upload db files !! if (Folder.DB_FILENAME.equalsIgnoreCase(dl.file.getName()) || Folder.DB_BACKUP_FILENAME.equalsIgnoreCase(dl.file.getName())) { log() .error( from.getNick() + " has illegally requested to download a folder database file"); return null; } Upload oldUpload = null; Upload upload = new Upload(this, from, dl); FolderRepository repo = getController().getFolderRepository(); File diskFile = upload.getFile().getDiskFile(repo); if (diskFile == null || !diskFile.exists()) { // file no longer there Folder folder = repo.getFolder(upload.getFile().getFolderInfo()); if (folder.isKnown(upload.getFile())) { // it is in the database FileInfo localFileInfo = folder.getFile(upload.getFile()); if (localFileInfo.isDeleted()) { // ok file is allready marked deleted in DB so its requested // before we could send our changes return null; } if (folder.getSyncProfile().isAutoDetectLocalChanges()) { // make sure the file is scanned in next check folder.forceScanOnNextMaintenance(); } return null; } // file is not known in internal database ignore invalid request return null; } if (upload.isBroken()) { // connection lost // Check if this download is broken return null; } // Check if we have a old upload to break synchronized (activeUploads) { synchronized (queuedUploads) { int oldUploadIndex = activeUploads.indexOf(upload); if (oldUploadIndex >= 0) { oldUpload = activeUploads.get(oldUploadIndex); activeUploads.remove(oldUploadIndex); } oldUploadIndex = queuedUploads.indexOf(upload); if (oldUploadIndex >= 0) { if (oldUpload != null) { // Should never happen throw new IllegalStateException( "Found illegal upload. is in list of queued AND active uploads: " + oldUpload); } oldUpload = queuedUploads.get(oldUploadIndex); queuedUploads.remove(oldUploadIndex); } } } if (oldUpload != null) { log().warn( "Received already known download request for " + dl.file + " from " + from.getNick() + ", overwriting old request"); // Stop former upload request oldUpload.abort(); oldUpload.shutdown(); setBroken(oldUpload); } synchronized (queuedUploads) { log().debug( "Upload enqueud: " + dl.file + ", startOffset: " + dl.startOffset + ", to: " + from); queuedUploads.add(upload); } // If upload is not started, tell peer if (!upload.isStarted()) { from.sendMessageAsynchron(new DownloadQueued(upload.getFile()), null); } if (!upload.isBroken()) { fireUploadRequested(new TransferManagerEvent(this, upload)); } // Trigger working thread triggerTransfersCheck(); return upload; }
log().verbose( "Starting upload at queue index: " + uploadIndex);
log() .verbose( "Starting upload at queue position: " + uploadIndex);
public void run() { long waitTime = getController().getWaitTime() * 2; int count = 0; List<Upload> uploadsToStart = new LinkedList<Upload>(); List<Member> uploadsToStartNodes = new LinkedList<Member>(); List<Upload> uploadsToBreak = new LinkedList<Upload>(); List<Download> downloadsToBreak = new LinkedList<Download>(); while (!Thread.currentThread().isInterrupted()) { // Check uploads/downloads every 10 seconds if (logVerbose) { log().verbose("Checking uploads/downloads"); } // Check uploads to start uploadsToStart.clear(); uploadsToStartNodes.clear(); uploadsToBreak.clear(); if (logVerbose) { log().verbose("Checking queued uploads"); } synchronized (queuedUploads) { for (Iterator it = queuedUploads.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); if (upload.isBroken()) { // add to break dls uploadsToBreak.add(upload); } else if ((hasFreeUploadSlots() || upload.getPartner() .isOnLAN()) && !uploadingTo(upload.getPartner()) && !uploadsToStartNodes.contains(upload.getPartner())) { // start the upload if we have free slots // and not uploading to member currently // or user is on local network // TODO should check if this file is not sended (or is // being send) to other user in the last minute or so to // allow for disitributtion of that file by user that // just received that file from us // Enqueue upload to friends and lan members first int uploadIndex = upload.getPartner().isFriend() ? 0 : uploadsToStart.size(); log().verbose( "Starting upload at queue index: " + uploadIndex); uploadsToStart.add(uploadIndex, upload); // Do not start another upload to that node // I implemented this wrong // I want to allow a start of 2 more uploads to a // partner on lan. // if (upload.getPartner().isOnLAN()) { // if (lanUploadCount++==2) { // uploadsToStartNodes.add(upload.getPartner()); // } // } else { // add to list of nodes to indicate are already // uploading to this partner uploadsToStartNodes.add(upload.getPartner()); // } } } } if (logVerbose) { log().verbose( "Starting " + uploadsToStart.size() + " Uploads, " + uploadsToBreak.size() + " are getting broken"); } // Start uploads for (Iterator it = uploadsToStart.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); upload.start(); } for (Iterator it = uploadsToBreak.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); // Set broken setBroken(upload); } // Check pending downloads checkPendingDownloads(); // Checking downloads downloadsToBreak.clear(); int activeDownloads = 0; int sleepingDownloads = 0; if (logVerbose) { log().verbose("Checking downloads"); } synchronized (downloads) { for (Iterator it = downloads.values().iterator(); it.hasNext();) { Download download = (Download) it.next(); if (download.isBroken()) { // Set broken downloadsToBreak.add(download); } else if (download.isStarted()) { activeDownloads++; } else { sleepingDownloads++; } } } if (logVerbose) { log().verbose( "Breaking " + downloadsToBreak.size() + " downloads"); } // Now set broken downloads for (Iterator it = downloadsToBreak.iterator(); it.hasNext();) { Download download = (Download) it.next(); setBroken(download); } // log upload / donwloads if (count % 2 == 0) { log().debug( "Transfers: " + activeDownloads + " download(s), " + sleepingDownloads + " in queue, " + activeUploads.size() + " upload(s), " + queuedUploads.size() + " in queue, " + Format.NUMBER_FORMATS.format(getUploadCounter() .calculateCurrentKBS()) + " KByte/s"); } count++; // wait a bit to next work try { synchronized (waitTrigger) { waitTrigger.wait(waitTime); } // Wait another 100ms to avoid spamming via trigger Thread.sleep(100); } catch (InterruptedException e) { // Break break; } } }
synchronized (waitTrigger) { waitTrigger.wait(waitTime);
if (!transferCheckTriggered) { synchronized (waitTrigger) { waitTrigger.wait(waitTime); }
public void run() { long waitTime = getController().getWaitTime() * 2; int count = 0; List<Upload> uploadsToStart = new LinkedList<Upload>(); List<Member> uploadsToStartNodes = new LinkedList<Member>(); List<Upload> uploadsToBreak = new LinkedList<Upload>(); List<Download> downloadsToBreak = new LinkedList<Download>(); while (!Thread.currentThread().isInterrupted()) { // Check uploads/downloads every 10 seconds if (logVerbose) { log().verbose("Checking uploads/downloads"); } // Check uploads to start uploadsToStart.clear(); uploadsToStartNodes.clear(); uploadsToBreak.clear(); if (logVerbose) { log().verbose("Checking queued uploads"); } synchronized (queuedUploads) { for (Iterator it = queuedUploads.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); if (upload.isBroken()) { // add to break dls uploadsToBreak.add(upload); } else if ((hasFreeUploadSlots() || upload.getPartner() .isOnLAN()) && !uploadingTo(upload.getPartner()) && !uploadsToStartNodes.contains(upload.getPartner())) { // start the upload if we have free slots // and not uploading to member currently // or user is on local network // TODO should check if this file is not sended (or is // being send) to other user in the last minute or so to // allow for disitributtion of that file by user that // just received that file from us // Enqueue upload to friends and lan members first int uploadIndex = upload.getPartner().isFriend() ? 0 : uploadsToStart.size(); log().verbose( "Starting upload at queue index: " + uploadIndex); uploadsToStart.add(uploadIndex, upload); // Do not start another upload to that node // I implemented this wrong // I want to allow a start of 2 more uploads to a // partner on lan. // if (upload.getPartner().isOnLAN()) { // if (lanUploadCount++==2) { // uploadsToStartNodes.add(upload.getPartner()); // } // } else { // add to list of nodes to indicate are already // uploading to this partner uploadsToStartNodes.add(upload.getPartner()); // } } } } if (logVerbose) { log().verbose( "Starting " + uploadsToStart.size() + " Uploads, " + uploadsToBreak.size() + " are getting broken"); } // Start uploads for (Iterator it = uploadsToStart.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); upload.start(); } for (Iterator it = uploadsToBreak.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); // Set broken setBroken(upload); } // Check pending downloads checkPendingDownloads(); // Checking downloads downloadsToBreak.clear(); int activeDownloads = 0; int sleepingDownloads = 0; if (logVerbose) { log().verbose("Checking downloads"); } synchronized (downloads) { for (Iterator it = downloads.values().iterator(); it.hasNext();) { Download download = (Download) it.next(); if (download.isBroken()) { // Set broken downloadsToBreak.add(download); } else if (download.isStarted()) { activeDownloads++; } else { sleepingDownloads++; } } } if (logVerbose) { log().verbose( "Breaking " + downloadsToBreak.size() + " downloads"); } // Now set broken downloads for (Iterator it = downloadsToBreak.iterator(); it.hasNext();) { Download download = (Download) it.next(); setBroken(download); } // log upload / donwloads if (count % 2 == 0) { log().debug( "Transfers: " + activeDownloads + " download(s), " + sleepingDownloads + " in queue, " + activeUploads.size() + " upload(s), " + queuedUploads.size() + " in queue, " + Format.NUMBER_FORMATS.format(getUploadCounter() .calculateCurrentKBS()) + " KByte/s"); } count++; // wait a bit to next work try { synchronized (waitTrigger) { waitTrigger.wait(waitTime); } // Wait another 100ms to avoid spamming via trigger Thread.sleep(100); } catch (InterruptedException e) { // Break break; } } }
transferCheckTriggered = false;
public void run() { long waitTime = getController().getWaitTime() * 2; int count = 0; List<Upload> uploadsToStart = new LinkedList<Upload>(); List<Member> uploadsToStartNodes = new LinkedList<Member>(); List<Upload> uploadsToBreak = new LinkedList<Upload>(); List<Download> downloadsToBreak = new LinkedList<Download>(); while (!Thread.currentThread().isInterrupted()) { // Check uploads/downloads every 10 seconds if (logVerbose) { log().verbose("Checking uploads/downloads"); } // Check uploads to start uploadsToStart.clear(); uploadsToStartNodes.clear(); uploadsToBreak.clear(); if (logVerbose) { log().verbose("Checking queued uploads"); } synchronized (queuedUploads) { for (Iterator it = queuedUploads.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); if (upload.isBroken()) { // add to break dls uploadsToBreak.add(upload); } else if ((hasFreeUploadSlots() || upload.getPartner() .isOnLAN()) && !uploadingTo(upload.getPartner()) && !uploadsToStartNodes.contains(upload.getPartner())) { // start the upload if we have free slots // and not uploading to member currently // or user is on local network // TODO should check if this file is not sended (or is // being send) to other user in the last minute or so to // allow for disitributtion of that file by user that // just received that file from us // Enqueue upload to friends and lan members first int uploadIndex = upload.getPartner().isFriend() ? 0 : uploadsToStart.size(); log().verbose( "Starting upload at queue index: " + uploadIndex); uploadsToStart.add(uploadIndex, upload); // Do not start another upload to that node // I implemented this wrong // I want to allow a start of 2 more uploads to a // partner on lan. // if (upload.getPartner().isOnLAN()) { // if (lanUploadCount++==2) { // uploadsToStartNodes.add(upload.getPartner()); // } // } else { // add to list of nodes to indicate are already // uploading to this partner uploadsToStartNodes.add(upload.getPartner()); // } } } } if (logVerbose) { log().verbose( "Starting " + uploadsToStart.size() + " Uploads, " + uploadsToBreak.size() + " are getting broken"); } // Start uploads for (Iterator it = uploadsToStart.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); upload.start(); } for (Iterator it = uploadsToBreak.iterator(); it.hasNext();) { Upload upload = (Upload) it.next(); // Set broken setBroken(upload); } // Check pending downloads checkPendingDownloads(); // Checking downloads downloadsToBreak.clear(); int activeDownloads = 0; int sleepingDownloads = 0; if (logVerbose) { log().verbose("Checking downloads"); } synchronized (downloads) { for (Iterator it = downloads.values().iterator(); it.hasNext();) { Download download = (Download) it.next(); if (download.isBroken()) { // Set broken downloadsToBreak.add(download); } else if (download.isStarted()) { activeDownloads++; } else { sleepingDownloads++; } } } if (logVerbose) { log().verbose( "Breaking " + downloadsToBreak.size() + " downloads"); } // Now set broken downloads for (Iterator it = downloadsToBreak.iterator(); it.hasNext();) { Download download = (Download) it.next(); setBroken(download); } // log upload / donwloads if (count % 2 == 0) { log().debug( "Transfers: " + activeDownloads + " download(s), " + sleepingDownloads + " in queue, " + activeUploads.size() + " upload(s), " + queuedUploads.size() + " in queue, " + Format.NUMBER_FORMATS.format(getUploadCounter() .calculateCurrentKBS()) + " KByte/s"); } count++; // wait a bit to next work try { synchronized (waitTrigger) { waitTrigger.wait(waitTime); } // Wait another 100ms to avoid spamming via trigger Thread.sleep(100); } catch (InterruptedException e) { // Break break; } } }
if (transfer instanceof Upload) { triggerTransfersCheck(); }
void setCompleted(Transfer transfer) { boolean transferFound = false; transfer.setCompleted(); if (transfer instanceof Download) { Download download = (Download) transfer; transferFound = downloads.containsKey(transfer.getFile()); if (!transferFound) { return; } FileInfo fInfo = transfer.getFile(); // Inform other folder member of added file Folder folder = fInfo.getFolder(getController() .getFolderRepository()); if (folder != null) { // scan in new downloaded file folder.scanDownloadFile(fInfo, download.getTempFile()); } // Actually remove from active downloads list downloads.remove(transfer.getFile()); // Add to list of completed downloads completedDownloads.add((Download) transfer); // Fire event fireDownloadCompleted(new TransferManagerEvent(this, (Download) transfer)); Integer nDlFromNode = countNodesActiveAndQueuedDownloads().get( transfer.getPartner()); if (nDlFromNode == null || nDlFromNode.intValue() <= 2) { // Trigger filerequestor getController().getFolderRepository().getFileRequestor() .triggerFileRequesting(); } else { log().verbose( "Not triggering file requestor. " + nDlFromNode + " more dls from " + transfer.getPartner()); } // Autostart torrents File diskFile = fInfo.getDiskFile(getController() .getFolderRepository()); boolean isLeechFile = diskFile != null && fInfo.getFilenameOnly().endsWith(".torrent"); // Autostart bittorento! if (folder.getSyncProfile().isAutostartLeechPrograms() && isLeechFile) { log().warn("Auto starting: " + diskFile.getAbsolutePath()); try { FileUtils.executeFile(diskFile); } catch (IOException e) { log().error(e); // unableToStart(fInfo, ex); } } } else if (transfer instanceof Upload) { transferFound = queuedUploads.remove(transfer); transferFound = activeUploads.remove(transfer) || transferFound; if (transferFound) { // Fire event fireUploadCompleted(new TransferManagerEvent(this, (Upload) transfer)); } } log().debug("Transfer completed: " + transfer); if (transfer instanceof Upload) { // Now trigger, to start next upload triggerTransfersCheck(); } }
transferCheckTriggered = true;
private void triggerTransfersCheck() { // log().verbose("Triggering transfers check"); synchronized (waitTrigger) { waitTrigger.notifyAll(); } }
List<MessageBundleInfo> bundles = new ArrayList<MessageBundleInfo>(Arrays.asList( MESSAGE_BUNDLE_INFO)); addLocalMessageBundles(bundles); registerMessageBundles(bundles);
private void commonInit(Properties inProps) { sLogger = LoggerAdapter.initializeLogger("mktctrRoot"); final ApplicationBase outerThis = this; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { outerThis.shutdown(); } }); properties = inProps; jcycloneConfig = generateJCycloneConfig(properties); }
LoggerAdapter.error("Unable to register JMX Mbean: ", ex, this);
LoggerAdapter.error(MessageKey.JMX_BEAN_FAILURE.getLocalizedMessage(), ex, this);
protected void registerMBean(boolean fExitOnFail) { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { String pkgName = this.getClass().getPackage().toString(); String className = this.getClass().getSimpleName(); ObjectName name = new ObjectName(pkgName +":type="+className); mbs.registerMBean(this, name); } catch (JMException ex) { LoggerAdapter.error("Unable to register JMX Mbean: ", ex, this); if(fExitOnFail) {System.exit(-1); } } }
LoggerAdapter.info("Shutting down application", this);
LoggerAdapter.info(MessageKey.APP_SHUTDOWN.getLocalizedMessage(), this);
public void shutdown() { LoggerAdapter.info("Shutting down application", this); try { if(jcyclone!=null) { jcyclone.stop(); // reset the var so that we don't try to shutdown twice (this may happen in unit tests) jcyclone = null; } } catch (Exception e) { LoggerAdapter.error("Error while shutting down JCyclone framework", e, this); } }
LoggerAdapter.error("Error while shutting down JCyclone framework", e, this);
LoggerAdapter.error(MessageKey.JCYCLONE_SHUTDOWN_ERR.getLocalizedMessage(), e, this);
public void shutdown() { LoggerAdapter.info("Shutting down application", this); try { if(jcyclone!=null) { jcyclone.stop(); // reset the var so that we don't try to shutdown twice (this may happen in unit tests) jcyclone = null; } } catch (Exception e) { LoggerAdapter.error("Error while shutting down JCyclone framework", e, this); } }
throw new IllegalArgumentException("Item must not be null.");
throw new IllegalArgumentException(MessageKey.ERROR_NULL_DELAYED_ITEM.getLocalizedMessage());
public DelayedItem(long delayInMillis, T anItem, Clock clock) { if (anItem == null) { throw new IllegalArgumentException("Item must not be null."); } if (clock == null) { mClock = new Clock() { public long getTime() { return System.currentTimeMillis(); } public long getApproximateTime() { return System.currentTimeMillis(); } }; } else { mClock = clock; } mItemSendTime = mClock.getTime() + delayInMillis; if(LoggerAdapter.isDebugEnabled(this)) { LoggerAdapter.debug("Will send at "+new Date(mItemSendTime), this); } mItem = anItem; }
return "In " + getDelay(TimeUnit.MILLISECONDS) + " millis, will send " + mItem.toString();
return MessageKey.DELAYED_ITEM_DESC.getLocalizedMessage(new Object[]{getDelay(TimeUnit.MILLISECONDS), mItem.toString()});
public String toString() { return "In " + getDelay(TimeUnit.MILLISECONDS) + " millis, will send " + mItem.toString(); }
log().verbose("Network folder list processor triggerd");
if (logVerbose) { log().verbose("Network folder list processor triggerd"); }
public void run() { while (started) { synchronized (receivedNetworkFolderLists) { try { receivedNetworkFolderLists.wait(); } catch (InterruptedException e) { log().verbose("Stopping network folder list processor", e); break; } } log().verbose("Network folder list processor triggerd"); try { // Wait a bit to avoid spamming Thread.sleep(5000); } catch (InterruptedException e) { log().verbose("Stopping network folder list processor", e); break; } while (!receivedNetworkFolderLists.isEmpty()) { NetworkFolderList netList = receivedNetworkFolderLists .remove(0); processNetworkFolderList(netList); } } }
listeners = Collections .synchronizedList(new ArrayList<FolderRepositoryListener>());
this.listenerSupport = (FolderRepositoryListener) ListenerSupportFactory .createListenerSupport(FolderRepositoryListener.class);
public FolderRepository(Controller controller) { super(controller); // UI Code TreeNode rootNode = controller.isUIOpen() ? controller .getUIController().getControlQuarter().getNavigationTreeModel() .getRootNode() : null; this.joinedFolders = new TreeNodeList("JOINED_FOLDERS", rootNode); this.networkFolders = Collections .synchronizedMap(new HashMap<FolderInfo, FolderDetails>()); this.receivedNetworkFolderLists = Collections .synchronizedList(new ArrayList<NetworkFolderList>()); // Rest this.joinedFolders.sortBy(new FolderComparator()); this.folders = Collections.synchronizedMap(new HashMap()); this.fileRequestor = new FileRequestor(controller); this.shares = new Shares(controller); this.netListProcessor = new NetworkFolderListProcessor(); this.started = false; // Create listener support // this.listenerSupport = (FolderRepositoryListener) // ListenerSupportFactory // .createListenerSupport(FolderRepositoryListener.class); listeners = Collections .synchronizedList(new ArrayList<FolderRepositoryListener>()); }
synchronized (listeners) { listeners.add(listener); }
ListenerSupportFactory.addListener(listenerSupport, listener);
public void addFolderRepositoryListener(FolderRepositoryListener listener) { // ListenerSupportFactory.addListener(listenerSupport, listener); synchronized (listeners) { listeners.add(listener); } }
log().verbose("Omitting cleanup of network folder list");
if (logVerbose) { log().verbose("Omitting cleanup of network folder list"); }
private void cleanupNetworkFoldersIfNessesary() { long time2Wait = 1000 * 60 * 5; boolean nessesary = lastNetworkFolderListCleanup == null || (lastNetworkFolderListCleanup.getTime() < System .currentTimeMillis() - time2Wait); if (nessesary) { // Cleanup cleanupNetworkFolder(); } else { log().verbose("Omitting cleanup of network folder list"); } }
final FolderRepositoryEvent e = new FolderRepositoryEvent(this, folder); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.folderCreated(e); } }
listenerSupport.folderCreated(new FolderRepositoryEvent(this, folder));
private void fireFolderCreated(Folder folder) { final FolderRepositoryEvent e = new FolderRepositoryEvent(this, folder); // Call to listener support // listenerSupport.folderCreated(e); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.folderCreated(e); } } }
final FolderRepositoryEvent e = new FolderRepositoryEvent(this, folder); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.folderRemoved(e); } }
listenerSupport.folderRemoved(new FolderRepositoryEvent(this, folder));
private void fireFolderRemoved(Folder folder) { final FolderRepositoryEvent e = new FolderRepositoryEvent(this, folder); // Call to listener support // listenerSupport.folderRemoved(e); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.folderRemoved(e); } } }
final FolderRepositoryEvent e = new FolderRepositoryEvent(this); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.scansFinished(e); } }
listenerSupport.scansFinished(new FolderRepositoryEvent(this));
private void fireScansFinished() { final FolderRepositoryEvent e = new FolderRepositoryEvent(this); // Call to listener support // listenerSupport.scansFinished(e); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.scansFinished(e); } } }
final FolderRepositoryEvent e = new FolderRepositoryEvent(this); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.scansStarted(e); } }
listenerSupport.scansStarted(new FolderRepositoryEvent(this));
private void fireScansStarted() { final FolderRepositoryEvent e = new FolderRepositoryEvent(this); // Call to listener support // listenerSupport.scansStarted(e); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.scansStarted(e); } } }
final FolderRepositoryEvent e = new FolderRepositoryEvent(this, info); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.unjoinedFolderAdded(e); } }
listenerSupport.unjoinedFolderAdded(new FolderRepositoryEvent(this, info));
private void fireUnjoinedFolderAdded(FolderInfo info) { final FolderRepositoryEvent e = new FolderRepositoryEvent(this, info); // Call to listener support // listenerSupport.unjoinedFolderAdded(e); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.unjoinedFolderAdded(e); } } }
final FolderRepositoryEvent e = new FolderRepositoryEvent(this, info); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.unjoinedFolderRemoved(e); } }
listenerSupport.unjoinedFolderRemoved(new FolderRepositoryEvent(this, info));
private void fireUnjoinedFolderRemoved(FolderInfo info) { final FolderRepositoryEvent e = new FolderRepositoryEvent(this, info); // Call to listener support // listenerSupport.unjoinedFolderRemoved(e); synchronized (listeners) { for (FolderRepositoryListener listener : listeners) { listener.unjoinedFolderRemoved(e); } } }
log().verbose(size + " Folders now in the network");
if (logVerbose) { log().verbose(size + " Folders now in the network"); }
private void processNetworkFolderList(NetworkFolderList netFolders) { List newFolders = new ArrayList(); // Update internal network folder database synchronized (networkFolders) { for (int i = 0; i < netFolders.folderDetails.length; i++) { FolderDetails remoteDetails = netFolders.folderDetails[i]; FolderDetails localDetails = networkFolders.get(remoteDetails .getFolderInfo()); if (!remoteDetails.isValid()) { // Skip if remote details are not valid anymore continue; } boolean changed = false; if (localDetails == null) { localDetails = new FolderDetails(remoteDetails .getFolderInfo()); // We do not have that folder details, add it networkFolders.put(localDetails.getFolderInfo(), remoteDetails); newFolders.add(remoteDetails); changed = true; } else { // Merge our details with remote one changed = localDetails.merge(remoteDetails); } // Connect to new users if (hasJoinedFolder(localDetails.getFolderInfo()) && changed && localDetails.isSomeoneOnline(getController())) { log().debug( "Triggering connecto to members of joined folder " + localDetails.getFolderInfo().name); localDetails.connectToMembers(getController(), false); } } } // Remove inactive folders cleanupNetworkFoldersIfNessesary(); // Add new folders to unjoined list for (Iterator it = newFolders.iterator(); it.hasNext();) { FolderDetails foDetails = (FolderDetails) it.next(); addUnjoinedFolder(foDetails); } int size; synchronized(networkFolders) { size = networkFolders.size(); } log().verbose(size + " Folders now in the network"); }
log().verbose( "Processing new folderlist from " + source.getNick() + ", he has joined " + folderList.folders.length + " public folder");
if (logVerbose) { log().verbose( "Processing new folderlist from " + source.getNick() + ", he has joined " + folderList.folders.length + " public folder"); }
public void receivedFolderList(Member source, FolderList folderList) { if (folderList.isEmpty()) { // Ignore return; } log().verbose( "Processing new folderlist from " + source.getNick() + ", he has joined " + folderList.folders.length + " public folder"); // Proceess his folder list Set remoteFolders = new HashSet(Arrays.asList(folderList.folders)); MemberInfo sourceInfo = source.getInfo(); Set removedUnjoinedFolders = new HashSet(); synchronized (networkFolders) { for (Iterator it = networkFolders.values().iterator(); it.hasNext();) { FolderDetails localDetails = (FolderDetails) it.next(); if (remoteFolders.contains(localDetails.getFolderInfo())) { if (!localDetails.hasMember(sourceInfo)) { localDetails.addMember(sourceInfo); } // Folder found in local db, remove from list remoteFolders.remove(localDetails.getFolderInfo()); } else { // Remove from folder localDetails.removeMember(sourceInfo); } } // Add unkown/new folders for (Iterator it = remoteFolders.iterator(); it.hasNext();) { FolderInfo foInfo = (FolderInfo) it.next(); FolderDetails foDetails = new FolderDetails(foInfo); foDetails.addMember(sourceInfo); networkFolders.put(foInfo, foDetails); } } // Remove not longer used unjoined folders for (Iterator it = removedUnjoinedFolders.iterator(); it.hasNext();) { FolderDetails foDetails = (FolderDetails) it.next(); fireUnjoinedFolderRemoved(foDetails.getFolderInfo()); } // Cleanup folders cleanupNetworkFoldersIfNessesary(); // Send source folders details which are intersting for him if (getController().getMySelf().isSupernode() || source.isFriend()) { sendPreparedNetworkFolderList(source, folderList); } int size; synchronized(networkFolders) { size = networkFolders.size(); } log().verbose(size + " Folders now in the network"); }
log().verbose(size + " Folders now in the network");
if (logVerbose) { log().verbose(size + " Folders now in the network"); }
public void receivedFolderList(Member source, FolderList folderList) { if (folderList.isEmpty()) { // Ignore return; } log().verbose( "Processing new folderlist from " + source.getNick() + ", he has joined " + folderList.folders.length + " public folder"); // Proceess his folder list Set remoteFolders = new HashSet(Arrays.asList(folderList.folders)); MemberInfo sourceInfo = source.getInfo(); Set removedUnjoinedFolders = new HashSet(); synchronized (networkFolders) { for (Iterator it = networkFolders.values().iterator(); it.hasNext();) { FolderDetails localDetails = (FolderDetails) it.next(); if (remoteFolders.contains(localDetails.getFolderInfo())) { if (!localDetails.hasMember(sourceInfo)) { localDetails.addMember(sourceInfo); } // Folder found in local db, remove from list remoteFolders.remove(localDetails.getFolderInfo()); } else { // Remove from folder localDetails.removeMember(sourceInfo); } } // Add unkown/new folders for (Iterator it = remoteFolders.iterator(); it.hasNext();) { FolderInfo foInfo = (FolderInfo) it.next(); FolderDetails foDetails = new FolderDetails(foInfo); foDetails.addMember(sourceInfo); networkFolders.put(foInfo, foDetails); } } // Remove not longer used unjoined folders for (Iterator it = removedUnjoinedFolders.iterator(); it.hasNext();) { FolderDetails foDetails = (FolderDetails) it.next(); fireUnjoinedFolderRemoved(foDetails.getFolderInfo()); } // Cleanup folders cleanupNetworkFoldersIfNessesary(); // Send source folders details which are intersting for him if (getController().getMySelf().isSupernode() || source.isFriend()) { sendPreparedNetworkFolderList(source, folderList); } int size; synchronized(networkFolders) { size = networkFolders.size(); } log().verbose(size + " Folders now in the network"); }
synchronized (listeners) { listeners.remove(listener); }
ListenerSupportFactory.removeListener(listenerSupport, listener);
public void removeFolderRepositoryListener(FolderRepositoryListener listener) { // ListenerSupportFactory.removeListener(listenerSupport, listener); synchronized (listeners) { listeners.remove(listener); } }
log().error("setSuspendFireEvents Not Implemented ");
ListenerSupportFactory.setSuspended(listenerSupport, suspended); log().debug("setSuspendFireEvents: " + suspended);
public void setSuspendFireEvents(boolean suspended) { // ListenerSupportFactory.setSuspended(listenerSupport, suspended); // log().debug("setSuspendFireEvents: " + suspended); log().error("setSuspendFireEvents Not Implemented "); }
log().verbose("All Nodes: Synchronize Foldermemberships");
if (logVerbose) { log().verbose("All Nodes: Synchronize Foldermemberships"); }
private void synchronizeAllFolderMemberships() { if (!started) { log().verbose( "Not synchronizing Foldermemberships, repo not started, yet"); } log().verbose("All Nodes: Synchronize Foldermemberships"); Member[] nodes = getController().getNodeManager().getNodes(); FolderInfo[] myJoinedFolders = getJoinedFolderInfos(); for (int i = 0; i < nodes.length; i++) { nodes[i].synchronizeFolderMemberships(myJoinedFolders); } }
folderBart.scanLocalFiles(true);
folderBart.forceScanOnNextMaintenance(); folderBart.maintain();
public void testStartAutoDownloadInSilentMode() throws FolderException { FolderInfo testFolder = new FolderInfo("testFolder", IdGenerator .makeId(), true); // Prepare folder on "host" Bart. Folder folderBart = getContollerBart().getFolderRepository() .createFolder(testFolder, new File(FOLDERDIR1)); TestHelper.createRandomFile(new File(FOLDERDIR1)); TestHelper.createRandomFile(new File(FOLDERDIR1)); TestHelper.createRandomFile(new File(FOLDERDIR1)); folderBart.scanLocalFiles(true); // Set lisa in silent mode getContollerLisa().setSilentMode(true); // Now let lisa join with auto-download final Folder folderLisa = getContollerLisa().getFolderRepository() .createFolder(testFolder, new File(FOLDERDIR2), SyncProfile.AUTO_DOWNLOAD_FROM_ALL, false); TestHelper.waitForCondition(50, new TestHelper.Condition() { public boolean reached() { return folderLisa.getFiles().length >= 3; } }); assertEquals(3, folderLisa.getFilesCount()); assertEquals(4, folderLisa.getLocalBase().list().length); }
storeNodes1(getController().getConfigName() + ".nodes", new NodeList( this, false)); storeNodes1(getController().getConfigName() + ".nodes.backup", new NodeList(this, false));
storeNodes1(getController().getConfigName() + ".nodes", false); storeNodes1(getController().getConfigName() + ".nodes.backup", false);
private void storeNodes() { // storeNodes0(getController().getConfigName() + ".nodes", false); storeNodes1(getController().getConfigName() + ".nodes", new NodeList( this, false)); storeNodes1(getController().getConfigName() + ".nodes.backup", new NodeList(this, false)); }
private void storeNodes1(String filename, NodeList nodeList) {
private void storeNodes1(String filename, boolean onlySuperNodes) {
private void storeNodes1(String filename, NodeList nodeList) { File nodesFile = new File(Controller.getMiscFilesLocation(), filename); // Add myself to know nodes nodeList.getNodeList().add(getMySelf().getInfo()); if (nodeList.getNodeList().isEmpty()) { log().verbose("Not storing list of nodes, none known"); return; } log().debug("Saving known nodes/friends"); try { nodeList.save(nodesFile); } catch (IOException e) { log().warn( "Unable to write supernodes to file '" + filename + "'. " + e.getMessage()); log().verbose(e); } }
if (!nodesFile.getParentFile().exists()) { log().warn("Unable to create store nodes!"); return; } NodeList nodeList = new NodeList(this, onlySuperNodes);
private void storeNodes1(String filename, NodeList nodeList) { File nodesFile = new File(Controller.getMiscFilesLocation(), filename); // Add myself to know nodes nodeList.getNodeList().add(getMySelf().getInfo()); if (nodeList.getNodeList().isEmpty()) { log().verbose("Not storing list of nodes, none known"); return; } log().debug("Saving known nodes/friends"); try { nodeList.save(nodesFile); } catch (IOException e) { log().warn( "Unable to write supernodes to file '" + filename + "'. " + e.getMessage()); log().verbose(e); } }
storeNodes1(getController().getConfigName() + "-Supernodes.nodes", new NodeList(this, true));
storeNodes1(getController().getConfigName() + "-Supernodes.nodes", true);
private void storeSupernodes() { storeNodes1(getController().getConfigName() + "-Supernodes.nodes", new NodeList(this, true)); // storeNodes0(getController().getConfigName() + "-Supernodes.nodes", // true); }
List allFiles = new LinkedList();
List<FileInfo> allFiles = new LinkedList<FileInfo>();
private void createDisplayList() { List allFiles = new LinkedList(); // java 1.5: // Collections.addAll(allFiles, fileInfos); for (int i = 0; i < fileInfos.length; i++) { allFiles.add(fileInfos[i]); } List filteredFiles = fileFilterModel.filter(null, allFiles); //quick fix null pointer exception //FIXME: need to follow same patern as in DirectoryTableModel if (filteredFiles != null) { synchronized (displayList) { displayList.clear(); displayList.addAll(filteredFiles); } sort(); } }
public Class getColumnClass(int columnIndex) {
public Class<FileInfo> getColumnClass(int columnIndex) {
public Class getColumnClass(int columnIndex) { return FileInfo.class; }
uploads.add(event.getUpload());
int index = -1; synchronized (uploads) { if (uploads.contains(event.getUpload())) { index = removeUpload(event.getUpload()); } uploads.add(event.getUpload()); } if (index >= 0) { rowsUpdated(0, index); }
public void uploadRequested(TransferManagerEvent event) { uploads.add(event.getUpload()); rowAdded(); }
getFile().getFolder(getController().getFolderRepository()) .getStatistic().getDownloadCounter().chunkTransferred(chunk);
public synchronized void addChunk(FileChunk chunk) { if (chunk == null) { return; } if (!isStarted()) { // donwload begins to start setStarted(); } lastTouch.setTime(System.currentTimeMillis()); if (super.isBroken()) { return; } // check tempfile File tempFile = getTempFile(); // create subdirs File subdirs = tempFile.getParentFile(); if (!subdirs.exists()) { //TODO check if works else give warning because of invalid directory name // and move to blacklist subdirs.mkdirs(); log().verbose("Subdirectory created: " + subdirs); } if (tempFile.exists() && chunk.offset == 0) { // download started from offset 0 new, remove file, // "erase and rewind" ;) if (!tempFile.delete()) { log().error( "Unable to removed broken tempfile for download: " + tempFile.getAbsolutePath()); tempFileError = true; return; } } if (!tempFile.exists()) { try { // TODO check if works else give warning because of invalid filename or diskfull? // and move to blacklist tempFile.createNewFile(); } catch (IOException e) { log().error( "Unable to create/open tempfile for donwload: " + tempFile.getAbsolutePath() + ". " + e.getMessage()); tempFileError = true; return; } } // log().warn("Tempfile exists ? " + tempFile.exists() + ", " + // tempFile.getAbsolutePath()); if (!tempFile.canWrite()) { log().error( "Unable to write to tempfile for donwload: " + tempFile.getAbsolutePath()); tempFileError = true; return; } // check chunk validity if (chunk.offset < 0 || chunk.offset > getFile().getSize() || chunk.data == null || (chunk.data.length + chunk.offset > getFile().getSize()) || chunk.offset != tempFile.length()) { String reason = "unknown"; if (chunk.offset < 0 || chunk.offset > getFile().getSize()) { reason = "Illegal offset " + chunk.offset; } if (chunk.data == null) { reason = "Chunk data null"; } if (chunk.data.length + chunk.offset > getFile().getSize()) { reason = "Chunk exceeds filesize"; } if (chunk.offset != tempFile.length()) { reason = "Offset does not matches the current tempfile size. offset: " + chunk.offset + ", filesize: " + tempFile.length(); } log().error( "Received illegal chunk. " + chunk + ". Reason: " + reason); // Abort dl abort(); return; } try { // add bytes to transferred status getCounter().chunkTransferred(chunk); // FIXME: Parse offset/not expect linar download OutputStream fOut = new BufferedOutputStream(new FileOutputStream( tempFile, true)); fOut.write(chunk.data); fOut.close(); // Set lastmodified date of file info /* * log().warn( "Setting lastmodified of tempfile for: " + * getFile().toDetailString()); */ tempFile.setLastModified(getFile().getModifiedDate().getTime()); log().verbose( "Wrote " + chunk.data.length + " bytes to tempfile " + tempFile.getAbsolutePath()); } catch (IOException e) { // TODO: Disk full warning ? log().error( "Error while writing to tempfile for donwload: " + tempFile.getAbsolutePath() + ". " + e.getMessage()); log().verbose(e); tempFileError = true; return; } // FIXME: currently the trigger to stop dl is // the arrival of a chunk which matches exactly to // the last chunk of the file if (!completed) { completed = chunk.data.length + chunk.offset == getFile().getSize(); if (completed) { // Finish download finish(); } } }
b.setBorder(Borders.createEmptyBorder("0, 3ldu,0, 3dlu"));
b.setBorder(Borders.createEmptyBorder("0, 1dlu, 0, 2dlu"));
private JPanel buildStatusBar(CellConstraints cc) { FormLayout layout = new FormLayout( "pref, fill:pref:grow, pref, 3dlu, pref, 3dlu, pref", "pref"); DefaultFormBuilder b = new DefaultFormBuilder(layout); b.setBorder(Borders.createEmptyBorder("0, 3ldu,0, 3dlu")); b.add(onlineStateInfo, cc.xy(1, 1)); JSeparator sep1 = new JSeparator(SwingConstants.VERTICAL); sep1.setPreferredSize(new Dimension(2, 12)); b.add(downStats, cc.xy(3, 1)); b.add(sep1, cc.xy(5, 1)); b.add(upStats, cc.xy(7, 1)); return b.getPanel(); }
folderAtBart.scanLocalFiles(true);
folderAtBart.forceScanOnNextMaintenance(); folderAtBart.maintain();
public void testDeletionSyncScenario() { // file "host" and "client" folderAtBart.setSyncProfile(SyncProfile.MANUAL_DOWNLOAD); folderAtLisa.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); File file1 = TestHelper .createTestFile(folderAtBart.getLocalBase(), "/TestFile.txt", "This are the contents of the testfile".getBytes()); File file2 = TestHelper.createTestFile(folderAtBart.getLocalBase(), "/TestFile2.txt", "This are the contents of the 2nd testfile" .getBytes()); File file3 = TestHelper.createTestFile(folderAtBart.getLocalBase(), "/sub/sub/TestFile3.txt", "This are the contents of the 3nd testfile".getBytes()); // Let him scan the new content folderAtBart.scanLocalFiles(true); assertEquals(3, folderAtBart.getFilesCount()); // Give them time to copy TestHelper.waitForCondition(20, new Condition() { public boolean reached() { return folderAtLisa.getFilesCount() >= 3; } }); // Test ;) assertEquals(3, folderAtLisa.getFilesCount()); // Version should be the 0 for new files for (FileInfo fileInfo : folderAtBart.getFiles()) { assertEquals(0, fileInfo.getVersion()); } // Version should be the 0 for new files for (FileInfo fileInfo : folderAtLisa.getFiles()) { assertEquals(0, fileInfo.getVersion()); } assertEquals(getContollerBart().getRecycleBin().getSize(), 0); assertEquals(getContollerLisa().getRecycleBin().getSize(), 0); file1.delete(); file2.delete(); file3.delete(); assertFalse(file1.exists()); assertFalse(file2.exists()); assertFalse(file3.exists()); // Let him scan the new content folderAtBart.scanLocalFiles(true); // all 3 must be deleted FileInfo[] folder1Files = folderAtBart.getFiles(); for (FileInfo fileInfo : folder1Files) { assertTrue(fileInfo.isDeleted()); assertEquals(1, fileInfo.getVersion()); } // Give them time to remote deletion TestHelper.waitMilliSeconds(3000); // all 3 must be deleted remote FileInfo[] folder2Files = folderAtLisa.getFiles(); for (FileInfo fileInfo : folder2Files) { assertTrue(fileInfo.isDeleted()); assertEquals(1, fileInfo.getVersion()); File file = folderAtLisa.getDiskFile(fileInfo); assertFalse(file.exists()); } assertEquals(getContollerLisa().getRecycleBin().getSize(), 3); // switch profiles folderAtLisa.setSyncProfile(SyncProfile.MANUAL_DOWNLOAD); folderAtBart.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); RecycleBin recycleBin = getContollerLisa().getRecycleBin(); List<FileInfo> deletedFilesAtLisa = getContollerLisa().getRecycleBin() .getAllRecycledFiles(); for (FileInfo deletedFileAtLisa : deletedFilesAtLisa) { recycleBin.restoreFromRecycleBin(deletedFileAtLisa); } // all 3 must not be deleted at folder2 for (FileInfo fileAtLisa : folderAtLisa.getFiles()) { assertFalse(fileAtLisa.isDeleted()); assertEquals(2, fileAtLisa.getVersion()); assertEquals(getContollerLisa().getMySelf().getInfo(), fileAtLisa .getModifiedBy()); File file = folderAtLisa.getDiskFile(fileAtLisa); assertTrue(file.exists()); assertEquals(fileAtLisa.getSize(), file.length()); assertEquals(fileAtLisa.getModifiedDate().getTime(), file .lastModified()); } getContollerBart().getFolderRepository().getFileRequestor() .triggerFileRequesting(); // Give them time to undelete sync (means downloading;) TestHelper.waitMilliSeconds(3000); // all 3 must not be deleted anymore at folder1 for (FileInfo fileInfo : folderAtBart.getFiles()) { assertEquals(2, fileInfo.getVersion()); assertFalse(fileInfo.isDeleted()); assertTrue(fileInfo.getDiskFile( getContollerBart().getFolderRepository()).exists()); } // Version should be the same (file did not change, it was only deleted // and restored!) for (FileInfo fileInfo : folderAtLisa.getFiles()) { assertEquals(2, fileInfo.getVersion()); assertFalse(fileInfo.isDeleted()); assertTrue(fileInfo.getDiskFile( getContollerLisa().getFolderRepository()).exists()); } }
} folderAtBart.scanLocalFiles(true);
} folderAtBart.forceScanOnNextMaintenance(); folderAtBart.maintain();
public void testMultipleFileDeleteSync() { folderAtBart.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); folderAtLisa.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); final int nFiles = 35; for (int i = 0; i < nFiles; i++) { TestHelper.createRandomFile(folderAtBart.getLocalBase()); } folderAtBart.scanLocalFiles(true); TestHelper.waitForCondition(20, new TestHelper.Condition() { public boolean reached() { return folderAtLisa.getFilesCount() >= nFiles; } }); assertEquals(nFiles, folderAtLisa.getFilesCount()); // Now delete the file at lisa FileInfo[] fInfosLisa = folderAtLisa.getFiles(); for (int i = 0; i < fInfosLisa.length; i++) { assertTrue(fInfosLisa[i].getDiskFile( getContollerLisa().getFolderRepository()).delete()); } folderAtLisa.scanLocalFiles(true); assertEquals(nFiles, folderAtLisa.getFilesCount()); fInfosLisa = folderAtLisa.getFiles(); for (int i = 0; i < fInfosLisa.length; i++) { assertEquals(1, fInfosLisa[i].getVersion()); assertTrue(fInfosLisa[i].isDeleted()); } // Wait to sync the deletions TestHelper.waitForCondition(20, new TestHelper.Condition() { public boolean reached() { return folderAtBart.getFiles()[nFiles - 1].isDeleted(); } }); TestHelper.waitMilliSeconds(500); // Test the correct deletions state at bart assertEquals(nFiles, folderAtBart.getFilesCount()); FileInfo[] fInfosBart = folderAtBart.getFiles(); for (int i = 0; i < fInfosBart.length; i++) { assertTrue(fInfosBart[i].isDeleted()); assertEquals(1, fInfosBart[i].getVersion()); } // Assume only 1 file (=PowerFolder system dir) assertEquals(1, folderAtBart.getLocalBase().list().length); }
folderAtLisa.scanLocalFiles(true);
folderAtLisa.forceScanOnNextMaintenance(); folderAtLisa.maintain();
public void testMultipleFileDeleteSync() { folderAtBart.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); folderAtLisa.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); final int nFiles = 35; for (int i = 0; i < nFiles; i++) { TestHelper.createRandomFile(folderAtBart.getLocalBase()); } folderAtBart.scanLocalFiles(true); TestHelper.waitForCondition(20, new TestHelper.Condition() { public boolean reached() { return folderAtLisa.getFilesCount() >= nFiles; } }); assertEquals(nFiles, folderAtLisa.getFilesCount()); // Now delete the file at lisa FileInfo[] fInfosLisa = folderAtLisa.getFiles(); for (int i = 0; i < fInfosLisa.length; i++) { assertTrue(fInfosLisa[i].getDiskFile( getContollerLisa().getFolderRepository()).delete()); } folderAtLisa.scanLocalFiles(true); assertEquals(nFiles, folderAtLisa.getFilesCount()); fInfosLisa = folderAtLisa.getFiles(); for (int i = 0; i < fInfosLisa.length; i++) { assertEquals(1, fInfosLisa[i].getVersion()); assertTrue(fInfosLisa[i].isDeleted()); } // Wait to sync the deletions TestHelper.waitForCondition(20, new TestHelper.Condition() { public boolean reached() { return folderAtBart.getFiles()[nFiles - 1].isDeleted(); } }); TestHelper.waitMilliSeconds(500); // Test the correct deletions state at bart assertEquals(nFiles, folderAtBart.getFilesCount()); FileInfo[] fInfosBart = folderAtBart.getFiles(); for (int i = 0; i < fInfosBart.length; i++) { assertTrue(fInfosBart[i].isDeleted()); assertEquals(1, fInfosBart[i].getVersion()); } // Assume only 1 file (=PowerFolder system dir) assertEquals(1, folderAtBart.getLocalBase().list().length); }
folderAtBart.scanLocalFiles(true);
folderAtBart.forceScanOnNextMaintenance(); folderAtBart.maintain();
public void testSingleFileDeleteSync() { folderAtBart.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); folderAtLisa.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); File testFileBart = TestHelper.createRandomFile(folderAtBart .getLocalBase()); folderAtBart.scanLocalFiles(true); FileInfo fInfoBart = folderAtBart.getFiles()[0]; TestHelper.waitForCondition(10, new TestHelper.Condition() { public boolean reached() { return folderAtLisa.getFilesCount() >= 1; } }); assertEquals(1, folderAtLisa.getFilesCount()); FileInfo fInfoLisa = folderAtLisa.getFiles()[0]; File testFileLisa = fInfoLisa.getDiskFile(getContollerLisa() .getFolderRepository()); assertTrue(fInfoLisa.completelyIdentical(fInfoBart)); assertEquals(testFileBart.length(), testFileLisa.length()); // Now delete the file at lisa assertTrue(testFileLisa.delete()); folderAtLisa.scanLocalFiles(true); assertEquals(1, folderAtLisa.getFilesCount()); assertEquals(1, folderAtLisa.getFiles()[0].getVersion()); assertTrue(folderAtLisa.getFiles()[0].isDeleted()); TestHelper.waitForCondition(10, new TestHelper.Condition() { public boolean reached() { return folderAtBart.getFiles()[0].isDeleted(); } }); assertEquals(1, folderAtBart.getFilesCount()); assertEquals(1, folderAtBart.getFiles()[0].getVersion()); assertTrue(folderAtBart.getFiles()[0].isDeleted()); // Assume only 1 file (=PowerFolder system dir) assertEquals(1, folderAtBart.getLocalBase().list().length); }
folderAtLisa.scanLocalFiles(true);
folderAtLisa.forceScanOnNextMaintenance(); folderAtLisa.maintain();
public void testSingleFileDeleteSync() { folderAtBart.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); folderAtLisa.setSyncProfile(SyncProfile.SYNCHRONIZE_PCS); File testFileBart = TestHelper.createRandomFile(folderAtBart .getLocalBase()); folderAtBart.scanLocalFiles(true); FileInfo fInfoBart = folderAtBart.getFiles()[0]; TestHelper.waitForCondition(10, new TestHelper.Condition() { public boolean reached() { return folderAtLisa.getFilesCount() >= 1; } }); assertEquals(1, folderAtLisa.getFilesCount()); FileInfo fInfoLisa = folderAtLisa.getFiles()[0]; File testFileLisa = fInfoLisa.getDiskFile(getContollerLisa() .getFolderRepository()); assertTrue(fInfoLisa.completelyIdentical(fInfoBart)); assertEquals(testFileBart.length(), testFileLisa.length()); // Now delete the file at lisa assertTrue(testFileLisa.delete()); folderAtLisa.scanLocalFiles(true); assertEquals(1, folderAtLisa.getFilesCount()); assertEquals(1, folderAtLisa.getFiles()[0].getVersion()); assertTrue(folderAtLisa.getFiles()[0].isDeleted()); TestHelper.waitForCondition(10, new TestHelper.Condition() { public boolean reached() { return folderAtBart.getFiles()[0].isDeleted(); } }); assertEquals(1, folderAtBart.getFilesCount()); assertEquals(1, folderAtBart.getFiles()[0].getVersion()); assertTrue(folderAtBart.getFiles()[0].isDeleted()); // Assume only 1 file (=PowerFolder system dir) assertEquals(1, folderAtBart.getLocalBase().list().length); }
return SideImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText());
return SideImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText().toUpperCase());
public SideImage fromToken(Tok tok) { return SideImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText()); }
return TimeInForceImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText());
return TimeInForceImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText().toUpperCase());
public TimeInForceImage fromToken(Tok tok) { return TimeInForceImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText()); }
return CommandImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText());
return CommandImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText().toUpperCase());
public CommandImage fromToken(Tok tok) { return CommandImage.fromName(((TypedToken<TokenType>)tok.getToken()).getText()); }
FIXDataDictionaryManager.loadDictionary(FIXDataDictionaryManager.FIX_4_2_BEGIN_STRING);
FIXDataDictionaryManager.setFIXVersion(FIXDataDictionaryManager.FIX_4_2_BEGIN_STRING);
public Object run(Object args) throws Exception { FIXDataDictionaryManager.loadDictionary(FIXDataDictionaryManager.FIX_4_2_BEGIN_STRING); fixMessageHistory = new FIXMessageHistory(); jmsConnector = new JMSConnector(); orderManager = new OrderManager(idFactory, fixMessageHistory); Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) { return IPlatformRunnable.EXIT_RESTART; } return IPlatformRunnable.EXIT_OK; } finally { display.dispose(); } }
|| node.isUnableToConnect())
|| node.isUnableToConnect() || node.getReconnectAddress() == null)
public boolean markNodeForImmediateReconnection(Member node) { if (node.isConnected() || node.isReconnecting() || node.isMySelf() || node.isUnableToConnect()) { // Not reconnect nesseary return false; } if (getController().isLanOnly() && !NetworkUtil.isOnLanOrLoopback(node.getReconnectAddress() .getAddress())) { // no strangers in lan only mode return false; } // TODO: This code is also in buildReconnectionQueue // Offline limit time, all nodes before this time are not getting // reconnected Date offlineLimitTime = new Date(System.currentTimeMillis() - Constants.MAX_NODE_OFFLINE_TIME); // Check if node was offline too long Date lastConnectTime = node.getLastNetworkConnectTime(); boolean offlineTooLong = true; offlineTooLong = lastConnectTime != null ? lastConnectTime .before(offlineLimitTime) : true; if (offlineTooLong) { return false; } if (logVerbose) { log().verbose("Marking node for immediate reconnect: " + node); } synchronized (reconnectionQueue) { // Remove node reconnectionQueue.remove(node); // Add at start reconnectionQueue.add(0, node); } return true; }
List<FileInfo> filesToRemove = new ArrayList();
List<FileInfo> filesToRemove = new ArrayList<FileInfo>();
public Object construct() { boolean dirRemoved = false; List<FileInfo> filesToRemove = new ArrayList(); for (Object object : toRemove) { if (object instanceof FileInfo) { filesToRemove.add((FileInfo) object); } else if (object instanceof Directory) { Directory directoryToRemove = (Directory) object; if (!moveToRecycleBin(directoryToRemove)) { log().error( "move to recyclebin failed for:" + directoryToRemove); } dirRemoved = true; } } FileInfo[] filesToRemoveArray = new FileInfo[filesToRemove .size()]; filesToRemoveArray = filesToRemove .toArray(filesToRemoveArray); if (filesToRemoveArray.length > 0) { folder.removeFilesLocal(filesToRemoveArray); } if (dirRemoved) { // TODO Schaatser please check this folder.maintain(); } return null; }
List<FileInfo> existingFiles = new ArrayList();
List<FileInfo> existingFiles = new ArrayList<FileInfo>();
private boolean moveToRecycleBin(Directory directory) { FolderRepository repo = directory.getRootFolder().getController() .getFolderRepository(); List<Directory> subs = directory.listSubDirectories(); for (Directory sub : subs) { moveToRecycleBin(sub); } List<FileInfo> files = directory.getFiles(); List<FileInfo> existingFiles = new ArrayList(); for (FileInfo fileInfo : files) { File file = fileInfo.getDiskFile(repo); if (file.exists()) { existingFiles.add(fileInfo); } } FileInfo[] filesArray = new FileInfo[existingFiles.size()]; filesArray = existingFiles.toArray(filesArray); directory.getRootFolder().removeFilesLocal(filesArray); return true; }
boolean neverAsk = getController().getPreferences() .getBoolean(Member.CONFIG_ASKFORFRIENDSHIP, false);
boolean neverAsk = PreferencesEntry.CONFIG_ASKFORFRIENDSHIP.getValueBoolean(getController());
public void askForFriendship( AskForFriendshipEvent askForFriendshipEvent) { final Member member = askForFriendshipEvent.getMember(); final Set<FolderInfo> joinedFolders = askForFriendshipEvent.getJoinedFolders(); boolean neverAsk = getController().getPreferences() .getBoolean(Member.CONFIG_ASKFORFRIENDSHIP, false); if (getController().isUIOpen() && !member.isFriend() && !neverAsk && !member.askedForFriendship()) { // Okay we are asking for friendship now member.setAskedForFriendship(true); Runnable friendAsker = new Runnable() { public void run() { getController().getUIController().getBlinkManager() .setBlinkingTrayIcon(Icons.ST_NODE); String folderString = ""; for (FolderInfo folderInfo : joinedFolders) { String secrectOrPublicText; if (folderInfo.secret) { secrectOrPublicText = Translation .getTranslation("folderjoin.secret"); } else { secrectOrPublicText = Translation .getTranslation("folderjoin.public"); } folderString += folderInfo.name + " (" + secrectOrPublicText + ")\n"; } Object[] options = { Translation .getTranslation("dialog.addmembertofriendlist.button.yes"), Translation .getTranslation("dialog.addmembertofriendlist.button.no"), Translation .getTranslation("dialog.addmembertofriendlist.button.no_neveraskagain")}; String text = Translation.getTranslation( "dialog.addmembertofriendlist.question", member.getNick(), folderString) + "\n\n" + Translation .getTranslation("dialog.addmembertofriendlist.explain"); // if mainframe is hidden we should wait till its opened int result = JOptionPane .showOptionDialog(getController().getUIController() .getMainFrame().getUIComponent(), text, Translation .getTranslation( "dialog.addmembertofriendlist.title", member.getNick()), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); member.setFriend(result == 0); if (result == 2) { member.setFriend(false); // dont ask me again getController().getPreferences().putBoolean(Member.CONFIG_ASKFORFRIENDSHIP, false); } getController().getUIController().getBlinkManager() .setBlinkingTrayIcon(null); } }; SwingUtilities.invokeLater(friendAsker); } else { member.setFriend(false); } }
getController().getPreferences().putBoolean(Member.CONFIG_ASKFORFRIENDSHIP, false);
PreferencesEntry.CONFIG_ASKFORFRIENDSHIP.setValue(getController(), false);
public void askForFriendship( AskForFriendshipEvent askForFriendshipEvent) { final Member member = askForFriendshipEvent.getMember(); final Set<FolderInfo> joinedFolders = askForFriendshipEvent.getJoinedFolders(); boolean neverAsk = getController().getPreferences() .getBoolean(Member.CONFIG_ASKFORFRIENDSHIP, false); if (getController().isUIOpen() && !member.isFriend() && !neverAsk && !member.askedForFriendship()) { // Okay we are asking for friendship now member.setAskedForFriendship(true); Runnable friendAsker = new Runnable() { public void run() { getController().getUIController().getBlinkManager() .setBlinkingTrayIcon(Icons.ST_NODE); String folderString = ""; for (FolderInfo folderInfo : joinedFolders) { String secrectOrPublicText; if (folderInfo.secret) { secrectOrPublicText = Translation .getTranslation("folderjoin.secret"); } else { secrectOrPublicText = Translation .getTranslation("folderjoin.public"); } folderString += folderInfo.name + " (" + secrectOrPublicText + ")\n"; } Object[] options = { Translation .getTranslation("dialog.addmembertofriendlist.button.yes"), Translation .getTranslation("dialog.addmembertofriendlist.button.no"), Translation .getTranslation("dialog.addmembertofriendlist.button.no_neveraskagain")}; String text = Translation.getTranslation( "dialog.addmembertofriendlist.question", member.getNick(), folderString) + "\n\n" + Translation .getTranslation("dialog.addmembertofriendlist.explain"); // if mainframe is hidden we should wait till its opened int result = JOptionPane .showOptionDialog(getController().getUIController() .getMainFrame().getUIComponent(), text, Translation .getTranslation( "dialog.addmembertofriendlist.title", member.getNick()), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); member.setFriend(result == 0); if (result == 2) { member.setFriend(false); // dont ask me again getController().getPreferences().putBoolean(Member.CONFIG_ASKFORFRIENDSHIP, false); } getController().getUIController().getBlinkManager() .setBlinkingTrayIcon(null); } }; SwingUtilities.invokeLater(friendAsker); } else { member.setFriend(false); } }
getController().getPreferences().putBoolean(Member.CONFIG_ASKFORFRIENDSHIP, false);
PreferencesEntry.CONFIG_ASKFORFRIENDSHIP.setValue(getController(), false);
public void run() { getController().getUIController().getBlinkManager() .setBlinkingTrayIcon(Icons.ST_NODE); String folderString = ""; for (FolderInfo folderInfo : joinedFolders) { String secrectOrPublicText; if (folderInfo.secret) { secrectOrPublicText = Translation .getTranslation("folderjoin.secret"); } else { secrectOrPublicText = Translation .getTranslation("folderjoin.public"); } folderString += folderInfo.name + " (" + secrectOrPublicText + ")\n"; } Object[] options = { Translation .getTranslation("dialog.addmembertofriendlist.button.yes"), Translation .getTranslation("dialog.addmembertofriendlist.button.no"), Translation .getTranslation("dialog.addmembertofriendlist.button.no_neveraskagain")}; String text = Translation.getTranslation( "dialog.addmembertofriendlist.question", member.getNick(), folderString) + "\n\n" + Translation .getTranslation("dialog.addmembertofriendlist.explain"); // if mainframe is hidden we should wait till its opened int result = JOptionPane .showOptionDialog(getController().getUIController() .getMainFrame().getUIComponent(), text, Translation .getTranslation( "dialog.addmembertofriendlist.title", member.getNick()), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); member.setFriend(result == 0); if (result == 2) { member.setFriend(false); // dont ask me again getController().getPreferences().putBoolean(Member.CONFIG_ASKFORFRIENDSHIP, false); } getController().getUIController().getBlinkManager() .setBlinkingTrayIcon(null); }
aMessage.getHeader().setField(new SenderCompID("send-dude")); aMessage.getHeader().setField(new TargetCompID("target-dude"));
public static Message getTestableExecutionReport() { Message aMessage = FIXMessageUtil.newExecutionReport(new InternalID("456"), CL_ORD_ID, "987", ExecTransType.STATUS, ExecType.PARTIAL_FILL, OrdStatus.PARTIALLY_FILLED, Side.BUY, new BigDecimal(1000), new BigDecimal("12.3"), new BigDecimal(500), new BigDecimal("12.3"), new BigDecimal(500), new BigDecimal(500), new BigDecimal("12.3"), SYMBOL, null); aMessage.setUtcTimeStamp(TransactTime.FIELD, THE_TRANSACT_TIME); return aMessage; }
queuedMessages = new LinkedList<Message>(); orderManager = new PhotonController(); orderManager.setMessageHistory(messageHistory); orderManager.setIDFactory(idFactory);
photonController = new ImmediatePhotonController(); photonController.setMessageHistory(messageHistory); photonController.setIDFactory(idFactory); photonController.setJmsOperations(new NullJmsOperations());
protected void setUp() throws Exception { idFactory = new InMemoryIDFactory(999); messageHistory = new FIXMessageHistory(); queuedMessages = new LinkedList<Message>(); orderManager = new PhotonController(); orderManager.setMessageHistory(messageHistory); orderManager.setIDFactory(idFactory); }
orderManager.handleInternalMessage(message);
photonController.handleInternalMessage(message);
public void testCancelOneOrder() throws FieldNotFound, MarketceteraException, IncorrectTagValue { String myClOrdID = "MyClOrdID"; Message message = FIXMessageUtil.newMarketOrder(new InternalID(myClOrdID), Side.BUY, BigDecimal.ONE, new MSymbol("QWER"), TimeInForce.DAY, null); orderManager.handleInternalMessage(message); EventList<MessageHolder> history = messageHistory.getAllMessagesList(); assertEquals(1, history.size()); Message cancelMessage = new quickfix.fix42.Message(); cancelMessage.getHeader().setField(new MsgType(MsgType.ORDER_CANCEL_REQUEST)); cancelMessage.setField(new OrigClOrdID(myClOrdID)); cancelMessage.setField(new Symbol("QWER")); orderManager.handleInternalMessage(cancelMessage); history = messageHistory.getAllMessagesList(); assertEquals(2, history.size()); assertEquals(OutgoingMessageHolder.class, history.get(1).getClass()); OutgoingMessageHolder holder = (OutgoingMessageHolder) history.get(1); Message filledCancel = holder.getMessage(); assertEquals(MsgType.ORDER_CANCEL_REQUEST, filledCancel.getHeader().getString(MsgType.FIELD)); FIXDataDictionaryManager.getDictionary().validate(filledCancel); }
orderManager.handleInternalMessage(cancelMessage);
photonController.handleInternalMessage(cancelMessage);
public void testCancelOneOrder() throws FieldNotFound, MarketceteraException, IncorrectTagValue { String myClOrdID = "MyClOrdID"; Message message = FIXMessageUtil.newMarketOrder(new InternalID(myClOrdID), Side.BUY, BigDecimal.ONE, new MSymbol("QWER"), TimeInForce.DAY, null); orderManager.handleInternalMessage(message); EventList<MessageHolder> history = messageHistory.getAllMessagesList(); assertEquals(1, history.size()); Message cancelMessage = new quickfix.fix42.Message(); cancelMessage.getHeader().setField(new MsgType(MsgType.ORDER_CANCEL_REQUEST)); cancelMessage.setField(new OrigClOrdID(myClOrdID)); cancelMessage.setField(new Symbol("QWER")); orderManager.handleInternalMessage(cancelMessage); history = messageHistory.getAllMessagesList(); assertEquals(2, history.size()); assertEquals(OutgoingMessageHolder.class, history.get(1).getClass()); OutgoingMessageHolder holder = (OutgoingMessageHolder) history.get(1); Message filledCancel = holder.getMessage(); assertEquals(MsgType.ORDER_CANCEL_REQUEST, filledCancel.getHeader().getString(MsgType.FIELD)); FIXDataDictionaryManager.getDictionary().validate(filledCancel); }
orderManager.handleInternalMessage(message);
photonController.handleInternalMessage(message);
public void testCancelOneOrderByClOrdID() throws FieldNotFound, MarketceteraException, IncorrectTagValue { String myClOrdID = "MyClOrdID"; Message message = FIXMessageUtil.newMarketOrder(new InternalID(myClOrdID), Side.BUY, BigDecimal.ONE, new MSymbol("QWER"), TimeInForce.DAY, null); orderManager.handleInternalMessage(message); EventList<MessageHolder> history = messageHistory.getAllMessagesList(); assertEquals(1, history.size()); Message cancelMessage = new quickfix.fix42.Message(); cancelMessage.getHeader().setField(new MsgType(MsgType.ORDER_CANCEL_REQUEST)); cancelMessage.setField(new OrigClOrdID(myClOrdID)); cancelMessage.setField(new Symbol("QWER")); orderManager.cancelOneOrderByClOrdID(myClOrdID); history = messageHistory.getAllMessagesList(); assertEquals(2, history.size()); assertEquals(OutgoingMessageHolder.class, history.get(1).getClass()); OutgoingMessageHolder holder = (OutgoingMessageHolder) history.get(1); Message filledCancel = holder.getMessage(); assertEquals(MsgType.ORDER_CANCEL_REQUEST, filledCancel.getHeader().getString(MsgType.FIELD)); FIXDataDictionaryManager.getDictionary().validate(filledCancel); assertEquals(myClOrdID, filledCancel.getString(OrigClOrdID.FIELD)); assertEquals("999", filledCancel.getString(ClOrdID.FIELD)); assertEquals("QWER", filledCancel.getString(Symbol.FIELD)); assertEquals(Side.BUY, filledCancel.getChar(Side.FIELD)); assertEquals(new Date().getTime(), filledCancel.getUtcTimeStamp(TransactTime.FIELD).getTime(), 500); }
orderManager.cancelOneOrderByClOrdID(myClOrdID);
photonController.cancelOneOrderByClOrdID(myClOrdID);
public void testCancelOneOrderByClOrdID() throws FieldNotFound, MarketceteraException, IncorrectTagValue { String myClOrdID = "MyClOrdID"; Message message = FIXMessageUtil.newMarketOrder(new InternalID(myClOrdID), Side.BUY, BigDecimal.ONE, new MSymbol("QWER"), TimeInForce.DAY, null); orderManager.handleInternalMessage(message); EventList<MessageHolder> history = messageHistory.getAllMessagesList(); assertEquals(1, history.size()); Message cancelMessage = new quickfix.fix42.Message(); cancelMessage.getHeader().setField(new MsgType(MsgType.ORDER_CANCEL_REQUEST)); cancelMessage.setField(new OrigClOrdID(myClOrdID)); cancelMessage.setField(new Symbol("QWER")); orderManager.cancelOneOrderByClOrdID(myClOrdID); history = messageHistory.getAllMessagesList(); assertEquals(2, history.size()); assertEquals(OutgoingMessageHolder.class, history.get(1).getClass()); OutgoingMessageHolder holder = (OutgoingMessageHolder) history.get(1); Message filledCancel = holder.getMessage(); assertEquals(MsgType.ORDER_CANCEL_REQUEST, filledCancel.getHeader().getString(MsgType.FIELD)); FIXDataDictionaryManager.getDictionary().validate(filledCancel); assertEquals(myClOrdID, filledCancel.getString(OrigClOrdID.FIELD)); assertEquals("999", filledCancel.getString(ClOrdID.FIELD)); assertEquals("QWER", filledCancel.getString(Symbol.FIELD)); assertEquals(Side.BUY, filledCancel.getChar(Side.FIELD)); assertEquals(new Date().getTime(), filledCancel.getUtcTimeStamp(TransactTime.FIELD).getTime(), 500); }
orderManager.handleInternalMessage(message);
photonController.handleInternalMessage(message);
public void testCancelReplaceOneOrder() throws FieldNotFound, MarketceteraException, IncorrectTagValue { String myClOrdID = "MyClOrdID"; Message message = FIXMessageUtil.newLimitOrder(new InternalID(myClOrdID), Side.BUY, BigDecimal.ONE, new MSymbol("QWER"), BigDecimal.TEN, TimeInForce.DAY, null); orderManager.handleInternalMessage(message); EventList<MessageHolder> history = messageHistory.getAllMessagesList(); assertEquals(1, history.size()); Message cancelReplaceMessage = FIXMessageUtil.newCancelReplaceFromMessage(message); cancelReplaceMessage.setField(new OrigClOrdID(myClOrdID)); orderManager.handleInternalMessage(cancelReplaceMessage); history = messageHistory.getAllMessagesList(); assertEquals(2, history.size()); assertEquals(OutgoingMessageHolder.class, history.get(1).getClass()); OutgoingMessageHolder holder = (OutgoingMessageHolder) history.get(1); Message filledCancelReplace = holder.getMessage(); assertEquals(MsgType.ORDER_CANCEL_REPLACE_REQUEST, filledCancelReplace.getHeader().getString(MsgType.FIELD)); FIXDataDictionaryManager.getDictionary().validate(filledCancelReplace); assertEquals("1", filledCancelReplace.getString(OrderQty.FIELD)); }
orderManager.handleInternalMessage(cancelReplaceMessage);
photonController.handleInternalMessage(cancelReplaceMessage);
public void testCancelReplaceOneOrder() throws FieldNotFound, MarketceteraException, IncorrectTagValue { String myClOrdID = "MyClOrdID"; Message message = FIXMessageUtil.newLimitOrder(new InternalID(myClOrdID), Side.BUY, BigDecimal.ONE, new MSymbol("QWER"), BigDecimal.TEN, TimeInForce.DAY, null); orderManager.handleInternalMessage(message); EventList<MessageHolder> history = messageHistory.getAllMessagesList(); assertEquals(1, history.size()); Message cancelReplaceMessage = FIXMessageUtil.newCancelReplaceFromMessage(message); cancelReplaceMessage.setField(new OrigClOrdID(myClOrdID)); orderManager.handleInternalMessage(cancelReplaceMessage); history = messageHistory.getAllMessagesList(); assertEquals(2, history.size()); assertEquals(OutgoingMessageHolder.class, history.get(1).getClass()); OutgoingMessageHolder holder = (OutgoingMessageHolder) history.get(1); Message filledCancelReplace = holder.getMessage(); assertEquals(MsgType.ORDER_CANCEL_REPLACE_REQUEST, filledCancelReplace.getHeader().getString(MsgType.FIELD)); FIXDataDictionaryManager.getDictionary().validate(filledCancelReplace); assertEquals("1", filledCancelReplace.getString(OrderQty.FIELD)); }