Beispiel #1
0
 /**
  * Set persistent value.
  *
  * @param uri Data URI
  * @param data Data String
  * @return true on success, else false
  */
 public static boolean setValue(String uri, String data) {
   Logger logger = Core.getLogger();
   javax.jnlp.PersistenceService ps = null;
   String codebase = null;
   try {
     ps =
         (javax.jnlp.PersistenceService)
             javax.jnlp.ServiceManager.lookup("javax.jnlp.PersistenceService");
     javax.jnlp.BasicService bs =
         (javax.jnlp.BasicService) javax.jnlp.ServiceManager.lookup("javax.jnlp.BasicService");
     codebase = bs.getCodeBase().toString();
   } catch (Exception ex) {
     logger.warning("Unable to look up PersistenceService: " + ex);
     return false;
   }
   URL key = null;
   javax.jnlp.FileContents fc = null;
   try {
     key = new URL(codebase + uri);
   } catch (MalformedURLException ex) {
     Core.getLogger().warning("Unable to build persistence service uri: " + ex);
     return false;
   }
   try {
     ps.create(key, data.getBytes().length);
     fc = ps.get(key);
     fc.getOutputStream(false).write(data.getBytes());
     return true;
   } catch (Exception ex) {
     logger.warning("Unable to write to persistence service: " + ex);
   }
   return false;
 }
