コード例 #1
1
ファイル: SVGApplet.java プロジェクト: ilyessou/jhotdraw
  /**
   * Loads the drawing. By convention this method is invoked on a worker thread.
   *
   * @param progress A ProgressIndicator to inform the user about the progress of the operation.
   * @return The Drawing that was loaded.
   */
  protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
    Drawing drawing = createDrawing();
    if (getParameter("datafile") != null) {
      URL url = new URL(getDocumentBase(), getParameter("datafile"));
      URLConnection uc = url.openConnection();

      // Disable caching. This ensures that we always request the
      // newest version of the drawing from the server.
      // (Note: The server still needs to set the proper HTTP caching
      // properties to prevent proxies from caching the drawing).
      if (uc instanceof HttpURLConnection) {
        ((HttpURLConnection) uc).setUseCaches(false);
      }

      // Read the data into a buffer
      int contentLength = uc.getContentLength();
      InputStream in = uc.getInputStream();
      try {
        if (contentLength != -1) {
          in = new BoundedRangeInputStream(in);
          ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
          progress.setProgressModel((BoundedRangeModel) in);
          progress.setIndeterminate(false);
        }
        BufferedInputStream bin = new BufferedInputStream(in);
        bin.mark(512);

        // Read the data using all supported input formats
        // until we succeed
        IOException formatException = null;
        for (InputFormat format : drawing.getInputFormats()) {
          try {
            bin.reset();
          } catch (IOException e) {
            uc = url.openConnection();
            in = uc.getInputStream();
            in = new BoundedRangeInputStream(in);
            ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
            progress.setProgressModel((BoundedRangeModel) in);
            bin = new BufferedInputStream(in);
            bin.mark(512);
          }
          try {
            bin.reset();
            format.read(bin, drawing, true);
            formatException = null;
            break;
          } catch (IOException e) {
            formatException = e;
          }
        }
        if (formatException != null) {
          throw formatException;
        }
      } finally {
        in.close();
      }
    }
    return drawing;
  }
コード例 #2
0
ファイル: Installer.java プロジェクト: suever/CTP
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
コード例 #3
0
ファイル: Resource.java プロジェクト: bozhink/Code-Chunks
 /**
  * Gets the absolute path.
  *
  * @return the absolute path
  */
 public String getAbsolutePath() {
   if (getFile() != null) {
     try {
       return XML.forwardSlash(getFile().getCanonicalPath());
     } catch (IOException ex) {
       ex.printStackTrace();
     }
     return getFile().getAbsolutePath();
   }
   if (getURL() != null) {
     URL url = getURL();
     String path = url.getPath();
     // remove file protocol, if any
     if (path.startsWith("file:")) { // $NON-NLS-1$
       path = path.substring(5);
     }
     // remove leading slash if drive is specified
     if (path.startsWith("/") && path.indexOf(":") > -1) { // $NON-NLS-1$ //$NON-NLS-2$
       path = path.substring(1);
     }
     // replace "%20" with space
     int i = path.indexOf("%20"); // $NON-NLS-1$
     while (i > -1) {
       String s = path.substring(0, i);
       path = s + " " + path.substring(i + 3); // $NON-NLS-1$
       i = path.indexOf("%20"); // $NON-NLS-1$
     }
     return path;
   }
   return null;
 }
