/**
   * Load from resource. url = ZeppelinConfiguration.class.getResource(ZEPPELIN_SITE_XML);
   *
   * @throws ConfigurationException
   */
  public static ZeppelinConfiguration create() {
    if (conf != null) {
      return conf;
    }

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL url;

    url = ZeppelinConfiguration.class.getResource(ZEPPELIN_SITE_XML);
    if (url == null) {
      ClassLoader cl = ZeppelinConfiguration.class.getClassLoader();
      if (cl != null) {
        url = cl.getResource(ZEPPELIN_SITE_XML);
      }
    }
    if (url == null) {
      url = classLoader.getResource(ZEPPELIN_SITE_XML);
    }

    if (url == null) {
      LOG.warn("Failed to load configuration, proceeding with a default");
      conf = new ZeppelinConfiguration();
    } else {
      try {
        LOG.info("Load configuration from " + url);
        conf = new ZeppelinConfiguration(url);
      } catch (ConfigurationException e) {
        LOG.warn("Failed to load configuration from " + url + " proceeding with a default", e);
        conf = new ZeppelinConfiguration();
      }
    }

    return conf;
  }
Esempio n. 2
0
 public static Icon getIcon(String iconName) {
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   URL url = cl.getResource("test/check/icons/" + iconName + ".gif");
   if (url != null) return new ImageIcon(url);
   url = cl.getResource("test/check/icons/" + iconName + ".png");
   if (url != null) return new ImageIcon(url);
   return null;
 }
Esempio n. 3
0
 public ViewportRenderer() {
   ClassLoader loader = getClass().getClassLoader();
   surfaceIcon =
       new ImageIcon(loader.getResource(IMAGE_BASE + "/vrjuggler-surface-viewport.png"));
   simIcon = new ImageIcon(loader.getResource(IMAGE_BASE + "/vrjuggler-sim-viewport.png"));
   scaledSurfaceIcon = new ImageIcon();
   scaledSimIcon = new ImageIcon();
 }
Esempio n. 4
0
 public URL getURL(String fileName) {
   URL url = null;
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   url = cl.getResource(fileName);
   if (url == null) {
     cl = this.getClass().getClassLoader();
     url = cl.getResource(fileName);
   }
   return url;
 }
Esempio n. 5
0
  /** @param frameName title name for frame */
  public ShowSavedResults(String frameName) {
    super(frameName);
    aboutRes =
        new JTextArea(
            "Select a result set from"
                + "\nthose listed and details"
                + "\nof that analysis will be"
                + "\nshown here. Then you can"
                + "\neither delete or view those"
                + "\nresults using the buttons below.");
    aboutScroll = new JScrollPane(aboutRes);
    ss = new JScrollPane(sp);
    ss.getViewport().setBackground(Color.white);

    //  resMenu.setLayout(new FlowLayout(FlowLayout.LEFT,10,1));
    ClassLoader cl = getClass().getClassLoader();
    rfii = new ImageIcon(cl.getResource("images/Refresh_button.gif"));

    // results status
    resButtonStatus = new JPanel(new BorderLayout());
    Border loweredbevel = BorderFactory.createLoweredBevelBorder();
    Border raisedbevel = BorderFactory.createRaisedBevelBorder();
    Border compound = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel);
    statusField = new JTextField();
    statusField.setBorder(compound);
    statusField.setEditable(false);
  }
Esempio n. 6
0
 @Override
 public URL getResource(String name) {
   incRecurseDepth();
   try {
     // First try with this class loader
     URL url = findResource(name);
     if (url == null) {
       // Detect circular hierarchy
       Set<ModuleClassLoader> walked = getWalked();
       walked.add(this);
       // Now try with the parents
       for (ModuleReference parent : parents) {
         checkAlreadyWalked(walked, parent);
         url = parent.mcl.getResource(name);
         if (url != null) {
           return url;
         }
       }
       // If got here then none of the parents know about it, so try the system
       url = system.getResource(name);
     }
     return url;
   } finally {
     checkClearTLs();
   }
 }
 @Test
 public void testResourceLookupWithPrefixAfterLoading() throws Exception {
   assertThat(classLoader.loadClass(Foo.class.getName()).getClassLoader(), is(classLoader));
   assertThat(
       classLoader.getResource("/" + Foo.class.getName().replace('.', '/') + CLASS_FILE),
       expectedResourceLookup ? notNullValue(URL.class) : nullValue(URL.class));
 }
 private String getCsvFilePath() {
   ClassLoader classLoader = getClass().getClassLoader();
   URL csvUrl = classLoader.getResource("category_mapping.csv");
   if (csvUrl == null || csvUrl.getFile() == null) {
     throw new RuntimeException("Bad path to category_mapping.csv");
   }
   return csvUrl.getFile();
 }
 public static Map<Lang, Result> convert(
     ClassLoader loader, List<Lang> langs, String source, String fqn, String method)
     throws Exception {
   URL url = loader.getResource(source);
   if (url == null) {
     throw new Exception("Cannot resolve source " + source + "");
   }
   String file = new File(url.toURI()).getAbsolutePath();
   return convertFromFiles(loader, langs, file, fqn, method);
 }
