void setConfig(Configuration config) { log.debug("config: " + config); proxyHost = config.get(PARAM_PROXY_HOST); proxyPort = config.getInt(PARAM_PROXY_PORT, DEFAULT_PROXY_PORT); if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) { String http_proxy = System.getenv("http_proxy"); if (!StringUtil.isNullString(http_proxy)) { try { HostPortParser hpp = new HostPortParser(http_proxy); proxyHost = hpp.getHost(); proxyPort = hpp.getPort(); } catch (HostPortParser.InvalidSpec e) { log.warning("Can't parse http_proxy environment var, ignoring: " + http_proxy + ": " + e); } } } if (StringUtil.isNullString(proxyHost) || proxyPort <= 0) { proxyHost = null; } else { log.info("Proxying through " + proxyHost + ":" + proxyPort); } userAgent = config.get(PARAM_USER_AGENT); if (StringUtil.isNullString(userAgent)) { userAgent = null; } else { log.debug("Setting User-Agent to " + userAgent); } }
/** Create LockssKeystores from config subtree below {@link #PARAM_KEYSTORE} */ void configureKeyStores(Configuration config) { Configuration allKs = config.getConfigTree(PARAM_KEYSTORE); for (Iterator iter = allKs.nodeIterator(); iter.hasNext(); ) { String id = (String) iter.next(); Configuration oneKs = allKs.getConfigTree(id); try { LockssKeyStore lk = createLockssKeyStore(oneKs); String name = lk.getName(); if (name == null) { log.error("KeyStore definition missing name: " + oneKs); continue; } LockssKeyStore old = keystoreMap.get(name); if (old != null && !lk.equals(old)) { log.warning( "Keystore " + name + " redefined. " + "New definition may not take effect until daemon restart"); } log.debug("Adding keystore " + name); keystoreMap.put(name, lk); } catch (Exception e) { log.error("Couldn't create keystore: " + oneKs, e); } } }
/** * Find mod files in the "mods" folder * * @param modFolder Folder to search * @param modFiles List of mod files to load */ protected void findModFiles(File modFolder, LinkedList<File> modFiles) { List<String> supportedVerions = Arrays.asList(SUPPORTED_VERSIONS); for (File modFile : modFolder.listFiles(this)) { try { // Check for a version file ZipFile modZip = new ZipFile(modFile); ZipEntry version = modZip.getEntry("version.txt"); if (version != null) { // Read the version string InputStream versionStream = modZip.getInputStream(version); BufferedReader versionReader = new BufferedReader(new InputStreamReader(versionStream)); String strVersion = versionReader.readLine(); versionReader.close(); // Only add the mod if the version matches and we were able to successfully add it to the // class path if (supportedVerions.contains(strVersion) && addURLToClassPath(modFile.toURI().toURL())) { modFiles.add(modFile); } } modZip.close(); } catch (Exception ex) { logger.warning( "Error enumerating '" + modFile.getAbsolutePath() + "': Invalid zip file or error reading file"); } } }
protected void initFeatureVersions() throws PluginException.InvalidDefinition { if (definitionMap.containsKey(KEY_PLUGIN_FEATURE_VERSION_MAP)) { Map<Plugin.Feature, String> map = new HashMap<Plugin.Feature, String>(); Map<String, String> spec = (Map<String, String>) definitionMap.getMap(KEY_PLUGIN_FEATURE_VERSION_MAP); log.debug2("features: " + spec); for (Map.Entry<String, String> ent : spec.entrySet()) { try { // Prefix version string with feature name to create separate // namespace for each feature String key = ent.getKey(); map.put(Plugin.Feature.valueOf(key), key + "_" + ent.getValue()); } catch (RuntimeException e) { log.warning( getPluginName() + " set unknown feature: " + ent.getKey() + " to version " + ent.getValue(), e); throw new PluginException.InvalidDefinition("Unknown feature: " + ent.getKey(), e); } } featureVersion = map; } else { featureVersion = null; } }
/** * Handles a message. Knows type "collectiveUpdate-"+name only. It is the responsibility of the * owner to propagate messages of this type using this method. */ public boolean handleMessage(Message m, Object o) { if (!shouldLive || !m.getType().equals("collectiveUpdate-" + name)) return false; final String logSender = observer + "#collectiveUpdate"; Logger.debug(logSender, "Update from " + m.getSender()); /**/ if (!m.getRecipient().name.equals(contributor.getName())) Logger.warning( logSender, "Recipient and my contributor are not the same:\n" + "Recipient: " + m.getRecipient().name + "\n" + "Contributor: " + contributor.getName(), null); /**/ Collective c = (Collective) o; // --- reset array representations cacheCollection = null; commandCollection = null; // --- remove possible garbage cache.remove(m.getRecipient().name); c.cache.remove(m.getRecipient().name); cache.remove(m.getSender().name); c.cache.remove(m.getSender().name); // --- sending our contributions if (contributor == null) Logger.warning(logSender, "Non-contributor observer is known by " + m.getSender(), null); updateLocalInfo(); m.setReply(this); // --- update containers repairSenderAddress(c, m.getSender()); merge(c); observer.collectiveUpdated((ContributionBox) cache.get(m.getSender().name)); return true; }
private void teardownAuthTokenFile() { if (authTokenFile != null) try { authTokenFile.delete(); } catch (WindowsException ex) { logger.warning(Strings.get("cant.delete", dcomInfo.getHost(), authTokenFilePath)); } }
/** * Find mod classes in the class path and enumerated mod files list * * @param classPathEntries Java class path split into string entries * @return map of classes to load */ private HashMap<String, Class> findModClasses( String[] classPathEntries, LinkedList<File> modFiles) { // To try to avoid loading the same mod multiple times if it appears in more than one entry in // the class path, we index // the mods by name and hopefully match only a single instance of a particular mod HashMap<String, Class> modsToLoad = new HashMap<String, Class>(); try { logger.info("Searching protection domain code source..."); File packagePath = new File(LiteLoader.class.getProtectionDomain().getCodeSource().getLocation().toURI()); LinkedList<Class> modClasses = getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod"); for (Class mod : modClasses) { modsToLoad.put(mod.getSimpleName(), mod); } if (modClasses.size() > 0) logger.info(String.format("Found %s potential matches", modClasses.size())); } catch (Throwable th) { logger.warning("Error loading from local class path: " + th.getMessage()); } // Search through the class path and find mod classes for (String classPathPart : classPathEntries) { logger.info(String.format("Searching %s...", classPathPart)); File packagePath = new File(classPathPart); LinkedList<Class> modClasses = getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod"); for (Class mod : modClasses) { modsToLoad.put(mod.getSimpleName(), mod); } if (modClasses.size() > 0) logger.info(String.format("Found %s potential matches", modClasses.size())); } // Search through mod files and find mod classes for (File modFile : modFiles) { logger.info(String.format("Searching %s...", modFile.getAbsolutePath())); LinkedList<Class> modClasses = getSubclassesFor(modFile, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod"); for (Class mod : modClasses) { modsToLoad.put(mod.getSimpleName(), mod); } if (modClasses.size() > 0) logger.info(String.format("Found %s potential matches", modClasses.size())); } return modsToLoad; }
public void startFile(String logfile) { File parent = new File(logfile).getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) { logger.warning("Could not create log folder: " + parent); } Handler fileHandler = new RotatingFileHandler(logfile); fileHandler.setFormatter(new DateOutputFormatter(FILE_DATE)); logger.addHandler(fileHandler); }
/** Bucle principal del thread. */ public void run() { try { while (true) { mylogger.finer("Waiting for a message."); String pkt = myPP.receive(); mylogger.finer("Received message: " + pkt); if (pkt == null) break; StringTokenizer st = new StringTokenizer(pkt); int nsec = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { String disp = st.nextToken(); mylogger.fine("Requesting Start to Peers (" + nsec + "," + disp + ")"); NeReDa.peers.start(this, nsec, disp, null); } else { mylogger.fine("Requesting Stop to Peers (" + nsec + ")"); NeReDa.peers.stop(this, nsec); } } } catch (Exception e) { mylogger.warning("Terminated DataAttendant: " + e.getMessage()); } try { synchronized (sock) { sock.close(); sock.notify(); } } catch (Exception e) { mylogger.warning("Closing DataAttendant socket: " + e.getMessage()); } mylogger.fine("Deregistering"); NeReDa.peers.Del(this); }
protected String getHostName() { String res = ConfigManager.getPlatformHostname(); if (res == null) { try { InetAddress inet = InetAddress.getLocalHost(); return inet.getHostName(); } catch (UnknownHostException e) { log.warning("Can't get hostname", e); return "unknown"; } } return res; }
static Properties getAuIdProperties(String location) { File propFile = new File(location + File.separator + AU_ID_FILE); try { InputStream is = new BufferedInputStream(new FileInputStream(propFile)); Properties idProps = new Properties(); idProps.load(is); is.close(); return idProps; } catch (Exception e) { logger.warning("Error loading au id from " + propFile.getPath() + "."); return null; } }
static String canonRoot(String root) { synchronized (canonicalRoots) { String canon = (String) canonicalRoots.get(root); if (canon == null) { try { canon = new File(root).getCanonicalPath(); canonicalRoots.put(root, canon); } catch (IOException e) { logger.warning("Can't canonicalize: " + root, e); return root; } } return canon; } }
/** * Repairing address of sender (might contain only name). This sets the right address of * myContribution in c, and puts the contribution into c.cache. sender is the address of the peer * to our best knowledge. However the atual address of the contributor might be different due to * forwarding and other nuances. The authoritive name is in c.myContribution. The authoritive host * and port are in sender. */ private static void repairSenderAddress(Collective c, Address sender) { if (c.myContribution != null) { c.cache.put( c.myContribution.contributor.name, new ContributionBox( new Address(sender.getHost(), sender.port, c.myContribution.contributor.name), c.myContribution.timeStamp, c.myContribution.contribution)); } else Logger.warning( "Collective#repairSenderAddress()", "Update doesn't contain contribution of sender " + sender, null); }
void checkParamAgreement(String key, PrintfContext context) { List<String> printfList = getElementList(key); if (printfList == null) { return; } for (String printf : printfList) { if (StringUtil.isNullString(printf)) { log.warning("Null printf string in " + key); continue; } PrintfUtil.PrintfData p_data = PrintfUtil.stringToPrintf(printf); Collection<String> p_args = p_data.getArguments(); for (String arg : p_args) { ConfigParamDescr descr = findAuConfigDescr(arg); if (descr == null) { throw new PluginException.InvalidDefinition( "Not a declared parameter: " + arg + " in " + printf + " in " + getPluginName()); } // ensure range and set params used only in legal context switch (context) { case Regexp: case Display: // everything is legal in a regexp or a display string break; case URL: // NUM_RANGE and SET legal because can enumerate. Can't // enumerate RANGE switch (descr.getType()) { case ConfigParamDescr.TYPE_RANGE: throw new PluginException.InvalidDefinition( "Range parameter (" + arg + ") used in illegal context in " + getPluginName() + ": " + key + ": " + printf); default: } } } } }
/** * Create mod instances from the enumerated classes * * @param modsToLoad List of mods to load */ private void loadMods(HashMap<String, Class> modsToLoad) { if (modsToLoad == null) { logger.info("Mod class discovery failed. Not loading any mods!"); return; } logger.info("Discovered " + modsToLoad.size() + " total mod(s)"); for (Class mod : modsToLoad.values()) { try { logger.info("Loading mod from " + mod.getName()); LiteMod newMod = (LiteMod) mod.newInstance(); mods.add(newMod); logger.info( "Successfully added mod " + newMod.getName() + " version " + newMod.getVersion()); } catch (Throwable th) { logger.warning(th.toString()); th.printStackTrace(); } } }
protected CIProperties makeCIProperties(ArchiveRecordHeader elementHeader) throws IOException { CIProperties ret = new CIProperties(); Set elementHeaderFieldKeys = elementHeader.getHeaderFieldKeys(); for (Iterator i = elementHeaderFieldKeys.iterator(); i.hasNext(); ) { String key = (String) i.next(); try { Object valueObject = elementHeader.getHeaderValue(key); if (valueObject == null) { logger.warning("Ignoring null value for key '" + key + "'."); } else { String value = valueObject.toString(); logger.debug3(key + ": " + value); ret.put(key, value); } } catch (ClassCastException ex) { logger.error("makeCIProperties: " + key + " threw ", ex); throw new CacheException.ExploderException(ex); } } return (ret); }
/** * Create a new TdbAu instance from the properties. * * @param props the properties * @return a TdbAu instance set built from the properties */ private TdbAu newTdbAu(Properties props) { String pluginId = (String) props.get("plugin"); if (pluginId == null) { throw new IllegalArgumentException("TdbAu plugin ID not specified"); } String auName = props.getProperty("title"); if (auName == null) { throw new IllegalArgumentException("TdbAu title not specified"); } // create a new TdbAu and set its elements TdbAu au = new TdbAu(auName, pluginId); // process attrs, and params Map<String, Map<String, String>> paramMap = new HashMap<String, Map<String, String>>(); for (Map.Entry<Object, Object> entry : props.entrySet()) { String key = String.valueOf(entry.getKey()); String value = String.valueOf(entry.getValue()); if (key.startsWith("attributes.")) { // set attributes directly String name = key.substring("attributes.".length()); try { au.setAttr(name, value); } catch (TdbException ex) { logger.warning( "Cannot set attribute \"" + name + "\" with value \"" + value + "\" -- ignoring"); } } else if (key.startsWith("param.")) { // skip to param name String param = key.substring("param.".length()); int i; if (((i = param.indexOf(".key")) < 0) && ((i = param.indexOf(".value")) < 0)) { logger.warning( "Ignoring unexpected param key for au \"" + auName + "\" key: \"" + key + "\" -- ignoring"); } else { // get param map for pname String pname = param.substring(0, i); Map<String, String> pmap = paramMap.get(pname); if (pmap == null) { pmap = new HashMap<String, String>(); paramMap.put(pname, pmap); } // add name and value to param map for pname String name = param.substring(i + 1); pmap.put(name, value); } } else if (!key.equals("title") // TdbAu has "name" property && !key.equals("plugin") // TdbAu has "pluginId" property && !key.equals("journalTitle") // TdbAu has "title" TdbTitle property && !key.startsWith("journal.")) { // TdbAu has "title" TdbTitle property // translate all other properties into AU properties try { au.setPropertyByName(key, value); } catch (TdbException ex) { logger.warning( "Cannot set property \"" + key + "\" with value \"" + value + "\" -- ignoring"); } } } // set param from accumulated "key", and "value" entries for (Map<String, String> pmap : paramMap.values()) { String name = pmap.get("key"); String value = pmap.get("value"); if (name == null) { logger.warning("Ignoring property with null name"); } else if (value == null) { logger.warning("Ignoring property \"" + name + "\" with null value"); } else { try { au.setParam(name, value); } catch (TdbException ex) { logger.warning( "Cannot set param \"" + name + "\" with value \"" + value + "\" -- ignoring"); } } } return au; }
/** Query the daemon for information required to set up this command */ private boolean commandSetup() { Configuration configuration = null; Collection noEditKeys = null; String key; String value; /* * Configure a well known publication? */ if ((value = getParameter(AP_E_PUBLICATION)) != null) { PluginProxy plugin = getTitlePlugin(value); /* * Set plugin and Title configuration information */ if (plugin == null) { String message = "Unknown Publication:" + value; log.warning(message); return error(message); } setPlugin(plugin); setTitleConfig(plugin.getTitleConfig(value)); configuration = getTitleConfig().getConfig(); noEditKeys = getNoEditKeys(); } else { /* * Lookup by Plugin or Class name - set the plugin * * NB: As of 23-Feb-04, this is not supported from AddAuPage.java. See * AddAuWithCompleteFunctionalityPage.java for full support. */ if ((value = getParameter(AP_E_PLUGIN)) != null) { key = RemoteApi.pluginKeyFromId(value); } else if ((value = getParameter(AP_E_CLASSNAME)) != null) { key = RemoteApi.pluginKeyFromId(value); } else { return error("Supply a Publication, Plugin, or Class name"); } if (StringUtil.isNullString(key)) { return error("Supply a valid Publication, Plugin, or Class name"); } if (!pluginLoaded(key)) { return error("Plugin is not loaded: " + key); } setPlugin(getPluginProxy(key)); } /* * Finally, return an XML rendition of the Plugin and AU key set up */ generateSetupXml(configuration, noEditKeys); return true; }
/** * A tracker wants to know if there's a Task to run. Returns a task we'd like the TaskTracker to * execute right now. * * <p>Eventually this function should compute load on the various TaskTrackers, and incorporate * knowledge of DFS file placement. But for right now, it just grabs a single item out of the * pending task list and hands it back. */ public synchronized Task pollForNewTask(String taskTracker) { // // Compute average map and reduce task numbers across pool // int avgMaps = 0; int avgReduces = 0; int numTaskTrackers; TaskTrackerStatus tts; synchronized (taskTrackers) { numTaskTrackers = taskTrackers.size(); tts = (TaskTrackerStatus) taskTrackers.get(taskTracker); } if (numTaskTrackers > 0) { avgMaps = totalMaps / numTaskTrackers; avgReduces = totalReduces / numTaskTrackers; } int totalCapacity = numTaskTrackers * maxCurrentTasks; // // Get map + reduce counts for the current tracker. // if (tts == null) { LOG.warning("Unknown task tracker polling; ignoring: " + taskTracker); return null; } int numMaps = tts.countMapTasks(); int numReduces = tts.countReduceTasks(); // // In the below steps, we allocate first a map task (if appropriate), // and then a reduce task if appropriate. We go through all jobs // in order of job arrival; jobs only get serviced if their // predecessors are serviced, too. // // // We hand a task to the current taskTracker if the given machine // has a workload that's equal to or less than the averageMaps // +/- TASK_ALLOC_EPSILON. (That epsilon is in place in case // there is an odd machine that is failing for some reason but // has not yet been removed from the pool, making capacity seem // larger than it really is.) // synchronized (jobsByArrival) { if ((numMaps < maxCurrentTasks) && (numMaps <= (avgMaps + TASK_ALLOC_EPSILON))) { int totalNeededMaps = 0; for (Iterator it = jobsByArrival.iterator(); it.hasNext(); ) { JobInProgress job = (JobInProgress) it.next(); if (job.getStatus().getRunState() != JobStatus.RUNNING) { continue; } Task t = job.obtainNewMapTask(taskTracker, tts); if (t != null) { return t; } // // Beyond the highest-priority task, reserve a little // room for failures and speculative executions; don't // schedule tasks to the hilt. // totalNeededMaps += job.desiredMaps(); double padding = 0; if (totalCapacity > MIN_SLOTS_FOR_PADDING) { padding = Math.min(maxCurrentTasks, totalNeededMaps * PAD_FRACTION); } if (totalNeededMaps + padding >= totalCapacity) { break; } } } // // Same thing, but for reduce tasks // if ((numReduces < maxCurrentTasks) && (numReduces <= (avgReduces + TASK_ALLOC_EPSILON))) { int totalNeededReduces = 0; for (Iterator it = jobsByArrival.iterator(); it.hasNext(); ) { JobInProgress job = (JobInProgress) it.next(); if (job.getStatus().getRunState() != JobStatus.RUNNING) { continue; } Task t = job.obtainNewReduceTask(taskTracker, tts); if (t != null) { return t; } // // Beyond the highest-priority task, reserve a little // room for failures and speculative executions; don't // schedule tasks to the hilt. // totalNeededReduces += job.desiredReduces(); double padding = 0; if (totalCapacity > MIN_SLOTS_FOR_PADDING) { padding = Math.min(maxCurrentTasks, totalNeededReduces * PAD_FRACTION); } if (totalNeededReduces + padding >= totalCapacity) { break; } } } } return null; }
/** * @param in input stream to be used (e.g. System.in) * @param prompt The prompt to display to the user. * @return The password as entered by the user. */ public static final char[] getPassword(InputStream in, String prompt) throws IOException { MaskingThread maskingthread = new MaskingThread(prompt); Thread thread = new Thread(maskingthread); thread.start(); char[] lineBuffer; char[] buf; int i; buf = lineBuffer = new char[128]; int room = buf.length; int offset = 0; int c; loop: while (true) { c = in.read(); switch (c) { case -1: case '\n': break loop; case '\r': int c2 = in.read(); if ((c2 != '\n') && (c2 != -1)) { if (!(in instanceof PushbackInputStream)) { in = new PushbackInputStream(in); } ((PushbackInputStream) in).unread(c2); } else { break loop; } default: if (--room < 0) { buf = new char[offset + 128]; room = buf.length - offset - 1; System.arraycopy(lineBuffer, 0, buf, 0, offset); Arrays.fill(lineBuffer, ' '); lineBuffer = buf; } buf[offset++] = (char) c; break; } } maskingthread.stopMasking(); System.out.print("\010"); // Code to clear doskey on win nt/2000 - Alt+F7 String os = System.getProperty("os.name"); if (os != null && os.toLowerCase().startsWith("windows")) { try { java.awt.Robot robot = new java.awt.Robot(); robot.keyPress(java.awt.event.KeyEvent.VK_ALT); robot.keyPress(java.awt.event.KeyEvent.VK_F7); robot.keyRelease(java.awt.event.KeyEvent.VK_F7); robot.keyRelease(java.awt.event.KeyEvent.VK_ALT); } catch (Exception ignore) { logger.warning("Could not clears command history: " + ignore); } } if (offset == 0) { return null; } char[] ret = new char[offset]; System.arraycopy(buf, 0, ret, 0, offset); Arrays.fill(buf, ' '); return ret; }
public QSAdminGUI(QSAdminMain qsadminMain, JFrame parentFrame) { this.parentFrame = parentFrame; Container cp = this; qsadminMain.setGUI(this); cp.setLayout(new BorderLayout(5, 5)); headerPanel = new HeaderPanel(qsadminMain, parentFrame); mainCommandPanel = new MainCommandPanel(qsadminMain); cmdConsole = new CmdConsole(qsadminMain); propertiePanel = new PropertiePanel(qsadminMain); if (headerPanel == null || mainCommandPanel == null || cmdConsole == null || propertiePanel == null) { throw new RuntimeException("Loading of one of gui component failed."); } headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); cp.add(headerPanel, BorderLayout.NORTH); JScrollPane propertieScrollPane = new JScrollPane(propertiePanel); // JScrollPane commandScrollPane = new JScrollPane(mainCommandPanel); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, mainCommandPanel, cmdConsole); splitPane.setOneTouchExpandable(false); splitPane.setDividerLocation(250); // splitPane.setDividerLocation(0.70); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.addTab("Main", ball, splitPane, "Main Commands"); tabbedPane.addTab("Get/Set", ball, propertieScrollPane, "Properties Panel"); QSAdminPluginConfig qsAdminPluginConfig = null; PluginPanel pluginPanel = null; // -- start of loadPlugins try { File xmlFile = null; ClassLoader classLoader = null; Class mainClass = null; File file = new File(pluginDir); File dirs[] = null; if (file.canRead()) dirs = file.listFiles(new DirFileList()); for (int i = 0; dirs != null && i < dirs.length; i++) { xmlFile = new File(dirs[i].getAbsolutePath() + File.separator + "plugin.xml"); if (xmlFile.canRead()) { qsAdminPluginConfig = PluginConfigReader.read(xmlFile); if (qsAdminPluginConfig.getActive().equals("yes") && qsAdminPluginConfig.getType().equals("javax.swing.JPanel")) { classLoader = ClassUtil.getClassLoaderFromJars(dirs[i].getAbsolutePath()); mainClass = classLoader.loadClass(qsAdminPluginConfig.getMainClass()); logger.fine("Got PluginMainClass " + mainClass); pluginPanel = (PluginPanel) mainClass.newInstance(); if (JPanel.class.isInstance(pluginPanel) == true) { logger.info("Loading plugin : " + qsAdminPluginConfig.getName()); pluginPanelMap.put("" + (2 + i), pluginPanel); plugins.add(pluginPanel); tabbedPane.addTab( qsAdminPluginConfig.getName(), ball, (JPanel) pluginPanel, qsAdminPluginConfig.getDesc()); pluginPanel.setQSAdminMain(qsadminMain); pluginPanel.init(); } } else { logger.info( "Plugin " + dirs[i] + " is disabled so skipping " + qsAdminPluginConfig.getActive() + ":" + qsAdminPluginConfig.getType()); } } else { logger.info("No plugin configuration found in " + xmlFile + " so skipping"); } } } catch (Exception e) { logger.warning("Error loading plugin : " + e); logger.fine("StackTrace:\n" + MyString.getStackTrace(e)); } // -- end of loadPlugins tabbedPane.addChangeListener( new ChangeListener() { int selected = -1; int oldSelected = -1; public void stateChanged(ChangeEvent e) { // if plugin selected = tabbedPane.getSelectedIndex(); if (selected >= 2) { ((PluginPanel) pluginPanelMap.get("" + selected)).activated(); } if (oldSelected >= 2) { ((PluginPanel) pluginPanelMap.get("" + oldSelected)).deactivated(); } oldSelected = selected; } }); // tabbedPane.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); cp.add(tabbedPane, BorderLayout.CENTER); buildMenu(); }
/** * Merge other Tdb into this one. Makes copies of otherTdb's non-duplicate TdbPublisher, TdbTitle, * and TdbAu objects and their non-duplicate children. The object themselves are not merged. * * @param otherTdb the other Tdb * @throws TdbException if Tdb is sealed */ public void copyFrom(Tdb otherTdb) throws TdbException { // ignore inappropriate Tdb values if ((otherTdb == null) || (otherTdb == this)) { return; } if (isSealed()) { throw new TdbException("Cannot add otherTdb AUs to sealed Tdb"); } // merge non-duplicate publishers of otherTdb boolean tdbIsNew = tdbPublisherMap.isEmpty(); for (TdbPublisher otherPublisher : otherTdb.getAllTdbPublishers().values()) { String pubName = otherPublisher.getName(); TdbPublisher thisPublisher; boolean publisherIsNew = true; if (tdbIsNew) { // no need to check for existing publisher if TDB is new thisPublisher = new TdbPublisher(pubName); tdbPublisherMap.put(pubName, thisPublisher); } else { thisPublisher = tdbPublisherMap.get(pubName); publisherIsNew = (thisPublisher == null); if (publisherIsNew) { // copy publisher if not present in this Tdb thisPublisher = new TdbPublisher(pubName); tdbPublisherMap.put(pubName, thisPublisher); } } // merge non-duplicate titles of otherPublisher into thisPublisher for (TdbTitle otherTitle : otherPublisher.getTdbTitles()) { String otherId = otherTitle.getId(); TdbTitle thisTitle; boolean titleIsNew = true; if (publisherIsNew) { // no need to check for existing title if publisher is new thisTitle = otherTitle.copyForTdbPublisher(thisPublisher); thisPublisher.addTdbTitle(thisTitle); } else { thisTitle = thisPublisher.getTdbTitleById(otherId); titleIsNew = (thisTitle == null); if (titleIsNew) { // copy title if not present in this publisher thisTitle = otherTitle.copyForTdbPublisher(thisPublisher); thisPublisher.addTdbTitle(thisTitle); } else if (!thisTitle.getName().equals(otherTitle.getName())) { // error because it could lead to a missing title -- one probably has a typo // (what about checking other title elements too?) logger.error( "Ignorning duplicate title entry: \"" + otherTitle.getName() + "\" with the same ID as \"" + thisTitle.getName() + "\""); } } // merge non-duplicate TdbAus of otherTitle into thisTitle for (TdbAu otherAu : otherTitle.getTdbAus()) { // no need to check for existing au if title is new String pluginId = otherAu.getPluginId(); if (titleIsNew || !getTdbAuIds(pluginId).contains(otherAu.getId())) { // always succeeds we've already checked for duplicate TdbAu thisAu = otherAu.copyForTdbTitle(thisTitle); addTdbAuForPlugin(thisAu); } else { TdbAu thisAu = findExistingTdbAu(otherAu); if (!thisAu.getTdbTitle().getName().equals(otherAu.getTdbTitle().getName())) { if (!thisAu.getName().equals(otherAu.getName())) { logger.error( "Ignorning duplicate au entry: \"" + otherAu.getName() + "\" for title \"" + otherAu.getTdbTitle().getName() + "\" with same definion as existing au entry: \"" + thisAu.getName() + "\" for title \"" + thisAu.getTdbTitle().getName() + "\""); } else { logger.error( "Ignorning duplicate au entry: \"" + otherAu.getName() + "\" for title \"" + otherAu.getTdbTitle().getName() + "\" with same definion as existing one for title \"" + thisAu.getTdbTitle().getName() + "\""); } } else if (!thisAu.getName().equals(otherAu.getName())) { // error because it could lead to a missing AU -- one probably has a typo logger.error( "Ignorning duplicate au entry: \"" + otherAu.getName() + "\" with the same definition as \"" + thisAu.getName() + "\" for title \"" + otherAu.getTdbTitle().getName()); } else { logger.warning( "Ignoring duplicate au entry: \"" + otherAu.getName() + "\" for title \"" + otherAu.getTdbTitle().getName()); } } } } } }
/** * Callback method to process modifications in the common ConfigOptions panel. ConfigOptions was * developed to be common to many applications (even though we only have three modes), so it does * not have any knowledge of how we are using it within this dialog box. So ConfigOptions just * sends updates to registered Observers whenever anything changes. We can receive those * notifications here, and decide whether we have enough information to enable the "Connect" * button of the dialog box. */ public void update(Observable o, Object arg) { // we are going to ignore the Observable object, since we are only // observing one object. All we are interested in is the argument. if (!(arg instanceof OptionUpdate)) { log.log( Level.WARNING, "DatabaseLocationDialog received update type: " + arg, new IllegalArgumentException()); return; } OptionUpdate optionUpdate = (OptionUpdate) arg; // load saved configuration SavedConfiguration config = SavedConfiguration.getSavedConfiguration(); switch (optionUpdate.getUpdateType()) { case DB_LOCATION_CHANGED: location = (String) optionUpdate.getPayload(); if (configOptions.getApplicationMode() == ApplicationMode.STANDALONE_CLIENT) { File f = new File(location); if (f.exists() && f.canRead() && f.canWrite()) { validDb = true; log.info("File chosen " + location); config.setParameter(SavedConfiguration.DATABASE_LOCATION, location); } else { log.warning("Invalid file " + location); } } else { try { if (location.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")) { // location given matches 4 '.' separated numbers // regex could be improved by limiting each quad to // no more than 3 digits. String[] quads = location.split("\\."); byte[] address = new byte[quads.length]; for (int i = 0; i < quads.length; i++) { address[i] = new Integer(quads[i]).byteValue(); } InetAddress.getByAddress(address); } else { InetAddress.getAllByName(location); } log.info("Server specified " + location); validDb = true; config.setParameter(SavedConfiguration.SERVER_ADDRESS, location); } catch (UnknownHostException uhe) { log.warning("Unknown host: " + location); validDb = false; } } break; case PORT_CHANGED: port = (String) optionUpdate.getPayload(); int p = Integer.parseInt(port); if (p >= LOWEST_PORT && p < HIGHEST_PORT) { if (p < SYSTEM_PORT_BOUNDARY) { log.info("User chose System port " + port); } else if (p < IANA_PORT_BOUNDARY) { log.info("User chose IANA port " + port); } else { log.info("User chose dynamic port " + port); } validPort = true; config.setParameter(SavedConfiguration.SERVER_PORT, port); } else { validPort = false; } break; case NETWORK_CHOICE_MADE: networkType = (ConnectionType) optionUpdate.getPayload(); switch (networkType) { case SOCKET: log.info("Server connection via Sockets"); break; case RMI: log.info("Server connection via RMI"); break; default: log.info("Unknown connection type: " + networkType); break; } config.setParameter(SavedConfiguration.NETWORK_TYPE, "" + networkType); validCnx = true; break; default: log.warning("Unknown update: " + optionUpdate); break; } boolean allValid = validDb && validPort && validCnx; connectButton.setEnabled(allValid); }
/** * This is called when a node is in an inconsistent state. It simply creates some necessary * directories and deactivates the node. Future polls should restore it properly. * * @param node the inconsistent node */ void deactivateInconsistentNode(RepositoryNodeImpl node) { logger.warning("Deactivating inconsistent node."); FileUtil.ensureDirExists(node.contentDir); // manually deactivate node.deactivateContent(); }
/** * Get or create TdbTitle for the specified properties and TdbAu. * * @param props the properties * @param au the TdbAu * @return the corresponding TdbTitle */ private TdbTitle getTdbTitle(Properties props, TdbAu au) { TdbTitle title = null; // get publisher name String publisherNameFromProps = getTdbPublisherName(props, au); // get the title name String titleNameFromProps = getTdbTitleName(props, au); // get the title ID String titleIdFromProps = getTdbTitleId(props, au); String titleId = titleIdFromProps; if (titleId == null) { // generate a titleId if one not specified, using the // hash code of the combined title name and publisher names int hash = (titleNameFromProps + publisherNameFromProps).hashCode(); titleId = (hash < 0) ? ("id:1" + (-hash)) : ("id:0" + hash); } // get publisher specified by property name TdbPublisher publisher = tdbPublisherMap.get(publisherNameFromProps); if (publisher != null) { // find title from publisher title = publisher.getTdbTitleById(titleId); if (title != null) { // warn that title name is different if (!title.getName().equals(titleNameFromProps)) { logger.warning( "Title for au \"" + au.getName() + "\": \"" + titleNameFromProps + "\" is different than existing title \"" + title.getName() + "\" for id " + titleId + " -- using existing title."); } return title; } } if (publisher == null) { // warn of missing publisher name if (publisherNameFromProps.startsWith(UNKNOWN_PUBLISHER_PREFIX)) { logger.warning( "Publisher missing for au \"" + au.getName() + "\" -- using \"" + publisherNameFromProps + "\""); } // create new publisher for specified publisher name publisher = new TdbPublisher(publisherNameFromProps); tdbPublisherMap.put(publisherNameFromProps, publisher); } // warn of missing title name and/or id if (titleNameFromProps.startsWith(UNKNOWN_TITLE_PREFIX)) { logger.warning( "Title missing for au \"" + au.getName() + "\" -- using \"" + titleNameFromProps + "\""); } if (titleIdFromProps == null) { logger.debug2("Title ID missing for au \"" + au.getName() + "\" -- using " + titleId); } // create title and add to publisher title = new TdbTitle(titleNameFromProps, titleId); try { publisher.addTdbTitle(title); } catch (TdbException ex) { // shouldn't happen: title already exists in publisher logger.error(ex.getMessage(), ex); } return title; }
/** Clean up all resources used by this poll. Removes the poll directory. */ public void closePoll() { if (pollDir != null && pollDir.isDirectory() && !FileUtil.delTree(pollDir)) log.warning("Unable to delete poll state directory: " + pollDir); }
/** * Creates a dialog where the user can specify the location of the database,including the type of * network connection (if this is a networked client)and IP address and port number; or search and * select the database on a local drive if this is a standalone client. * * @param parent Defines the Component that is to be the parent of this dialog box. For * information on how this is used, see <code>JOptionPane</code> * @param connectionMode Specifies the type of connection (standalone or networked) * @see JOptionPane */ public DatabaseLocationDialog(Frame parent, ApplicationMode connectionMode) { configOptions = (new ConfigOptions(connectionMode)); configOptions.getObservable().addObserver(this); // load saved configuration SavedConfiguration config = SavedConfiguration.getSavedConfiguration(); // the port and connection type are irrelevant in standalone mode if (connectionMode == ApplicationMode.STANDALONE_CLIENT) { validPort = true; validCnx = true; networkType = ConnectionType.DIRECT; location = config.getParameter(SavedConfiguration.DATABASE_LOCATION); } else { // there may not be a network connectivity type defined and, if // not, we do not set a default - force the user to make a choice // the at least for the first time they run this. String tmp = config.getParameter(SavedConfiguration.NETWORK_TYPE); if (tmp != null) { try { networkType = ConnectionType.valueOf(tmp); configOptions.setNetworkConnection(networkType); validCnx = true; } catch (IllegalArgumentException e) { log.warning("Unknown connection type: " + networkType); } } // there is always at least a default port number, so we don't have // to validate this. port = config.getParameter(SavedConfiguration.SERVER_PORT); configOptions.setPortNumberText(port); validPort = true; location = config.getParameter(SavedConfiguration.SERVER_ADDRESS); } // there may not be a default database location, so we had better // validate before using the returned value. if (location != null) { configOptions.setLocationFieldText(location); validDb = true; } options = new JOptionPane(configOptions, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); connectButton.setActionCommand(CONNECT); connectButton.addActionListener(this); boolean allValid = validDb && validPort && validCnx; connectButton.setEnabled(allValid); exitButton.setActionCommand(EXIT); exitButton.addActionListener(this); options.setOptions(new Object[] {connectButton, exitButton}); dialog = options.createDialog(parent, TITLE); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); dialog.addWindowListener(this); dialog.setVisible(true); }
/** * Add a TdbAu to a TdbTitle and TdbPubisher, and add links to the TdbTitle specified by the * properties. * * @param props the properties * @param au the TdbAu to add * @throws TdbException if the AU already exists in this Tdb */ private void addTdbAu(Properties props, TdbAu au) throws TdbException { // add au for plugin assuming it is not a duplicate if (!addTdbAuForPlugin(au)) { // au already registered -- report existing au TdbAu existingAu = findExistingTdbAu(au); String titleName = getTdbTitleName(props, au); if (!titleName.equals(existingAu.getTdbTitle().getName())) { throw new TdbException( "Cannot add duplicate au entry: \"" + au.getName() + "\" for title \"" + titleName + "\" with same definition as existing au entry: \"" + existingAu.getName() + "\" for title \"" + existingAu.getTdbTitle().getName() + "\" to title database"); } else if (!existingAu.getName().equals(au.getName())) { // error because it could lead to a missing AU -- one probably has a typo throw new TdbException( "Cannot add duplicate au entry: \"" + au.getName() + "\" with the same definition as \"" + existingAu.getName() + "\" for title \"" + titleName + "\" to title database"); } else { throw new TdbException( "Cannot add duplicate au entry: \"" + au.getName() + "\" for title \"" + titleName + "\" to title database"); } } // get or create the TdbTitle for this TdbTitle title = getTdbTitle(props, au); try { // add AU to title title.addTdbAu(au); } catch (TdbException ex) { // if we can't add au to title, remove for plugin and re-throw exception removeTdbAuForPlugin(au); throw ex; } // process title links Map<String, Map<String, String>> linkMap = new HashMap<String, Map<String, String>>(); for (Map.Entry<Object, Object> entry : props.entrySet()) { String key = "" + entry.getKey(); String value = "" + entry.getValue(); if (key.startsWith("journal.link.")) { // skip to link name String param = key.substring("link.".length()); int i; if (((i = param.indexOf(".type")) < 0) && ((i = param.indexOf(".journalId")) < 0)) { logger.warning( "Ignoring nexpected link key for au \"" + au.getName() + "\" key: \"" + key + "\""); } else { // get link map for linkName String lname = param.substring(0, i); Map<String, String> lmap = linkMap.get(lname); if (lmap == null) { lmap = new HashMap<String, String>(); linkMap.put(lname, lmap); } // add name and value to link map for link String name = param.substring(i + 1); lmap.put(name, value); } } } // add links to title from accumulated "type", "journalId" entries for (Map<String, String> lmap : linkMap.values()) { String name = lmap.get("type"); String value = lmap.get("journalId"); if ((name != null) && (value != null)) { try { TdbTitle.LinkType linkType = TdbTitle.LinkType.valueOf(name); title.addLinkToTdbTitleId(linkType, value); } catch (IllegalArgumentException ex) { logger.warning( "Ignoring unknown link type for au \"" + au.getName() + "\" name: \"" + name + "\""); } } } }