コード例 #4
0
ファイル: JopSpider.java プロジェクト: jordibrus/proview
  static void openURL(
      JopSession session, String name, boolean newFrame, String frameName, String bookmark) {
    System.out.println("openURL " + name);
    Object root = session.getRoot();

    // Replace any URL symbol
    name = replaceUrlSymbol(session, name);
    try {
      String url_str = null;
      if (name.substring(0, 5).equals("http:")) {
        url_str = name;
        if (url_str.lastIndexOf(".html") == -1
            && url_str.lastIndexOf(".shtml") == -1
            && url_str.lastIndexOf(".htm") == -1
            && url_str.lastIndexOf(".pdf") == -1) url_str = url_str + ".html";
      } else if (name.startsWith("$pwr_doc/")) {
        URL current = ((JApplet) root).getDocumentBase();
        String current_str = current.toString();
        int idx1 = current_str.indexOf('/');
        if (idx1 != -1 && current_str.length() > idx1 + 1) {
          idx1 = current_str.indexOf('/', idx1 + 1);
          if (idx1 != -1 && current_str.length() > idx1 + 1) {
            idx1 = current_str.indexOf('/', idx1 + 1);
            if (idx1 != -1 && current_str.length() > idx1 + 1) {
              url_str = current_str.substring(0, idx1 + 1) + "pwr_doc/" + name.substring(9);
              if (url_str.lastIndexOf(".html") == -1
                  && url_str.lastIndexOf(".shtml") == -1
                  && url_str.lastIndexOf(".htm") == -1
                  && url_str.lastIndexOf(".pdf") == -1) url_str = url_str + ".html";
            }
          }
        }
      } else {
        URL current = ((JApplet) root).getCodeBase();
        String current_str = current.toString();
        int idx1 = current_str.lastIndexOf('/');
        int idx2 = current_str.lastIndexOf(':');
        int idx = idx1;
        if (idx2 > idx) idx = idx2;
        String path = current_str.substring(0, idx + 1);
        if (name.lastIndexOf(".html") == -1
            && name.lastIndexOf(".shtml") == -1
            && name.lastIndexOf(".htm") == -1
            && name.lastIndexOf(".pdf") == -1) url_str = new String(path + name + ".html");
        else url_str = new String(path + name);
        if (bookmark != null) url_str += "#" + bookmark;
      }
      System.out.println("Opening URL: " + url_str);

      URL url = new URL(url_str);
      AppletContext appCtx = ((JApplet) root).getAppletContext();
      if (newFrame) appCtx.showDocument(url, "_blank");
      else if (frameName != null) appCtx.showDocument(url, frameName);
      else appCtx.showDocument(url, "_self");
    } catch (MalformedURLException e) {
      System.out.println("MalformedURL : " + name);
    }
  }
コード例 #5
0
  private void readFromStorableInput(String filename) {
    try {
      URL url = new URL(getCodeBase(), filename);
      InputStream stream = url.openStream();
      StorableInput input = new StorableInput(stream);
      fDrawing.release();

      fDrawing = (Drawing) input.readStorable();
      view().setDrawing(fDrawing);
    } catch (IOException e) {
      initDrawing();
      showStatus("Error:" + e);
    }
  }
コード例 #6
0
ファイル: AppFrame.java プロジェクト: CestLaVi3/Android-Mouse
  public AppFrame() {
    super();
    GlobalData.oFrame = this;
    this.setSize(this.width, this.height);
    this.toolkit = Toolkit.getDefaultToolkit();

    Dimension w = toolkit.getScreenSize();
    int fx = (int) w.getWidth();
    int fy = (int) w.getHeight();

    int wx = (fx - this.width) / 2;
    int wy = (fy - this.getHeight()) / 2;

    setLocation(wx, wy);

    this.tracker = new MediaTracker(this);
    String sHost = "";
    try {

      localAddr = InetAddress.getLocalHost();
      if (localAddr.isLoopbackAddress()) {
        localAddr = LinuxInetAddress.getLocalHost();
      }
      sHost = localAddr.getHostAddress();
    } catch (UnknownHostException ex) {
      sHost = "你的IP地址错误";
    }
    //
    this.textLines[0] = "服务器正在运行.";
    this.textLines[1] = "";
    this.textLines[2] = "你的IP地址: " + sHost;
    this.textLines[3] = "";
    this.textLines[4] = "请打开你的手机客户端";
    this.textLines[5] = "";
    this.textLines[6] = "输入屏幕上显示的IP地址.";
    //
    try {
      URL fileURL = this.getClass().getProtectionDomain().getCodeSource().getLocation();
      String sBase = fileURL.toString();
      if ("jar".equals(sBase.substring(sBase.length() - 3, sBase.length()))) {
        jar = new JarFile(new File(fileURL.toURI()));

      } else {
        basePath = System.getProperty("user.dir") + "\\res\\";
      }
    } catch (Exception ex) {
      this.textLines[1] = "exception: " + ex.toString();
    }
  }