Esempio n. 10
0
  @Test
  public void testJackson() throws Exception {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new VKontakteModule());
    objectMapper.getJsonFactory().setInputDecorator(new VKontakteDecoratorFilter());

    ClassLoader loader = getClass().getClassLoader();
    VKontakteNewsPosts resp =
        objectMapper.readValue(loader.getResource("wall.get.json"), VKontakteNewsPosts.class);
    System.out.println(resp);
  }
Esempio n. 11
0
  @Test
  public void testYoutubeJackson() throws Exception {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new YoutubeModule());

    ClassLoader loader = getClass().getClassLoader();
    YoutubeUserProfile profile =
        objectMapper.readValue(
            loader.getResource("youtube.profile.json"), new TypeReference<YoutubeUserProfile>() {});

    Assert.assertEquals(
        profile.getUid(), "http://gdata.youtube.com/feeds/api/users/RjgafKflW0WSEjtinXzprQ");
    Assert.assertEquals(profile.getUsername(), "andhomgmailcom");
  }
  /** Overrides the default behaviour to including binding of Grails domain classes. */
  @Override
  protected void secondPassCompile() throws MappingException {
    final Thread currentThread = Thread.currentThread();
    final ClassLoader originalContextLoader = currentThread.getContextClassLoader();
    if (!configLocked) {
      if (LOG.isDebugEnabled())
        LOG.debug(
            "[GrailsAnnotationConfiguration] ["
                + domainClasses.size()
                + "] Grails domain classes to bind to persistence runtime");

      // do Grails class configuration
      configureDomainBinder(binder, grailsApplication, domainClasses);

      for (GrailsDomainClass domainClass : domainClasses) {

        final String fullClassName = domainClass.getFullName();

        String hibernateConfig = fullClassName.replace('.', '/') + ".hbm.xml";
        final ClassLoader loader = originalContextLoader;
        // don't configure Hibernate mapped classes
        if (loader.getResource(hibernateConfig) != null) continue;

        final Mappings mappings = super.createMappings();
        if (!GrailsHibernateUtil.usesDatasource(domainClass, dataSourceName)) {
          continue;
        }

        LOG.debug(
            "[GrailsAnnotationConfiguration] Binding persistent class [" + fullClassName + "]");

        Mapping m = binder.getMapping(domainClass);
        mappings.setAutoImport(m == null || m.getAutoImport());
        binder.bindClass(domainClass, mappings, sessionFactoryBeanName);
      }
    }

    try {
      currentThread.setContextClassLoader(grailsApplication.getClassLoader());
      super.secondPassCompile();
      createSubclassForeignKeys();
    } finally {
      currentThread.setContextClassLoader(originalContextLoader);
    }

    configLocked = true;
  }
