Esempio n. 1
1
  /**
   * 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;
  }
Esempio n. 2
0
  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;
  }
Esempio n. 3
0
  /**
   * Enumerates the resouces in a give package name. This works even if the resources are loaded
   * from a jar file!
   *
   * <p>Adapted from code by mikewse on the java.sun.com message boards.
   * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984
   *
   * @param packageName The package to enumerate
   * @return A Set of Strings for each resouce in the package.
   */
  public static Set getResoucesInPackage(String packageName) throws IOException {
    String localPackageName;
    if (packageName.endsWith("/")) {
      localPackageName = packageName;
    } else {
      localPackageName = packageName + '/';
    }

    Enumeration dirEnum = ClassLoader.getSystemResources(localPackageName);

    Set names = new HashSet();

    // Loop CLASSPATH directories
    while (dirEnum.hasMoreElements()) {
      URL resUrl = (URL) dirEnum.nextElement();

      // Pointing to filesystem directory
      if (resUrl.getProtocol().equals("file")) {
        File dir = new File(resUrl.getFile());
        File[] files = dir.listFiles();
        if (files != null) {
          for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isDirectory()) continue;
            names.add(localPackageName + file.getName());
          }
        }

        // Pointing to Jar file
      } else if (resUrl.getProtocol().equals("jar")) {
        JarURLConnection jconn = (JarURLConnection) resUrl.openConnection();
        JarFile jfile = jconn.getJarFile();
        Enumeration entryEnum = jfile.entries();
        while (entryEnum.hasMoreElements()) {
          JarEntry entry = (JarEntry) entryEnum.nextElement();
          String entryName = entry.getName();
          // Exclude our own directory
          if (entryName.equals(localPackageName)) continue;
          String parentDirName = entryName.substring(0, entryName.lastIndexOf('/') + 1);
          if (!parentDirName.equals(localPackageName)) continue;
          names.add(entryName);
        }
      } else {
        // Invalid classpath entry
      }
    }

    return names;
  }
Esempio n. 4
0
 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;
   }
 }
Esempio n. 5
0
  /**
   * 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();
  }
Esempio n. 6
0
  /** Submits POST command to the server, and reads the reply. */
  public boolean post(
      String url,
      String fileName,
      String cryptToken,
      String type,
      String path,
      String content,
      String comment)
      throws IOException {

    String sep = "89692781418184";
    while (content.indexOf(sep) != -1) sep += "x";

    String message = makeMimeForm(fileName, cryptToken, type, path, content, comment, sep);

    // for test
    // URL server = new URL("http", "localhost", 80, savePath);
    URL server =
        new URL(getCodeBase().getProtocol(), getCodeBase().getHost(), getCodeBase().getPort(), url);
    URLConnection connection = server.openConnection();

    connection.setAllowUserInteraction(false);
    connection.setDoOutput(true);
    // connection.setDoInput(true);
    connection.setUseCaches(false);

    connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + sep);
    connection.setRequestProperty("Content-length", Integer.toString(message.length()));

    // System.out.println(url);
    String replyString = null;
    try {
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      out.writeBytes(message);
      out.close();
      // System.out.println("Wrote " + message.length() +
      //		   " bytes to\n" + connection);

      try {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String reply = null;
        while ((reply = in.readLine()) != null) {
          if (reply.startsWith("ERROR ")) {
            replyString = reply.substring("ERROR ".length());
          }
        }
        in.close();
      } catch (IOException ioe) {
        replyString = ioe.toString();
      }
    } catch (UnknownServiceException use) {
      replyString = use.getMessage();
      System.out.println(message);
    }
    if (replyString != null) {
      // System.out.println("---- Reply " + replyString);
      if (replyString.startsWith("URL ")) {
        URL eurl = getURL(replyString.substring("URL ".length()));
        getAppletContext().showDocument(eurl);
      } else if (replyString.startsWith("java.io.FileNotFoundException")) {
        // debug; when run from appletviewer, the http connection
        // is not available so write the file content
        if (path.endsWith(".draw") || path.endsWith(".map")) System.out.println(content);
      } else showStatus(replyString);
      return false;
    } else {
      showStatus(url + " saved");
      return true;
    }
  }
  /**
   * 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;
  }
Esempio n. 8
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];
  }