コード例 #7
0
  private URL verifyUrl(String url) {

    if (!url.toLowerCase().startsWith("http://")) return null;

    URL verifiedUrl = null;
    try {
      verifiedUrl = new URL(url);
    } catch (Exception e) {
      return null;
    }

    if (verifiedUrl.getFile().length() < 2) return null;

    return verifiedUrl;
  }
コード例 #8
0
 private void readFromObjectInput(String filename) {
   try {
     URL url = new URL(getCodeBase(), filename);
     InputStream stream = url.openStream();
     ObjectInput input = new ObjectInputStream(stream);
     fDrawing.release();
     fDrawing = (Drawing) input.readObject();
     view().setDrawing(fDrawing);
   } catch (IOException e) {
     initDrawing();
     showStatus("Error: " + e);
   } catch (ClassNotFoundException e) {
     initDrawing();
     showStatus("Class not found: " + e);
   }
 }
コード例 #9
0
ファイル: Controller.java プロジェクト: andrnil/marenor
  public void openLink(String link) {
    if (WWUtil.isEmpty(link)) return;

    try {
      try {
        // See if the link is a URL, and invoke the browser if it is
        URL url = new URL(link.replace(" ", "%20"));
        Desktop.getDesktop().browse(url.toURI());
        return;
      } catch (MalformedURLException ignored) { // just means that the link is not a URL
      }

      // It's not a URL, so see if it's a file and invoke the desktop to open it if it is.
      File file = new File(link);
      if (file.exists()) {
        Desktop.getDesktop().open(new File(link));
        return;
      }

      String message = "Cannot open resource. It's not a valid file or URL.";
      Util.getLogger().log(Level.SEVERE, message);
      this.showErrorDialog(null, "No Reconocido V\u00ednculo", message);
    } catch (UnsupportedOperationException e) {
      String message =
          "Unable to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "Error Opening Resource", message);
    } catch (IOException e) {
      String message =
          "I/O error while opening resource.\n"
              + link
              + (e.getMessage() != null ? ".\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "I/O Error", message);
    } catch (Exception e) {
      String message =
          "Error attempting to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message);
      this.showMessageDialog(message, "Error Opening Resource", JOptionPane.ERROR_MESSAGE);
    }
  }
コード例 #10
0
ファイル: Main.java プロジェクト: sidwubf/java-config
 /** Remove data component data JAR from cache */
 public static void removeInstallerComponent() {
   DownloadService downloadService = Config.getDownloadService();
   if (downloadService != null) {
     String component = Config.getInstallerLocation();
     String version = Config.getInstallerVersion();
     try {
       URL codebase = Config.getBasicService().getCodeBase();
       URL url = new URL(codebase, component);
       component = url.toString();
       Config.trace("Removing: " + component + "/" + version);
       downloadService.removeResource(url, version);
     } catch (IOException ioe) {
       Config.trace("Unable to remove " + component + "/" + version);
     }
   } else {
     Config.trace("No download service found");
   }
 }
コード例 #11
0
ファイル: TestFrame.java プロジェクト: jccmelo/GSPAnalyzer
 public HtmlRendererContext open(
     URL url, String windowName, String windowFeatures, boolean replace) {
   TestFrame frame = new TestFrame("Cobra Test Tool");
   frame.setSize(600, 400);
   frame.setExtendedState(TestFrame.NORMAL);
   frame.setVisible(true);
   HtmlRendererContext ctx = frame.getHtmlRendererContext();
   ctx.setOpener(this);
   frame.navigate(url.toExternalForm());
   return ctx;
 }
コード例 #12
0
ファイル: Installer.java プロジェクト: suever/CTP
 private boolean checkServer(int port, boolean ssl) {
   try {
     URL url = new URL("http://127.0.0.1:" + port);
     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     conn.setRequestMethod("GET");
     conn.connect();
     int length = conn.getContentLength();
     StringBuffer text = new StringBuffer();
     InputStream is = conn.getInputStream();
     InputStreamReader isr = new InputStreamReader(is);
     int size = 256;
     char[] buf = new char[size];
     int len;
     while ((len = isr.read(buf, 0, size)) != -1) text.append(buf, 0, len);
     isr.close();
     if (programName.equals("ISN")) return !shutdown(port, ssl);
     return true;
   } catch (Exception ex) {
     return false;
   }
 }
コード例 #13
0
ファイル: PostTest.java プロジェクト: pkupzj/research
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
コード例 #14
0
ファイル: Main.java プロジェクト: sidwubf/java-config
  /** Download data component JAR */
  public static boolean downloadInstallerComponent() {
    DownloadService downloadService = Config.getDownloadService();
    DownloadServiceListener listener = downloadService.getDefaultProgressWindow();
    String compName = Config.getInstallerLocation();
    String compVer = Config.getInstallerVersion();
    try {
      URL codebase = Config.getBasicService().getCodeBase();
      URL url = new URL(codebase, compName);
      String urlstr = url.toString();

      if (!downloadService.isResourceCached(url, compVer)) {
        // The installFailed string is only for debugging. No localization needed
        Config.trace("Downloading: " + urlstr);
        // Do download
        downloadService.loadResource(url, compVer, listener);
      }
    } catch (IOException ioe) {
      Config.trace("Unable to download: " + compName + "/" + compVer);
      return false;
    }
    return true;
  }
コード例 #15
0
ファイル: BrowserFrame.java プロジェクト: haleyjd/Browsar
  // implemented for HyperlinkListener
  public void hyperlinkUpdate(HyperlinkEvent e) {
    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      JEditorPane ep = (JEditorPane) (e.getSource());

      // handle frame events properly
      if (e instanceof HTMLFrameHyperlinkEvent) {
        HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;
        HTMLDocument doc = (HTMLDocument) (ep.getDocument());
        doc.processHTMLFrameHyperlinkEvent(evt);
      } else // handle normal links
      {
        try {
          URL currentLoc = new URL(location);
          URL newLoc = new URL(currentLoc, e.getDescription());

          setBrowserLocation(newLoc.toString());
        } catch (MalformedURLException malUrl) {
          JOptionPane.showMessageDialog(
              this, "Malformed URL", "Browser Error", JOptionPane.ERROR_MESSAGE);
          return;
        }
      }
    }
  }