Esempio n. 13
0
  public void processInput() {

    ClassLoader classLoader = getClass().getClassLoader();
    File englishStopWords =
        new File(classLoader.getResource("DEFAULT_ENGLISH_STOP_WORDS").getFile());

    processedInput = new ArrayList<String>();
    lemmatizedInput = new ArrayList<String>();

    // tokenize and stop word removal operations

    initStopWordList(englishStopWords);

    CharArraySet stopwords = new CharArraySet(stopWordPool, true);
    StandardAnalyzer analyzer = new StandardAnalyzer(stopwords);
    TokenStream stream;
    try {
      stream = analyzer.tokenStream(null, new StringReader(input));
      CharTermAttribute cattr = stream.addAttribute(CharTermAttribute.class);
      stream.reset();
      while (stream.incrementToken()) {
        if (!processedInput.contains(cattr.toString())) processedInput.add(cattr.toString());
      }
      stream.end();
      stream.close();

      // System.out.println("In input processing " + "      "
      // + processedInput);
      setProcessedInput(processedInput);

      // for lemmatization concatinate input strings and send to Standford
      // NLP processor

      for (int i = 0; i < processedInput.size(); i++) {
        lemmatizedInput.addAll(new StanfordLemmatizer().lemmatize(processedInput.get(i)));
      }

      // System.out.println("In input processing " + "      "
      // + lemmatizedInput);

      setLemmatizedInput(lemmatizedInput);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 14
0
  @Before
  public void setUp() throws Exception {
    ClassLoader loader = Ch02ExampleTest.class.getClassLoader();
    String classPathRoot = loader.getResource(".").getPath();
    contents =
        new String(
            Files.readAllBytes(Paths.get(classPathRoot, "ch02/alice.txt")), StandardCharsets.UTF_8);
    words = Arrays.asList(contents.split("[\\P{L}]+"));

    digits =
        new Integer[] {
          3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6,
          4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2, 8, 8, 4, 1, 9, 7, 1, 6, 9, 3, 9, 9,
          3, 7, 5, 1, 0, 5, 8, 2, 0, 9, 7, 4, 9, 4, 4, 5, 9, 2, 3, 0, 7, 8, 1,
          6, 4, 0, 6, 2, 8, 6
        };
  }
Esempio n. 15
0
  public NodeSettingsPanel() {
    try {
      jbInit();
    } catch (Exception e) {
      e.printStackTrace();
    }
    // Try to get icons for the toolbar buttons
    try {
      ClassLoader loader = getClass().getClassLoader();
      mClusterIcon = new ImageIcon(loader.getResource(COMMON_IMG_ROOT + "/ClusterIcon.png"));

      mIconLabel.setIcon(mClusterIcon);
    } catch (Exception e) {
      // Ack! No icons. Use text labels instead
      mIconLabel.setText("");
    }
  }
Esempio n. 16
0
  private InputStream getInputStreamByPath(String p) {
    InputStream is = appCL.getResourceAsStream(p);
    if (is != null) return is;

    is = Thread.currentThread().getContextClassLoader().getResourceAsStream(p);
    if (is != null) return is;

    ClassLoader mycl = this.getClass().getClassLoader();
    URL u = mycl.getResource(p);
    is = mycl.getResourceAsStream(p);
    if (is != null) return is;

    ClassLoader pcl = mycl;
    while ((pcl = pcl.getParent()) != null) {
      is = pcl.getResourceAsStream(p);
      if (is != null) return is;
    }
    return null;
  }
Esempio n. 17
0
 private MultiMap<String, ProjectTemplate> loadLocalTemplates() {
   ConcurrentMultiMap<String, ProjectTemplate> map =
       new ConcurrentMultiMap<String, ProjectTemplate>();
   ProjectTemplateEP[] extensions = ProjectTemplateEP.EP_NAME.getExtensions();
   for (ProjectTemplateEP ep : extensions) {
     ClassLoader classLoader = ep.getLoaderForClass();
     URL url = classLoader.getResource(ep.templatePath);
     if (url != null) {
       LocalArchivedTemplate template = new LocalArchivedTemplate(url, classLoader);
       if (ep.category) {
         TemplateBasedCategory category = new TemplateBasedCategory(template, ep.projectType);
         myTemplatesMap.putValue(new TemplatesGroup(category), template);
       } else {
         map.putValue(ep.projectType, template);
       }
     }
   }
   return map;
 }
Esempio n. 18
0
 private ExternalizableMap loadMap(String extMapName, ClassLoader loader)
     throws FileNotFoundException {
   String first = null;
   String next = extMapName;
   List<String> urls = new ArrayList<String>();
   ExternalizableMap res = null;
   while (next != null) {
     // convert the plugin class name to an xml file name
     String mapFile = next.replace('.', '/') + MAP_SUFFIX;
     URL url = loader.getResource(mapFile);
     if (url != null && urls.contains(url.toString())) {
       throw new PluginException.InvalidDefinition("Plugin inheritance loop: " + next);
     }
     // load into map
     ExternalizableMap oneMap = new ExternalizableMap();
     oneMap.loadMapFromResource(mapFile, loader);
     urls.add(url.toString());
     // apply overrides one plugin at a time in inheritance chain
     processOverrides(oneMap);
     if (res == null) {
       res = oneMap;
     } else {
       for (Map.Entry ent : oneMap.entrySet()) {
         String key = (String) ent.getKey();
         Object val = ent.getValue();
         if (!res.containsKey(key)) {
           res.setMapElement(key, val);
         }
       }
     }
     if (oneMap.containsKey(KEY_PLUGIN_PARENT)) {
       next = oneMap.getString(KEY_PLUGIN_PARENT);
     } else {
       next = null;
     }
   }
   loadedFromUrls = urls;
   return res;
 }
Esempio n. 19
0
  private void jbInit() throws Exception {
    titledBorder1 = new TitledBorder("");
    this.setLayout(baseLayout);

    double[][] lower_size = {
      {TableLayout.PREFERRED, TableLayout.FILL, 25}, {25, 25, TableLayout.FILL}
    };
    mLowerPanelLayout = new TableLayout(lower_size);

    mLowerPanel.setLayout(mLowerPanelLayout);

    double[][] dir_size = {
      {TableLayout.FILL, TableLayout.PREFERRED}, {TableLayout.PREFERRED, TableLayout.FILL}
    };
    mDirectionsPanelLayout = new TableLayout(dir_size);
    mDirectionsPanel.setLayout(mDirectionsPanelLayout);

    // Try to get icons for the toolbar buttons
    try {
      ClassLoader loader = getClass().getClassLoader();
      mAddIcon = new ImageIcon(loader.getResource(COMMON_IMG_ROOT + "/add.gif"));
      mRemoveIcon = new ImageIcon(loader.getResource(COMMON_IMG_ROOT + "/remove.gif"));
      mDisabledRemoveIcon =
          new ImageIcon(loader.getResource(COMMON_IMG_ROOT + "/remove_disabled.gif"));

      mAddNodeBtn.setIcon(mAddIcon);
      mRemoveNodeBtn.setIcon(mRemoveIcon);
      mRemoveNodeBtn.setDisabledIcon(mDisabledRemoveIcon);
    } catch (Exception e) {
      // Ack! No icons. Use text labels instead
      mAddNodeBtn.setText("Add");
      mRemoveNodeBtn.setText("Remove");
    }

    /*
    mAddNodeBtn.setMaximumSize(new Dimension(130, 33));
    mAddNodeBtn.setMinimumSize(new Dimension(130, 33));
    mAddNodeBtn.setPreferredSize(new Dimension(130, 33));
    mAddNodeBtn.setText("Add Node");
    */
    mAddNodeBtn.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            mAddNodeBtn_actionPerformed(e);
          }
        });
    /*
    mRemoveNodeBtn.setMaximumSize(new Dimension(130, 33));
    mRemoveNodeBtn.setMinimumSize(new Dimension(130, 33));
    mRemoveNodeBtn.setPreferredSize(new Dimension(130, 33));
    mRemoveNodeBtn.setText("Remove Node");
    */
    mRemoveNodeBtn.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            mRemoveNode();
          }
        });
    mHostnameLabel.setHorizontalAlignment(SwingConstants.TRAILING);
    mHostnameLabel.setLabelFor(mHostnameField);
    mHostnameLabel.setText("Hostname:");

    mHostnameField.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            mAddNodeBtn_actionPerformed(e);
          }
        });
    mDirectionsPanel.setBorder(BorderFactory.createEtchedBorder());
    mTitleLabel.setFont(new java.awt.Font("Serif", 1, 20));
    mTitleLabel.setHorizontalAlignment(SwingConstants.CENTER);
    mTitleLabel.setText("Add Cluster Nodes");
    mDirectionsLabel.setText("Click on the add button to add nodes to your cluster configuration.");
    mDirectionsLabel.setLineWrap(true);
    mDirectionsLabel.setEditable(false);
    mDirectionsLabel.setBackground(mTitleLabel.getBackground());

    baseLayout.setHgap(5);
    baseLayout.setVgap(5);
    mLowerPanel.add(
        mHostnameLabel, new TableLayoutConstraints(0, 0, 0, 0, TableLayout.FULL, TableLayout.FULL));
    mLowerPanel.add(
        mHostnameField, new TableLayoutConstraints(1, 0, 1, 0, TableLayout.FULL, TableLayout.FULL));
    mLowerPanel.add(
        mListScrollPane1,
        new TableLayoutConstraints(0, 1, 1, 2, TableLayout.FULL, TableLayout.FULL));
    mLowerPanel.add(
        mAddNodeBtn, new TableLayoutConstraints(2, 0, 2, 0, TableLayout.FULL, TableLayout.FULL));
    mLowerPanel.add(
        mRemoveNodeBtn, new TableLayoutConstraints(2, 1, 2, 1, TableLayout.FULL, TableLayout.FULL));
    this.add(mLowerPanel, BorderLayout.CENTER);
    mListScrollPane1.getViewport().add(lstNodes, null);
    mDirectionsPanel.add(
        mTitleLabel, new TableLayoutConstraints(0, 0, 0, 0, TableLayout.FULL, TableLayout.FULL));
    mDirectionsPanel.add(
        mDirectionsLabel,
        new TableLayoutConstraints(0, 1, 0, 1, TableLayout.FULL, TableLayout.FULL));
    mDirectionsPanel.add(
        mIconLabel, new TableLayoutConstraints(1, 0, 1, 1, TableLayout.FULL, TableLayout.FULL));
    this.add(mDirectionsPanel, BorderLayout.NORTH);
  }