Beispiel #2
0
 /**
  * Get persistent value.
  *
  * @param uri Data URI
  * @return Data String or null if not present
  */
 public static String getValue(String uri) {
   Logger logger = Core.getLogger();
   javax.jnlp.PersistenceService ps = null;
   String codebase = null;
   try {
     ps =
         (javax.jnlp.PersistenceService)
             javax.jnlp.ServiceManager.lookup("javax.jnlp.PersistenceService");
     javax.jnlp.BasicService bs =
         (javax.jnlp.BasicService) javax.jnlp.ServiceManager.lookup("javax.jnlp.BasicService");
     codebase = bs.getCodeBase().toString();
   } catch (Exception ex) {
     logger.warning("Unable to look up PersistenceService: " + ex);
     return null;
   }
   URL key = null;
   javax.jnlp.FileContents fc = null;
   try {
     key = new URL(codebase + uri);
   } catch (MalformedURLException ex) {
     Core.getLogger().warning("Unable to build persistence service uri: " + ex);
     return null;
   }
   try {
     fc = ps.get(key);
     byte[] b = new byte[(int) fc.getLength()];
     fc.getInputStream().read(b);
     return new String(b);
   } catch (Exception ex) {
     return null; // Failed to put something
   }
 }
  private static synchronized void initialize() {

    try {
      fos = (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService");
      fss = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
    } catch (UnavailableServiceException e) {
    }
  }
  /** @see org.newdawn.slick.muffin.Muffin#saveFile(java.util.HashMap, java.lang.String) */
  public void saveFile(HashMap scoreMap, String fileName) throws IOException {

    PersistenceService ps;
    BasicService bs;
    URL configURL;

    try {
      ps = (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService");
      bs = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
      URL baseURL = bs.getCodeBase();
      // System.out.println("CodeBase was " + baseURL);
      configURL = new URL(baseURL, fileName);
    } catch (Exception e) {
      Log.error(e);
      throw new IOException("Failed to save state: ");
    }

    try {
      ps.delete(configURL);
    } catch (Exception e) {
      Log.info("No exisiting Muffin Found - First Save");
    }

    try {
      ps.create(configURL, 1024); // 1024 bytes for our data

      FileContents fc = ps.get(configURL);
      DataOutputStream oos = new DataOutputStream(fc.getOutputStream(false));

      // scroll through hashMap and write key and value to file
      Set keys = scoreMap.keySet(); // get the keys

      // get values using keys
      for (Iterator i = keys.iterator(); i.hasNext(); ) {
        String key = (String) i.next();

        oos.writeUTF(key);

        if (fileName.endsWith("Number")) {
          double value = ((Double) scoreMap.get(key)).doubleValue();
          oos.writeDouble(value);
        } else {
          String value = (String) scoreMap.get(key);
          oos.writeUTF(value);
        }
      }

      oos.flush();
      oos.close();
    } catch (Exception e) {
      Log.error(e);
      throw new IOException("Failed to store map of state data");
    }
  }
Beispiel #5
0
  /**
   * Opens the online help
   *
   * @return boolean Return true if you open the online help, returns false otherwise
   */
  private static void riskOpenURL(URL docs) throws Exception {

    if (applet != null) {

      applet.getAppletContext().showDocument(docs, "_blank");
    } else if (webstart != null) {

      javax.jnlp.BasicService bs =
          (javax.jnlp.BasicService) javax.jnlp.ServiceManager.lookup("javax.jnlp.BasicService");

      boolean good = bs.showDocument(docs);

      if (!good) {

        throw new Exception("unable to open URL: " + docs);
      }

    } else {

      BrowserLauncher.openURL(docs.toString());
    }

    /*
    		if (applet == null ) {

    			File file = new File(docs);
    			openURL(new URL("file://" + file.getAbsolutePath()) );

    		}
    		else {

    			URL url = applet.getCodeBase(); // get url of the applet

    			openURL(new URL(url+docs));

    		}


    		try {

    			String cmd=null;

    			String os = System.getProperty("os.name");

    			if ( os != null && os.startsWith("Windows")) {
    				cmd = "rundll32 url.dll,FileProtocolHandler file://"+ file.getAbsolutePath();
    			}
    			else {
    				cmd = "mozilla file://"+ file.getAbsolutePath();
    			}

    			Runtime.getRuntime().exec(cmd);

    			return true;
    		}
    		catch(IOException x) {
    			return false;
    		}
    */
  }
  // constructor initializes LogoAnimatorJPanel by loading images
  public LogoAnimatorJPanel() {
    try {
      // get reference to FileOpenService
      FileOpenService fileOpenService =
          (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService");

      // display dialog that allows user to select multiple files
      FileContents[] contents = fileOpenService.openMultiFileDialog(null, null);

      // create array to store ImageIcon references
      images = new ImageIcon[contents.length];

      // load the selected images
      for (int count = 0; count < images.length; count++) {
        // create byte array to store an image's data
        byte[] imageData = new byte[(int) contents[count].getLength()];

        // get image's data and create image
        contents[count].getInputStream().read(imageData);
        images[count] = new ImageIcon(imageData);
      } // end for

      // this example assumes all images have the same width and height
      width = images[0].getIconWidth(); // get icon width
      height = images[0].getIconHeight(); // get icon height
    } // end try
    catch (Exception e) {
      e.printStackTrace();
    } // end catch
  } // end LogoAnimatorJPanel constructor
Beispiel #7
0
  private static URL getRiskFileURL(String a) {

    try {

      if (applet != null) {

        return new URL(applet.getCodeBase(), a);

      } else if (webstart != null) {

        javax.jnlp.BasicService bs =
            (javax.jnlp.BasicService) javax.jnlp.ServiceManager.lookup("javax.jnlp.BasicService");

        return new URL(bs.getCodeBase(), a);

      } else {

        return new File(a).toURI().toURL();
      }

    } catch (Exception e) {

      throw new RuntimeException(e);
    }
  }
  /** @see org.newdawn.slick.muffin.Muffin#loadFile(java.lang.String) */
  public HashMap loadFile(String fileName) throws IOException {
    HashMap hashMap = new HashMap();

    try {
      PersistenceService ps =
          (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService");
      BasicService bs = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
      URL baseURL = bs.getCodeBase();
      URL configURL = new URL(baseURL, fileName);
      FileContents fc = ps.get(configURL);
      DataInputStream ois = new DataInputStream(fc.getInputStream());

      // read in data from muffin
      String key;

      // load hashMap as <String, Int> or <String, String>
      if (fileName.endsWith("Number")) {
        double value;
        // while not end of file
        while ((key = ois.readUTF()) != null) {
          value = ois.readDouble();
          // load value into hashMap
          hashMap.put(key, new Double(value));
        }
      } else {
        String value;
        // while not end of file
        while ((key = ois.readUTF()) != null) {
          value = ois.readUTF();
          // load value into hashMap
          hashMap.put(key, value);
        }
      }

      ois.close();
    } catch (EOFException e) {
      // End of the file reached, do nothing
    } catch (IOException e) {
      // No data there - thats ok, just not saved before
    } catch (Exception e) {
      Log.error(e);
      throw new IOException("Failed to load state from webstart muffin");
    }

    return hashMap;
  }
Beispiel #9
0
  public static String getLoadFileName(Frame frame) {

    if (applet != null) {

      showAppletWarning(frame);

      return null;
    }

    String extension = RiskFileFilter.RISK_SAVE_FILES;

    if (webstart != null) {

      try {

        javax.jnlp.FileOpenService fos =
            (javax.jnlp.FileOpenService)
                javax.jnlp.ServiceManager.lookup("javax.jnlp.FileOpenService");

        javax.jnlp.FileContents fc = fos.openFileDialog(SAVES_DIR, new String[] {extension});

        if (fc != null) {

          fileio.put(fc.getName(), fc);

          return fc.getName();
        } else {

          return null;
        }
      } catch (Exception e) {

        return null;
      }
    } else {

      File dir = getSaveGameDir();
      JFileChooser fc = new JFileChooser(dir);

      fc.setFileFilter(new RiskFileFilter(extension));

      int returnVal =
          fc.showDialog(
              frame, TranslationBundle.getBundle().getString("mainmenu.loadgame.loadbutton"));
      if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {

        java.io.File file = fc.getSelectedFile();
        // Write your code here what to do with selected file
        return file.getAbsolutePath();

      } else {
        // Write your code here what to do if user has canceled Open dialog
        return null;
      }
    }
  }
 /** Register as a Java Web Start listener */
 private void registerJnlpListener() {
   try {
     sis = (SingleInstanceService) ServiceManager.lookup("javax.jnlp.SingleInstanceService");
     sisL = new SISListener();
     sis.addSingleInstanceListener(sisL);
   } catch (UnavailableServiceException e) {
     sis = null;
     logger.warn("Cannot create single instance service for web start");
   }
 }
    public void actionPerformed(ActionEvent e) {

      try {
        sysClipboard = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
        writeToClipboard();
      } catch (UnavailableServiceException use) {
        System.err.println(use);
        sysClipboard = null;
      }
    }
Beispiel #12
0
 /**
  * Check if JNLP functionality is available.
  *
  * @return true if available, else false
  */
 public static boolean isAvailable() {
   try {
     Class.forName("javax.jnlp.ServiceManager");
     javax.jnlp.PersistenceService ps =
         (javax.jnlp.PersistenceService)
             javax.jnlp.ServiceManager.lookup("javax.jnlp.PersistenceService");
   } catch (Exception ex) {
     System.out.println("JNLP.PersistenceService is not available: " + ex);
     return false;
   }
   return true;
 }
Beispiel #13
0
 /**
  * Quick test to see if running through Java webstart
  *
  * @return True if jws running
  */
 private boolean isWebstartAvailable() {
   try {
     Class.forName("javax.jnlp.ServiceManager");
     // this causes to go and see if the service is available
     ServiceManager.lookup("javax.jnlp.PersistenceService");
     Log.info("Webstart detected using Muffins");
   } catch (Exception e) {
     Log.info("Using Local File System");
     return false;
   }
   return true;
 }
  protected URL getURL(String filename) throws Exception {
    BasicService bs = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");

    URL codeBase = bs.getCodeBase();
    URL url = null;

    try {
      url = new URL(codeBase, filename);
    } catch (java.net.MalformedURLException e) {
      System.out.println("Couldn't create image: badly specified URL");
      return null;
    }
    return url;
  }
  /**
   * Overridden to fill the location with the path from the {@link #propertyLocationSystemProperty}
   *
   * @param props propeties instance to fill
   * @throws IOException
   */
  @Override
  protected void loadProperties(Properties props) throws IOException {
    Resource location = null;
    String webAppContextUrl = null;
    try {
      BasicService basicService = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
      String codeBase = basicService.getCodeBase().toExternalForm();
      System.out.println("codeBase=[" + codeBase + "]");
      if (!codeBase.endsWith("/")) {
        codeBase += "/";
      }
      int webAppContextUrlLength = codeBase.lastIndexOf("applications");
      webAppContextUrl = codeBase.substring(0, webAppContextUrlLength) + "config/";
      System.out.println("webAppContextUrl=[" + webAppContextUrl + "]");
    } catch (Exception e) {
      // TODO logging
      e.printStackTrace();
    }
    location = appContext.getResource("url:" + webAppContextUrl);

    setLocation(location);
    super.loadProperties(props);
  }
Beispiel #16
0
  public static void saveFile(String name, RiskGame obj) throws Exception {

    // it is impossible for a applet to get here

    if (webstart != null) {
      ByteArrayOutputStream stor = new ByteArrayOutputStream();
      obj.saveGame(stor);
      InputStream stream = new ByteArrayInputStream(stor.toByteArray());

      javax.jnlp.FileSaveService fss =
          (javax.jnlp.FileSaveService)
              javax.jnlp.ServiceManager.lookup("javax.jnlp.FileSaveService");
      javax.jnlp.FileContents fc =
          fss.saveFileDialog(
              name.substring(0, name.indexOf('/') + 1),
              new String[] {name.substring(name.indexOf('.') + 1)},
              stream,
              name.substring(name.indexOf('/') + 1, name.indexOf('.')));
    } else {
      FileOutputStream fileout = new FileOutputStream(name);
      obj.saveGame(fileout);
    }
  }
Beispiel #17
0
  public boolean test() {
    ExtendedService es = null;
    boolean ok = true;

    String tmpfilename = getParameter("tmpfile");

    try {
      // Lookup the javax.jnlp.ExtendedService object
      es = (ExtendedService) ServiceManager.lookup("javax.jnlp.ExtendedService");
    } catch (UnavailableServiceException ue) {
      System.out.println(ue);
      ue.printStackTrace();
      // Service is not supported
      ok = false;
    }
    if (!ok) return false;

    // Open a specific file in the local machine

    File tmpfile = new File(tmpfilename);

    // Java Web Start will pop up a dialog asking the user to grant permission
    // to read/write the file 'tempfile'

    try {
      FileContents fc_tmpfile = es.openFile(tmpfile);

      if (!tmpfilename.equals(fc_tmpfile.getName())) {
        System.out.println(
            "\t tmpfile(out): "
                + tmpfilename
                + ", unequal to fc-filename: "
                + fc_tmpfile.getName()
                + " - info");
        // ok=false;
        // return ok;
      }

      if (!fc_tmpfile.canWrite()) {
        System.out.println(
            "\t outfile: " + tmpfilename + ", no write access (may not exist yet) - info");
      }

      // You can now use the FileContents object to read/write the file

      java.io.OutputStream sout = fc_tmpfile.getOutputStream(true);

      BufferedWriter bwsout = new BufferedWriter(new OutputStreamWriter(sout));

      bwsout.write(datum, 0, datum.length());
      bwsout.flush();
      bwsout.close();
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
      System.out.println("\t Error while IO write - failed");
      ok = false;
      return ok;
    }

    // read back ..
    try {
      FileContents fc_tmpfile = es.openFile(tmpfile);

      if (!tmpfilename.equals(fc_tmpfile.getName())) {
        System.out.println(
            "\t tmpfile(in): "
                + tmpfilename
                + ", unequal to fc-filename: "
                + fc_tmpfile.getName()
                + " - info");
        // ok=false;
        // return ok;
      }

      if (!fc_tmpfile.canRead()) {
        System.out.println("\t outfile: " + tmpfilename + ", read access failed");
        ok = false;
      }

      // You can now use the FileContents object to read/write the file

      java.io.InputStream sin = fc_tmpfile.getInputStream();
      BufferedReader brsin = new BufferedReader(new InputStreamReader(sin));
      String in = brsin.readLine();

      if (!in.equals(datum)) {
        System.out.println("\t file content <" + in + "> does not match <" + datum + "> - failed");
        ok = false;
      }
      brsin.close();
    } catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
      System.out.println("\t Error while IO read - failed");
      ok = false;
      return ok;
    }

    return ok;
  }
 private static <T> T lookup(Class<T> type) throws UnavailableServiceException {
   return (T) ServiceManager.lookup(type.getName());
 }