コード例 #16
0
  public void actionPerformed(ActionEvent e) {
    SpinnerNumberModel m = ((SpinnerNumberModel) daysnr.getModel());
    int days = m.getNumber().intValue();
    String location = ((JTextField) loc).getText();
    java.util.List<PointOfInterest> points = parent.textFieldPoints(location);
    if (!points.isEmpty()) {
      double latitude = points.get(0).getLatlon().latitude.getDegrees(),
          longitude = points.get(0).getLatlon().longitude.getDegrees();
      // we want only the firs two decimals
      latitude = ((double) ((long) (latitude * 100))) / 100;
      longitude = ((double) ((long) (latitude * 100))) / 100;
      String APIKey = "65ea00ff33143650113112";
      String address =
          "http://free.worldweatheronline.com/feed/weather.ashx?"
              + "key="
              + APIKey
              + "&num_of_days="
              + days
              + "&q="
              + latitude
              + ","
              + longitude
              + "&format=json&cc=no";
      try {
        URL link = new URL(address);
        URLConnection yc = link.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        Vector<WeatherElements> elem = new Vector<WeatherElements>();
        String jsonFile = in.readLine();
        int i1 = 0, i2 = 0;
        for (int i = 0; i < days; i++) {
          i1 = jsonFile.indexOf("\"date\"", i2) + 9;
          i2 = jsonFile.indexOf("\"", i1);
          String date = jsonFile.substring(i1, i2);
          i2++;

          i1 = jsonFile.indexOf("\"precipMM\"", i2) + 13;
          i2 = jsonFile.indexOf("\"", i1);
          String rain = jsonFile.substring(i1, i2);
          i2++;

          i1 = jsonFile.indexOf("\"tempMaxC\"", i2) + 13;
          i2 = jsonFile.indexOf("\"", i1);
          String tempMax = jsonFile.substring(i1, i2);
          i2++;

          i1 = jsonFile.indexOf("\"tempMinC\"", i2) + 13;
          i2 = jsonFile.indexOf("\"", i1);
          String tempMin = jsonFile.substring(i1, i2);
          i2++;

          i1 = jsonFile.indexOf("\"value\"", i2) + 10;
          i2 = jsonFile.indexOf("\"", i1);
          String weatherStatus = jsonFile.substring(i1, i2);
          i2++;

          i1 = jsonFile.indexOf("\"value\"", i2) + 10;
          i2 = jsonFile.indexOf("\"", i1);
          String imgLink = jsonFile.substring(i1, i2);
          imgLink = imgLink.replace("\\", "");
          i2++;

          i1 = jsonFile.indexOf("\"winddirDegree\"", i2) + 18;
          i2 = jsonFile.indexOf("\"", i1);
          String windDirDegree = jsonFile.substring(i1, i2);
          i2++;

          i1 = jsonFile.indexOf("\"winddirection\"", i2) + 18;
          i2 = jsonFile.indexOf("\"", i1);
          String windDir = jsonFile.substring(i1, i2);
          i2++;

          i1 = jsonFile.indexOf("\"windspeedKmph\"", i2) + 18;
          i2 = jsonFile.indexOf("\"", i1);
          String windSpeed = jsonFile.substring(i1, i2);
          i2++;

          WeatherElements o =
              new WeatherElements(
                  date,
                  rain,
                  tempMax,
                  tempMin,
                  weatherStatus,
                  imgLink,
                  windDirDegree,
                  windDir,
                  windSpeed);
          elem.add(o);
        }

        weatherIcon.setVisible(true);
        dateout.setText(elem.elementAt(0).date);
        weatherIcon.setText("<html><img src=\"" + elem.elementAt(0).imgLink + "\" /></html>");
        weatherstatus.setText("<html><h1>" + elem.elementAt(0).weatherStatus + "</h1></html>");
        temperature.setText(
            "<html>Temperatures:<br />Temp min: "
                + elem.elementAt(0).tempMin
                + "°C<br />Temp max: "
                + elem.elementAt(0).tempMax
                + "°C</html>");
        rain.setText("Rain: " + elem.elementAt(0).rain + " mm");
        wind.setText(
            "<html>Wind: <br />"
                + "<img src=\"http://www.worldweatheronline.com"
                + "/App_Themes/Default/images/wind/"
                + elem.elementAt(0).windDir
                + ".png\" /><br />"
                + "Wind speed: "
                + elem.elementAt(0).windSpeed
                + "Km/h<br />"
                + elem.elementAt(0).windDir
                + "("
                + elem.elementAt(0).windDirDegree
                + "°)</html>");

        buttons.removeAll();
        pageNum.removeAll();
        buttons.updateUI();
        pageNum.updateUI();

        JButton previous = new JButton("Previous");
        previous.setEnabled(false);
        previous.setName("prev");

        JButton next = new JButton("Next");
        next.setName("next");

        if (days == 1) {
          next.setEnabled(false);
        }

        JTextField current = new JTextField("1", 3);
        current.setEditable(false);
        JTextField maxNum = new JTextField("" + elem.size(), 3);
        maxNum.setEditable(false);
        pageNum.add(current);
        pageNum.add(maxNum);

        previous.addActionListener(
            new WeatherButtonsActionListener(
                previous,
                next,
                weatherIcon,
                dateout,
                weatherstatus,
                temperature,
                rain,
                wind,
                elem,
                current));
        next.addActionListener(
            new WeatherButtonsActionListener(
                previous,
                next,
                weatherIcon,
                dateout,
                weatherstatus,
                temperature,
                rain,
                wind,
                elem,
                current));
        buttons.add(next);
        buttons.add(previous);
        JButton genHTML = new JButton("Generate HTML");
        genHTML.addActionListener(new genHTMLWeatherReport(parent, elem));
        buttons.add(genHTML);
      } catch (Exception ex) {
        parent.standardDialogBox("Fetching data error", "Somethnig goes wrong with the connection");
      }
    } else {
      parent.standardDialogBox("Incorrect input", "Input is incorrect!");
    }
  }