Esempio n. 20
0
  URL findResource(String name, boolean checkParent) {
    if ((name.length() > 1) && (name.charAt(0) == '/')) /* if name has a leading slash */
      name = name.substring(1); /* remove leading slash before search */
    String pkgName = getResourcePackageName(name);
    boolean bootDelegation = false;
    ClassLoader parentCL = getParentClassLoader();
    // follow the OSGi delegation model
    // First check the parent classloader for system resources, if it is a java resource.
    if (checkParent && parentCL != null) {
      if (pkgName.startsWith(JAVA_PACKAGE))
        // 1) if startsWith "java." delegate to parent and terminate search
        // we never delegate java resource requests past the parent
        return parentCL.getResource(name);
      else if (bundle.getFramework().isBootDelegationPackage(pkgName)) {
        // 2) if part of the bootdelegation list then delegate to parent and continue of failure
        URL result = parentCL.getResource(name);
        if (result != null) return result;
        bootDelegation = true;
      }
    }

    URL result = null;
    try {
      result = (URL) searchHooks(name, PRE_RESOURCE);
    } catch (FileNotFoundException e) {
      return null;
    } catch (ClassNotFoundException e) {
      // will not happen
    }
    if (result != null) return result;
    // 3) search the imported packages
    PackageSource source = findImportedSource(pkgName, null);
    if (source != null)
      // 3) found import source terminate search at the source
      return source.getResource(name);
    // 4) search the required bundles
    source = findRequiredSource(pkgName, null);
    if (source != null)
      // 4) attempt to load from source but continue on failure
      result = source.getResource(name);
    // 5) search the local bundle
    if (result == null) result = findLocalResource(name);
    if (result != null) return result;
    // 6) attempt to find a dynamic import source; only do this if a required source was not found
    if (source == null) {
      source = findDynamicSource(pkgName);
      if (source != null)
        // must return the result of the dynamic import and do not continue
        return source.getResource(name);
    }

    if (result == null)
      try {
        result = (URL) searchHooks(name, POST_RESOURCE);
      } catch (FileNotFoundException e) {
        return null;
      } catch (ClassNotFoundException e) {
        // will not happen
      }
    // do buddy policy loading
    if (result == null && policy != null) result = policy.doBuddyResourceLoading(name);
    if (result != null) return result;
    // hack to support backwards compatibiility for bootdelegation
    // or last resort; do class context trick to work around VM bugs
    if (parentCL != null
        && !bootDelegation
        && ((checkParent && bundle.getFramework().compatibiltyBootDelegation) || isRequestFromVM()))
      // we don't need to continue if the resource is not found here
      return parentCL.getResource(name);
    return result;
  }
Esempio n. 21
0
/**
 * QSAdminGUI - Control Panel for QuickServer Admin GUI - QSAdminGUI
 *
 * @author Akshathkumar Shetty
 * @since 1.3
 */
public class QSAdminGUI extends JPanel /*JFrame*/ {
  private static Logger logger = Logger.getLogger(QSAdminGUI.class.getName());

  private static QSAdminMain qsadminMain = null;
  private static String pluginDir = "./../plugin";

  private ClassLoader classLoader = getClass().getClassLoader();
  public ImageIcon logo = new ImageIcon(classLoader.getResource("icons/logo.gif"));
  public ImageIcon logoAbout = new ImageIcon(classLoader.getResource("icons/logo.png"));
  public ImageIcon ball = new ImageIcon(classLoader.getResource("icons/ball.gif"));

  private HeaderPanel headerPanel;
  private MainCommandPanel mainCommandPanel;
  private CmdConsole cmdConsole;
  private PropertiePanel propertiePanel;
  // private StatsPanel statsPanel;

  private JTabbedPane tabbedPane;
  private JFrame parentFrame;

  final HashMap pluginPanelMap = new HashMap();

  // --v1.3.2
  private ArrayList plugins = new ArrayList();

  private JMenu mainMenu, helpMenu;
  private JMenuBar jMenuBar;
  private JMenuItem loginMenuItem, exitMenuItem, aboutMenuItem;

  /** Logs the interaction, Type can be S - Server Sent C - Client Sent */
  public void logComand(String command, char type) {
    logger.info("For[" + type + "] " + command);
  }

  /** Displays the QSAdminGUi with in a JFrame. */
  public static void showGUI(String args[], final SplashScreen splash) {
    java.awt.EventQueue.invokeLater(
        new Runnable() {
          public void run() {
            try {
              UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
            } catch (Exception e) {
              try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (Exception ee) {
              }
            }

            qsadminMain = new QSAdminMain();

            JFrame frame = new JFrame("QSAdmin GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            QSAdminGUI qsAdminGUI = new QSAdminGUI(qsadminMain, frame);
            qsAdminGUI.updateConnectionStatus(false);
            frame.getContentPane().add(qsAdminGUI);
            frame.pack();
            frame.setSize(700, 450);
            frame.setIconImage(qsAdminGUI.logo.getImage());
            JFrameUtilities.centerWindow(frame);
            frame.setVisible(true);
            if (splash != null) splash.kill();
          }
        });
  }

  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();
  }