コード例 #17
0
ファイル: Main.java プロジェクト: sidwubf/java-config
  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];
  }
コード例 #18
0
ファイル: JopSpider.java プロジェクト: jordibrus/proview
  public static Image getImage(JopSession session, String image) {
    String fullName;
    if (session.getRoot() instanceof JopApplet) {
      String name;
      try {
        URL current = ((JApplet) session.getRoot()).getCodeBase();
        String current_str = current.toString();
        int idx1 = current_str.lastIndexOf('/');
        int idx2 = current_str.lastIndexOf(':');
        int idx = idx1;
        if (idx2 > idx) idx = idx2;
        String path = current_str.substring(0, idx + 1);
        String url_str;

        //        String url_str = new String( path + name);
        if (image.substring(0, 5).compareTo("jpwr/") == 0) {
          idx = image.lastIndexOf('/');
          name = image.substring(5, idx);

          url_str = new String("jar:" + path + "pwr_" + name + ".jar!/" + image);
        } else {
          idx = image.lastIndexOf('/');
          if (idx == -1) name = new String(image);
          else name = image.substring(idx + 1);

          url_str = new String("jar:" + path + "pwrp_" + systemName + "_web.jar!/" + name);
        }
        System.out.println("Opening URL: " + url_str);
        URL url = new URL(url_str);
        return Toolkit.getDefaultToolkit().getImage(url);
      } catch (MalformedURLException e) {
      }
      return null;
    } else {
      // Add default directory /pwrp/img
      System.out.println("Image: " + image);

      //      int idx = image.lastIndexOf('/');
      //      if ( idx == -1)
      //  fullName = new String("/pwrp/img/" + image);
      // else
      fullName = new String(image);
      //      return Toolkit.getDefaultToolkit().getImage( fullName);

      try {
        String name;
        String url_str;
        int idx;
        String path = new String("file://");
        if (image.substring(0, 5).compareTo("jpwr/") == 0) {
          idx = image.lastIndexOf('/');
          name = image.substring(5, idx);

          url_str = new String("$pwr_lib/pwr_" + name + ".jar");
          url_str = Gdh.translateFilename(url_str);
          url_str = new String("jar:" + path + url_str + "!/" + image);
        } else {
          idx = image.lastIndexOf('/');
          if (idx == -1) name = new String(image);
          else name = image.substring(idx + 1);

          url_str = new String("$pwrp_lib/pwrp_" + systemName + ".jar");
          System.out.println("java: " + url_str);
          url_str = Gdh.translateFilename(url_str);
          url_str = new String("jar:" + path + url_str + "!/" + name);
        }
        System.out.println("Opening URL: " + url_str);
        URL url = new URL(url_str);
        return Toolkit.getDefaultToolkit().getImage(url);
      } catch (MalformedURLException e) {
      }
    }
    return null;
  }