  public void setStatus(String msg) {
    headerPanel.setStatus(msg);
  }

  public void setResponse(String res) {
    int msgType = JOptionPane.PLAIN_MESSAGE;
    if (res.startsWith("+OK")) msgType = JOptionPane.INFORMATION_MESSAGE;
    if (res.startsWith("-ERR")) msgType = JOptionPane.ERROR_MESSAGE;
    JOptionPane.showMessageDialog(
        QSAdminGUI.this, res.substring(res.indexOf(" ") + 1), "Response", msgType);
  }

  public void appendToConsole(String msg) {
    cmdConsole.append(msg);
  }

  public void setConsoleSend(boolean flag) {
    cmdConsole.setSendEdit(flag);
  }

  public void updateConnectionStatus(boolean connected) {
    if (connected == true) {
      headerPanel.setLogoutText();
      loginMenuItem.setText("Logout");
    } else {
      headerPanel.setLoginText();
      loginMenuItem.setText("Login...");
    }
    mainCommandPanel.updateConnectionStatus(connected);
    propertiePanel.updateConnectionStatus(connected);
    cmdConsole.updateConnectionStatus(connected);
    Iterator iterator = plugins.iterator();
    PluginPanel updatePluginPanel = null;
    while (iterator.hasNext()) {
      updatePluginPanel = (PluginPanel) iterator.next();
      updatePluginPanel.updateConnectionStatus(connected);
    }

    if (connected == true) {
      int selected = tabbedPane.getSelectedIndex();
      if (selected >= 2) {
        ((PluginPanel) pluginPanelMap.get("" + selected)).activated();
      }
    }
  }

  // --v1.3.2
  public static void setPluginDir(String dir) {
    pluginDir = dir;
  }

  public static String getPluginDir() {
    return pluginDir;
  }

  private void buildMenu() {
    jMenuBar = new javax.swing.JMenuBar();
    mainMenu = new javax.swing.JMenu();
    mainMenu.setText("Main");

    loginMenuItem = new JMenuItem("Login...");
    loginMenuItem.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            headerPanel.handleLoginLogout();
          }
        });

    mainMenu.add(loginMenuItem);

    exitMenuItem = new JMenuItem("Exit");
    exitMenuItem.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (qsadminMain.isConnected() == true) {
              headerPanel.handleLoginLogout();
            }
            System.exit(0);
          }
        });
    mainMenu.add(exitMenuItem);

    helpMenu = new javax.swing.JMenu();
    helpMenu.setText("Help");

    aboutMenuItem = new JMenuItem("About...");
    aboutMenuItem.setEnabled(true);
    aboutMenuItem.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            about();
          }
        });
    helpMenu.add(aboutMenuItem);

    jMenuBar.add(mainMenu);
    jMenuBar.add(helpMenu);

    parentFrame.setJMenuBar(jMenuBar);
  }

  private void about() {
    JOptionPane.showMessageDialog(
        this,
        "QSAdminGUI\n\n"
            + "GUI Client for QSAdminServer of QuickServer.\n"
            + "This is compliant with QuickServer v"
            + QSAdminMain.VERSION_OF_SERVER
            + " release.\n\n"
            + "Copyright (C) QuickServer.org\n"
            + "http://www.quickserver.org",
        "About QSAdminGUI",
        JOptionPane.INFORMATION_MESSAGE,
        logoAbout);
  }
}
Esempio n. 22
0
  public static boolean showLicensing() {
    if (Config.getLicenseResource() == null) return true;
    ClassLoader cl = Main.class.getClassLoader();
    URL url = cl.getResource(Config.getLicenseResource());
    if (url == null) return true;

    String license = null;
    try {
      URLConnection con = url.openConnection();
      int size = con.getContentLength();
      byte[] content = new byte[size];
      InputStream in = new BufferedInputStream(con.getInputStream());
      in.read(content);
      license = new String(content);
    } catch (IOException ioe) {
      Config.trace("Got exception when reading " + Config.getLicenseResource() + ": " + ioe);
      return false;
    }

    // Build dialog
    JTextArea ta = new JTextArea(license);
    ta.setEditable(false);
    final JDialog jd = new JDialog(_installerFrame, true);
    Container comp = jd.getContentPane();
    jd.setTitle(Config.getLicenseDialogTitle());
    comp.setLayout(new BorderLayout(10, 10));
    comp.add(new JScrollPane(ta), "Center");
    Box box = new Box(BoxLayout.X_AXIS);
    box.add(box.createHorizontalStrut(10));
    box.add(new JLabel(Config.getLicenseDialogQuestionString()));
    box.add(box.createHorizontalGlue());
    JButton acceptButton = new JButton(Config.getLicenseDialogAcceptString());
    JButton exitButton = new JButton(Config.getLicenseDialogExitString());
    box.add(acceptButton);
    box.add(box.createHorizontalStrut(10));
    box.add(exitButton);
    box.add(box.createHorizontalStrut(10));
    jd.getRootPane().setDefaultButton(acceptButton);
    Box box2 = new Box(BoxLayout.Y_AXIS);
    box2.add(box);
    box2.add(box2.createVerticalStrut(5));
    comp.add(box2, "South");
    jd.pack();

    final boolean accept[] = new boolean[1];
    acceptButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            accept[0] = true;
            jd.hide();
            jd.dispose();
          }
        });

    exitButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            accept[0] = false;
            jd.hide();
            jd.dispose();
          }
        });

    // Apply any defaults the user may have, constraining to the size
    // of the screen, and default (packed) size.
    Rectangle size = new Rectangle(0, 0, 500, 300);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    size.width = Math.min(screenSize.width, size.width);
    size.height = Math.min(screenSize.height, size.height);
    // Center the window
    jd.setBounds(
        (screenSize.width - size.width) / 2,
        (screenSize.height - size.height) / 2,
        size.width,
        size.height);

    // Show dialog
    jd.show();

    return accept[0];
  }