コード例 #19
0
  private void buttonOKActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_buttonOKActionPerformed

    // verification si les champs sont vides
    if (textIndDestinataire.getText().equals("")
        || textIndObjet.getText().equals("")
        || textMessage.getText().equals("")) {
      JOptionPane.showMessageDialog(
          this,
          Bundle.getText("JDialogAlerteChampsVides"),
          Bundle.getText("JDialogAlerteAttentionMessage"),
          JOptionPane.WARNING_MESSAGE);
      return;
    }

    try {
      // Envoie du login et du password a la servlet "CreerSuperviseurServlet" pour l'ajouter a la
      // BD
      URL url =
          new URL(
              "http://"
                  + P2S.P2S.Preferences.getProperty("host")
                  + ":"
                  + P2S.P2S.Preferences.getProperty("port")
                  + "/p2sserver/CreerUnMessageServlet?login="******"&sujet="
                  + this.textIndObjet.getText()
                  + "&message="
                  + this.textMessage.getText());

      // Buffer qui va recuperer la reponse de la servlet
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
      // On recupere la reponse
      String inputLine = in.readLine();
      if (inputLine.equalsIgnoreCase("ok")) { // on a enregistré dans la bd
        this.dispose();
        in.close();
        return;
      } else if (inputLine.equalsIgnoreCase("nok")) {
        JOptionPane.showMessageDialog(
            this,
            Bundle.getText("JDialogAlerteNoSup"),
            Bundle.getText("JDialogAlerteAttentionMessage"),
            JOptionPane.WARNING_MESSAGE);
      }
      in.close();
    } catch (MalformedURLException e1) {
      javax.swing.JOptionPane.showMessageDialog(
          null,
          Bundle.getText("ExceptionErrorURL"),
          Bundle.getText("ExceptionErrorTitle"),
          javax.swing.JOptionPane.ERROR_MESSAGE);
    } catch (IOException e2) {
      javax.swing.JOptionPane.showMessageDialog(
          null,
          Bundle.getText("ExceptionErrorIO"),
          Bundle.getText("ExceptionErrorTitle"),
          javax.swing.JOptionPane.ERROR_MESSAGE);
    } catch (IllegalArgumentException e3) {
      javax.swing.JOptionPane.showMessageDialog(
          null,
          Bundle.getText("ExceptionErrorARGS"),
          Bundle.getText("ExceptionErrorTitle"),
          javax.swing.JOptionPane.ERROR_MESSAGE);
    }
  } // GEN-LAST:event_buttonOKActionPerformed
コード例 #20
0
  public static int commitGUIConfigurationTransaction(
      XMLTreeForConfiguration xtfcXMLTreeForConfiguration, Vector vFunctionalities) {

    TreeVisit tvConfigurationTreeVisit;
    TreeVisitToGetConfigurationFile tvgcTreeVisitToGetConfigurationFile;
    String sConfigurationFile;
    URL uXML;
    String sConfigurationLockFile;
    BufferedWriter bwBufferedWriter;
    File fFile;

    tvgcTreeVisitToGetConfigurationFile = new TreeVisitToGetConfigurationFile(vFunctionalities);
    tvConfigurationTreeVisit = new TreeVisit(tvgcTreeVisitToGetConfigurationFile);

    if (tvConfigurationTreeVisit.inOrderVisit(xtfcXMLTreeForConfiguration.getXMLTopTreeComponent())
        != 0) {
      JOptionPane.showMessageDialog(
          null, "inOrderVisit failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    sConfigurationFile = tvgcTreeVisitToGetConfigurationFile.getConfigurationFile();

    System.out.println("commitGUIConfigurationTransaction: " + sConfigurationFile);

    uXML = xtfcXMLTreeForConfiguration.getXML();

    try {
      bwBufferedWriter =
          new BufferedWriter(new FileWriter(URLDecoder.decode(uXML.getFile(), "UTF-8")));
      bwBufferedWriter.write(sConfigurationFile, 0, sConfigurationFile.length());
      bwBufferedWriter.close();

      System.out.println(
          "commitGUIConfigurationTransaction: file written ("
              + URLDecoder.decode(uXML.getFile(), "UTF-8")
              + ")");
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null,
          "Operation on BufferedWriter failed (3)",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 2;
    }

    sConfigurationLockFile = new String(uXML.getFile() + ".lck");

    try {
      fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8"));

      System.out.println("File. delete: " + URLDecoder.decode(sConfigurationLockFile, "UTF-8"));
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    if (fFile.delete() == false) {
      JOptionPane.showMessageDialog(
          null,
          "fFile.delete on " + sConfigurationLockFile + " failed",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 3;
    }

    return 0;
  }
コード例 #21
0
ファイル: FetchExternalLibrary.java プロジェクト: xinl/ToMaTo
  public void fetchExternalJSLibrary(String targetURLString) {

    final URL targetURL;
    String targetFile = "";
    String s = null;

    InputStream is = null;
    BufferedReader dis = null;

    try {
      // ------------------------------------------------------------//
      // Step 2:  Create the URL.                                   //
      // ------------------------------------------------------------//
      // Note: Put your real URL here, or better yet, read it as a  //
      // command-line arg, or read it from a file.                  //
      // ------------------------------------------------------------//

      targetURL = new URL(targetURLString);

      // ----------------------------------------------//
      // Step 3:  Open an input stream from the url.  //
      // ----------------------------------------------//

      is = targetURL.openStream();

      // -------------------------------------------------------------//
      // Step 4:                                                     //
      // -------------------------------------------------------------//
      // Convert the InputStream to BufferedReader                   //
      // -------------------------------------------------------------//

      dis = new BufferedReader(new InputStreamReader(is));

      // ------------------------------------------------------------//
      // Step 5:                                                    //
      // ------------------------------------------------------------//
      // Now just read each record of the input stream, and print   //
      // it out.  Note that it's assumed that this problem is run   //
      // from a command-line, not from an application or applet.    //
      // ------------------------------------------------------------//

      while ((s = dis.readLine()) != null) {
        targetFile = targetFile + "\n" + s;
      }

      alert(targetFile);
      System.out.println(targetFile);

    } catch (MalformedURLException mue) {

      alert("Ouch - a MalformedURLException happened.");
      System.out.println("Ouch - a MalformedURLException happened.");
      mue.printStackTrace();
      System.exit(1);

    } catch (IOException ioe) {

      alert("Ouch - an IOException happened.");
      System.out.println("Ouch - an IOException happened.");
      ioe.printStackTrace();
      System.exit(1);

    } catch (Exception e) {
      alert("Ouch - Something wrong happened.");
      alert(e.toString());
      alert(e.getMessage());
    } finally {

      // ---------------------------------//
      // Step 6:  Close the InputStream  //
      // ---------------------------------//

      try {
        is.close();
        dis.close();
      } catch (IOException ioe) {
        // just going to ignore this one
      }
    } // end of 'finally' clause
  }
コード例 #22
0
  /**
   * Creates this account on the server.
   *
   * @return the created account
   */
  public NewAccount createAccount() {
    // Check if the two passwords match.
    String pass1 = new String(passField.getPassword());
    String pass2 = new String(retypePassField.getPassword());
    if (!pass1.equals(pass2)) {
      showErrorMessage(
          IppiAccRegWizzActivator.getResources()
              .getI18NString("plugin.sipaccregwizz.NOT_SAME_PASSWORD"));

      return null;
    }

    NewAccount newAccount = null;
    try {
      StringBuilder registerLinkBuilder = new StringBuilder(registerLink);
      registerLinkBuilder
          .append(URLEncoder.encode("email", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode(emailField.getText(), "UTF-8"))
          .append("&")
          .append(URLEncoder.encode("password", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode(new String(passField.getPassword()), "UTF-8"))
          .append("&")
          .append(URLEncoder.encode("display_name", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode(displayNameField.getText(), "UTF-8"))
          .append("&")
          .append(URLEncoder.encode("username", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode(usernameField.getText(), "UTF-8"))
          .append("&")
          .append(URLEncoder.encode("user_agent", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode("sip-communicator.org", "UTF-8"));

      URL url = new URL(registerLinkBuilder.toString());
      URLConnection conn = url.openConnection();

      // If this is not an http connection we have nothing to do here.
      if (!(conn instanceof HttpURLConnection)) {
        return null;
      }

      HttpURLConnection httpConn = (HttpURLConnection) conn;

      int responseCode = httpConn.getResponseCode();

      if (responseCode == HttpURLConnection.HTTP_OK) {
        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String str;

        StringBuffer stringBuffer = new StringBuffer();
        while ((str = in.readLine()) != null) {
          stringBuffer.append(str);
        }

        if (logger.isInfoEnabled())
          logger.info("JSON response to create account request: " + stringBuffer.toString());

        newAccount = parseHttpResponse(stringBuffer.toString());
      }
    } catch (MalformedURLException e1) {
      if (logger.isInfoEnabled())
        logger.info("Failed to create URL with string: " + registerLink, e1);
    } catch (IOException e1) {
      if (logger.isInfoEnabled()) logger.info("Failed to open connection.", e1);
    }
    return newAccount;
  }