Esempio n. 23
0
  /** Unpacks a resource to a temp. file */
  public static File unpackInstaller(String resourceName) {
    // Array to hold all results (this code is slightly more
    // generally that it needs to be)
    File[] results = new File[1];
    URL[] urls = new URL[1];

    // Determine size of download
    ClassLoader cl = Main.class.getClassLoader();
    urls[0] = cl.getResource(Config.getInstallerResource());
    if (urls[0] == null) {
      Config.trace("Could not find resource: " + Config.getInstallerResource());
      return null;
    }

    int totalSize = 0;
    int totalRead = 0;
    for (int i = 0; i < urls.length; i++) {
      if (urls[i] != null) {
        try {
          URLConnection connection = urls[i].openConnection();
          totalSize += connection.getContentLength();
        } catch (IOException ioe) {
          Config.trace("Got exception: " + ioe);
          return null;
        }
      }
    }

    // Unpack each file
    for (int i = 0; i < urls.length; i++) {
      if (urls[i] != null) {
        // Create temp. file to store unpacked file in
        InputStream in = null;
        OutputStream out = null;
        try {
          // Use extension from URL (important for dll files)
          String extension = new File(urls[i].getFile()).getName();
          int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1;
          if (lastdotidx == -1) {
            extension = ".dat";
          } else {
            extension = extension.substring(lastdotidx);
          }

          // Create output stream
          results[i] = File.createTempFile("jre", extension);
          results[i].deleteOnExit();
          out = new FileOutputStream(results[i]);

          // Create inputstream
          URLConnection connection = urls[i].openConnection();
          in = connection.getInputStream();

          int read = 0;
          byte[] buf = new byte[BUFFER_SIZE];
          while ((read = in.read(buf)) != -1) {
            out.write(buf, 0, read);
            // Notify delegate
            totalRead += read;
            if (totalRead > totalSize && totalSize != 0) totalSize = totalRead;

            // Update UI
            if (totalSize != 0) {
              int percent = (100 * totalRead) / totalSize;
              setStepText(STEP_UNPACK, Config.getWindowStepProgress(STEP_UNPACK, percent));
            }
          }
        } catch (IOException ie) {
          Config.trace("Got exception while downloading resource: " + ie);
          for (int j = 0; j < results.length; j++) {
            if (results[j] != null) results[j].delete();
          }
          return null;
        } finally {
          try {
            if (in != null) in.close();
            if (out != null) out.close();
          } catch (IOException io) {
            /* ignore */
          }
        }
      }
    }

    setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK));
    return results[0];
  }
Esempio n. 24
0
 public URL getResource(String name) {
   return loader.getResource(name);
 }
Esempio n. 25
0
 public URL getEntry(String path) {
   if (path.startsWith("/")) path = path.substring(1);
   return loader.getResource(path);
 }
Esempio n. 26
0
  private static boolean changeLocale(Locale newLocale, boolean force) {
    // set locale for startup (will override immediately it on locale change anyway)
    Locale.setDefault(newLocale);

    if (!isCurrentLocale(newLocale) || force) {
      Locale.setDefault(LOCALE_DEFAULT);
      ResourceBundle newResourceBundle = null;
      String bundleFolder = BUNDLE_NAME.replace('.', '/');
      final String prefix = BUNDLE_NAME.substring(BUNDLE_NAME.lastIndexOf('.') + 1);
      final String extension = ".properties";

      if (newLocale.equals(LOCALE_ENGLISH)) newLocale = LOCALE_DEFAULT;

      try {
        File userBundleFile = new File(SystemProperties.getUserPath());
        File appBundleFile = new File(SystemProperties.getApplicationPath());

        // Get the jarURL
        // XXX Is there a better way to get the JAR name?
        ClassLoader cl = MessageText.class.getClassLoader();
        String sJar = cl.getResource(bundleFolder + extension).toString();
        sJar = sJar.substring(0, sJar.length() - prefix.length() - extension.length());
        URL jarURL = new URL(sJar);

        // User dir overrides app dir which overrides jar file bundles
        URL[] urls = {userBundleFile.toURL(), appBundleFile.toURL(), jarURL};

        /* This is debugging code, use it when things go wrong :) The line number
         * is approximate as the input stream is buffered by the reader...

        {
        	LineNumberInputStream lnis	= null;

            try{
                ClassLoader fff = new URLClassLoader(urls);

                java.io.InputStream stream = fff.getResourceAsStream("MessagesBundle_th_TH.properties");

                lnis = new LineNumberInputStream( stream );

                new java.util.PropertyResourceBundle(lnis);
            }catch( Throwable e ){

            	System.out.println( lnis.getLineNumber());

            	e.printStackTrace();
            }
        }
        */

        newResourceBundle =
            getResourceBundle("MessagesBundle", newLocale, new URLClassLoader(urls));
        // do more searches if getBundle failed, or if the language is not the
        // same and the user wanted a specific country
        if ((!newResourceBundle.getLocale().getLanguage().equals(newLocale.getLanguage())
            && !newLocale.getCountry().equals(""))) {

          Locale foundLocale = newResourceBundle.getLocale();
          System.out.println(
              "changeLocale: "
                  + (foundLocale.toString().equals("")
                      ? "*Default Language*"
                      : foundLocale.getDisplayLanguage())
                  + " != "
                  + newLocale.getDisplayName()
                  + ". Searching without country..");
          // try it without the country
          Locale localeJustLang = new Locale(newLocale.getLanguage());
          newResourceBundle =
              getResourceBundle("MessagesBundle", localeJustLang, new URLClassLoader(urls));

          if (newResourceBundle == null
              || !newResourceBundle
                  .getLocale()
                  .getLanguage()
                  .equals(localeJustLang.getLanguage())) {
            // find first language we have in our list
            System.out.println(
                "changeLocale: Searching for language "
                    + newLocale.getDisplayLanguage()
                    + " in *any* country..");
            Locale[] locales = getLocales();
            for (int i = 0; i < locales.length; i++) {
              if (locales[i].getLanguage() == newLocale.getLanguage()) {
                newResourceBundle =
                    getResourceBundle("MessagesBundle", locales[i], new URLClassLoader(urls));
                break;
              }
            }
          }
        }
      } catch (MissingResourceException e) {
        System.out.println("changeLocale: no resource bundle for " + newLocale);
        Debug.printStackTrace(e);
        return false;
      } catch (Exception e) {
        Debug.printStackTrace(e);
      }

      if (newResourceBundle != null) {
        if (!newLocale.equals(LOCALE_DEFAULT) && !newResourceBundle.getLocale().equals(newLocale)) {
          String sNewLanguage = newResourceBundle.getLocale().getDisplayName();
          if (sNewLanguage == null || sNewLanguage.trim().equals(""))
            sNewLanguage = "English (default)";
          System.out.println(
              "changeLocale: no message properties for Locale '"
                  + newLocale.getDisplayName()
                  + "' ("
                  + newLocale
                  + "), using '"
                  + sNewLanguage
                  + "'");
        }
        newLocale = newResourceBundle.getLocale();
        Locale.setDefault(newLocale.equals(LOCALE_DEFAULT) ? LOCALE_ENGLISH : newLocale);
        LOCALE_CURRENT = newLocale;
        setResourceBundle(new IntegratedResourceBundle(newResourceBundle, pluginLocalizationPaths));
        if (newLocale.equals(LOCALE_DEFAULT)) DEFAULT_BUNDLE = RESOURCE_BUNDLE;
        return true;
      } else return false;
    }
    return false;
  }
Esempio n. 27
0
 public static Image load(String res) throws IOException {
   ClassLoader cl = Utility.class.getClassLoader();
   return (ImageIO.read(cl.getResource(res)));
 }
 @Test
 public void testResourceLookupBeforeLoading() throws Exception {
   assertThat(
       classLoader.getResource(Foo.class.getName().replace('.', '/') + CLASS_FILE),
       expectedResourceLookup ? notNullValue(URL.class) : nullValue(URL.class));
 }