// test
  public static void main(String[] args) {
    String vers = "3.0";
    String wnhome = "C:/Program Files/WordNet/" + vers + "/dict";
    String icfile =
        "C:/Program Files/WordNet/" + vers + "/WordNet-InfoContent-" + vers + "/ic-semcor.dat";
    URL url = null;
    try {
      url = new URL("file", null, wnhome);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    if (url == null) {
      return;
    }
    IDictionary dict = new Dictionary(url);
    try {
      dict.open();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    ICFinder icfinder = new ICFinder(icfile);
    DepthFinder depthfinder = new DepthFinder(dict, icfile);
    double depth1 = depthfinder.getSynsetDepth("opposition", 2, "n");
    System.out.println(depth1);
  }
Example #2
0
  public static void main(String args[]) throws IOException {

    try {
      // Create a URL object

      String temp =
          "http://ccnabaaps.hostingsiteforfree.com/folder/phppart.php?q=http://www.espncricinfo.com/india/content/player/253802.html";
      URL url = new URL(temp);

      // Read all of the text returned by the HTTP server
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

      String htmlText;

      while ((htmlText = in.readLine()) != null) {
        // Keep in mind that readLine() strips the newline characters
        System.out.println(htmlText);
      }
      in.close();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #3
0
 public static String visitWeb(String urlStr) {
   URL url = null;
   HttpURLConnection httpConn = null;
   InputStream in = null;
   try {
     url = new URL(urlStr);
     httpConn = (HttpURLConnection) url.openConnection();
     HttpURLConnection.setFollowRedirects(true);
     httpConn.setRequestMethod("GET");
     httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)");
     in = httpConn.getInputStream();
     return convertStreamToString(in);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       in.close();
       httpConn.disconnect();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
   return null;
 }
Example #4
0
 static {
   dict = null;
   String wnhome = System.getenv("WNHOME");
   String path =
       (new StringBuilder(String.valueOf(wnhome)))
           .append(File.separator)
           .append("dict")
           .toString();
   System.out.println(
       (new StringBuilder("Path to dictionary:")).append(getWNLocation()).toString());
   URL url = null;
   try {
     File f =
         new File(
             (new StringBuilder(String.valueOf(getWNLocation())))
                 .append(File.separator)
                 .append("dict")
                 .toString());
     URI uri = f.toURI();
     url = uri.toURL();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   dict = new Dictionary(url);
   dict.open();
 }
 public HttpReport(QAT parent, String urlString, String baseDir, StatusWindow status) {
   // check if the basedir exists
   if (!(new File(baseDir).exists())) {
     String message = "Error - cannot generate report, directory does not exist:" + baseDir;
     if (status == null) {
       System.out.println(message);
     } else {
       status.setMessage(message);
     }
     return;
   }
   this.parent = parent;
   this.status = status;
   processedLinks = new ArrayList();
   try {
     processURL(new URL(urlString), baseDir, status);
     writeDeadLinks(baseDir);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     processedLinks.clear();
   }
 }
Example #6
0
  // прочитать весь json в строку
  private static String readAll() throws IOException {
    StringBuilder data = new StringBuilder();
    try {
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("GET");

      con.setDoInput(true);
      String s;
      try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
        while ((s = in.readLine()) != null) {
          data.append(s);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc.");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot read from  server");
    }
    return data.toString();
  }
  /**
   * Create a MonitoredHostProvider instance using the given HostIdentifier.
   *
   * @param hostId the host identifier for this MonitoredHost
   * @throws MonitorException Thrown on any error encountered while communicating with the remote
   *     host.
   */
  public MonitoredHostProvider(HostIdentifier hostId) throws MonitorException {
    this.hostId = hostId;
    this.listeners = new ArrayList();
    this.interval = DEFAULT_POLLING_INTERVAL;
    this.activeVms = new HashSet();

    String rmiName;
    String sn = serverName;
    String path = hostId.getPath();

    if ((path != null) && (path.length() > 0)) {
      sn = path;
    }

    if (hostId.getPort() != -1) {
      rmiName = "rmi://" + hostId.getHost() + ":" + hostId.getPort() + sn;
    } else {
      rmiName = "rmi://" + hostId.getHost() + sn;
    }

    try {
      remoteHost = (RemoteHost) Naming.lookup(rmiName);

    } catch (RemoteException e) {
      /*
       * rmi registry not available
       *
       * Access control exceptions, where the rmi server refuses a
       * connection based on policy file configuration, come through
       * here on the client side. Unfortunately, the RemoteException
       * doesn't contain enough information to determine the true cause
       * of the exception. So, we have to output a rather generic message.
       */
      String message = "RMI Registry not available at " + hostId.getHost();

      if (hostId.getPort() == -1) {
        message = message + ":" + java.rmi.registry.Registry.REGISTRY_PORT;
      } else {
        message = message + ":" + hostId.getPort();
      }

      if (e.getMessage() != null) {
        throw new MonitorException(message + "\n" + e.getMessage(), e);
      } else {
        throw new MonitorException(message, e);
      }

    } catch (NotBoundException e) {
      // no server with given name
      String message = e.getMessage();
      if (message == null) message = rmiName;
      throw new MonitorException("RMI Server " + message + " not available", e);
    } catch (MalformedURLException e) {
      // this is a programming problem
      e.printStackTrace();
      throw new IllegalArgumentException("Malformed URL: " + rmiName);
    }
    this.vmManager = new RemoteVmManager(remoteHost);
    this.timer = new Timer(true);
  }
Example #8
0
 public URL getURL() {
   try {
     return new URL(elt.getAttribute("url"));
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #9
0
  /**
   * 请求xml数据
   *
   * @param url
   * @param soapAction
   * @param xml
   * @return
   */
  public static String sendXMl(String url, String soapAction, String xml) {
    HttpURLConnection conn = null;
    InputStream in = null;
    InputStreamReader isr = null;
    OutputStream out = null;
    StringBuffer result = null;
    try {
      byte[] sendbyte = xml.getBytes("UTF-8");
      URL u = new URL(url);
      conn = (HttpURLConnection) u.openConnection();
      conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
      conn.setRequestProperty("SOAPAction", soapAction);
      conn.setRequestProperty("Content-Length", sendbyte.length + "");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(5000);

      out = conn.getOutputStream();
      out.write(sendbyte);

      if (conn.getResponseCode() == 200) {
        result = new StringBuffer();
        in = conn.getInputStream();
        isr = new InputStreamReader(in, "UTF-8");
        char[] c = new char[1024];
        int a = isr.read(c);
        while (a != -1) {
          result.append(new String(c, 0, a));
          a = isr.read(c);
        }
      }

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      try {
        if (in != null) {
          in.close();
        }
        if (isr != null) {
          isr.close();
        }
        if (out != null) {
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return result == null ? null : result + "";
  }
  public static String httsRequest(String url, String contentdata) {
    String str_return = "";
    SSLContext sc = null;
    try {
      sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {

      e.printStackTrace();
    }
    try {
      sc.init(
          null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom());
    } catch (KeyManagementException e) {

      e.printStackTrace();
    }
    URL console = null;
    try {
      console = new URL(url);
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    HttpsURLConnection conn;
    try {
      conn = (HttpsURLConnection) console.openConnection();
      conn.setRequestMethod("POST");
      conn.setSSLSocketFactory(sc.getSocketFactory());
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      conn.setRequestProperty("Accept", "application/json");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json"
      String inpputs = contentdata;
      OutputStream os = conn.getOutputStream();
      os.write(inpputs.getBytes());
      os.close();
      conn.connect();
      InputStream is = conn.getInputStream();
      // // DataInputStream indata = new DataInputStream(is);
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String ret = "";
      while (ret != null) {
        ret = reader.readLine();
        if (ret != null && !ret.trim().equals("")) {
          str_return = str_return + ret;
        }
      }
      is.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return str_return;
  }
Example #11
0
  private void buildUrlSets(String url) {

    try {
      outputMessage("\nFetching " + url, TEST_SUMMARY_MESSAGE);
      URL srcUrl = new URL(url);
      //       URLConnection conn = srcUrl.openConnection();
      //       String type = conn.getContentType();
      //       type = conn.getHeaderField("content-type");
      //       InputStream istr = conn.getInputStream();

      LockssUrlConnection conn = UrlUtil.openConnection(url, connectionPool);
      if (proxyHost != null) {
        conn.setProxy(proxyHost, proxyPort);
      }
      if (userAgent != null) {
        conn.setRequestProperty("user-agent", userAgent);
      }
      try {
        conn.execute();
        int resp = conn.getResponseCode();
        if (resp != 200) {
          outputMessage("Resp: " + resp + ": " + conn.getResponseMessage(), TEST_SUMMARY_MESSAGE);
          return;
        }
        depth_fetched[m_curDepth - 1]++;
        String cookies = conn.getResponseHeaderValue("Set-Cookie");
        if (cookies != null) {
          outputMessage("Cookies: " + cookies, PLAIN_MESSAGE);
        }
        String type = conn.getResponseContentType();
        if (type == null || !type.toLowerCase().startsWith("text/html")) {
          outputMessage("Type: " + type + ", not parsing", URL_SUMMARY_MESSAGE);
          return;
        }
        outputMessage("Type: " + type + ", extracting Urls", URL_SUMMARY_MESSAGE);
        InputStream istr = conn.getResponseInputStream();
        InputStreamReader reader = new InputStreamReader(istr);
        //       MyMockCachedUrl mcu = new MyMockCachedUrl(srcUrl.toString(), reader);
        GoslingHtmlLinkExtractor extractor = new GoslingHtmlLinkExtractor();
        extractor.extractUrls(null, istr, null, srcUrl.toString(), new MyLinkExtractorCallback());
        istr.close();
        depth_parsed[m_curDepth - 1]++;
      } finally {
        conn.release();
      }
    } catch (MalformedURLException murle) {
      murle.printStackTrace();
      outputErrResults(url, "Malformed URL:" + murle.getMessage());
    } catch (IOException ex) {
      ex.printStackTrace();
      outputErrResults(url, "IOException: " + ex.getMessage());
    }
  }
Example #12
0
  public ErrorInfo listPolicy(String polname, String token) throws IOException, RestException {

    String realm = "/";
    String data = null;
    ErrorInfo ei = null;
    InputStreamReader iss = null;
    BufferedReader br = null;
    HttpURLConnection urlc = null;
    InputStream inputStream = null;

    try {
      data =
          "policynames="
              + URLEncoder.encode(polname, "UTF-8")
              + "&realm="
              + URLEncoder.encode(realm, "UTF-8")
              + "&submit="
              + URLEncoder.encode("Submit", "UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("OpenssoHelper: " + e.getMessage());
      e.printStackTrace();
    }

    if (data != null) {
      try {
        r.Connect(new URL(url + ssoadm_list));
      } catch (MalformedURLException e) {
        System.out.println("OpenssoHelper: " + e.getMessage());
        e.printStackTrace();
      }

      urlc = (HttpURLConnection) r.c;
      urlc.addRequestProperty("Cookie", "iPlanetDirectoryPro=\"" + token + "\"");
      r.Send(urlc, data);

      String answer = null;
      int status = 0;
      inputStream = urlc.getInputStream();
      iss = new InputStreamReader(inputStream);
      br = new BufferedReader(iss);
      answer = BrToString(br);
      status = urlc.getResponseCode();
      if (answer != null) {
        ei = new ErrorInfo(answer, status);
      }
      br.close();
      iss.close();
      inputStream.close();
      urlc.disconnect();
    }

    return ei;
  }
Example #13
0
 /** Loop a sound file (in .wav, .mid, or .au format) in a background thread. */
 public static void loop(String filename) {
   URL url = null;
   try {
     File file = new File(filename);
     if (file.canRead()) url = file.toURI().toURL();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   // URL url = StdAudio.class.getResource(filename);
   if (url == null) throw new RuntimeException("audio " + filename + " not found");
   AudioClip clip = Applet.newAudioClip(url);
   clip.loop();
 }
  @Nullable
  static ClassLoader createPluginClassLoader(
      @NotNull File[] classPath,
      @NotNull ClassLoader[] parentLoaders,
      @NotNull IdeaPluginDescriptor pluginDescriptor) {

    if (pluginDescriptor.getUseIdeaClassLoader()) {
      try {
        final ClassLoader loader = PluginManagerCore.class.getClassLoader();
        final Method addUrlMethod = getAddUrlMethod(loader);

        for (File aClassPath : classPath) {
          final File file = aClassPath.getCanonicalFile();
          addUrlMethod.invoke(loader, file.toURI().toURL());
        }

        return loader;
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }

    PluginId pluginId = pluginDescriptor.getPluginId();
    File pluginRoot = pluginDescriptor.getPath();

    // if (classPath.length == 0) return null;
    if (isUnitTestMode()) return null;
    try {
      final List<URL> urls = new ArrayList<URL>(classPath.length);
      for (File aClassPath : classPath) {
        final File file =
            aClassPath
                .getCanonicalFile(); // it is critical not to have "." and ".." in classpath
                                     // elements
        urls.add(file.toURI().toURL());
      }
      return new PluginClassLoader(
          urls, parentLoaders, pluginId, pluginDescriptor.getVersion(), pluginRoot);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Example #15
0
  public ErrorInfo doLogin() throws IOException, RestException {

    String data = null;
    ErrorInfo ei = null;
    InputStreamReader iss = null;
    BufferedReader br = null;
    HttpURLConnection urlc = null;
    InputStream inputStream = null;

    try {
      data =
          "username="******"UTF-8")
              + "&password="******"UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("OpenssoHelper: " + e.getMessage());
      e.printStackTrace();
    }

    if (data != null) {
      try {
        r.Connect(new URL(url + authenticate));
      } catch (MalformedURLException e) {
        System.out.println("OpenssoHelper: " + e.getMessage());
        e.printStackTrace();
      }

      urlc = (HttpURLConnection) r.c;
      r.Send(urlc, data);

      String answer = null;
      int status = 0;

      inputStream = urlc.getInputStream();
      iss = new InputStreamReader(inputStream);
      br = new BufferedReader(iss);
      answer = BrToString(br);
      status = urlc.getResponseCode();
      if (answer != null) {
        ei = new ErrorInfo(answer, status);
      }
      br.close();
      iss.close();
      inputStream.close();
      urlc.disconnect();
    }

    return ei;
  }
  /**
   * Запрос с указанием параметров.
   *
   * @see MoneyDownloader#login
   * @see MoneyDownloader#password
   * @see MoneyDownloader#dateStart
   * @see MoneyDownloader#dateEnd
   */
  public final void run() {
    File file = new File(directory + "/Results.tsv");
    //        File test = new File(directory + "/tmp/result.tsv");

    try {
      if (!file.exists()) {
        file.createNewFile();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    String request = "https://rt.miran.ru?user="******"&pass="******"http://rt.miran.ru/rt/Search/Results.tsv?user="******"&pass="******"&Format=%27__Created__%2FTITLE%3A%D0%94%D0%B0%D1%82%D0%B0%27%2C%0A%27%20%20%20%3Cb%3E%3Ca%20href%3D%22%2Frt%2FTicket%2FDisplay.html%3Fid%3D__id__%22%3E__id__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3A%23%27%2C%0A%27__Subject__%2FTITLE%3A%D0%A2%D0%B5%D0%BC%D0%B0%27%2C%0A%27__QueueName__%2FTITLE%3A%D0%9E%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%27%2C%0A%27__CustomField.%7Binteraction%20type%7D__%2FTITLE%3A%D0%A2%D0%B8%D0%BF%27%2C%0A%27__CustomField.%7Bbussines%7D__%2FTITLE%3A%D0%91%D0%B8%D0%B7%D0%BD%D0%B5%D1%81%27%2C%0A%27__CustomField.%7Bdirection%7D__%2FTITLE%3A%D0%9D%D0%B0%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%27%2C%0A%27__CustomField.%7Bservice%7D__%2FTITLE%3A%D0%A3%D1%81%D0%BB%D1%83%D0%B3%D0%B0%27%2C%0A%27__CustomField.%7BSD%20Type%7D__%2FTITLE%3A%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F%27%2C%0A%27__CustomField.%7BSD%20Detail%7D__%2FTITLE%3A%D0%91%D0%BE%D0%BD%D1%83%D1%81%27%2C%0A%27__CustomField.%7BQA%7D__%2FTITLE%3A%D0%92%D1%8B%D0%BF%D0%BE%D0%BB%D0%BD%D0%B8%D0%BB%27&Order=DESC%7CASC%7CASC%7CASC&OrderBy=Created%7C%7C%7C&Page=1&Query=Created%20%3E%20%27"
            + dateStart
            + "%27%20AND%20Created%20%3C%20%27"
            + dateEnd
            + "%27%20AND%20Status%20%3D%20%27closed%27%20AND%20Queue%20!%3D%20%27manager%27%20AND%20Queue%20!%3D%20%27sales%27%20AND%20%27CF.%7BQA%7D%27%20%3D%20%27__CurrentUser__%27&RowsPerPage=0&SavedChartSearchId=new&SavedSearchId=";

    System.out.println(tickets);

    ListCookieHandler cookieHandler = new ListCookieHandler();
    CookieHandler.setDefault(cookieHandler);
    try {
      URL url = new URL(request);

      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.getResponseCode();

      GetMethod method = new GetMethod(tickets);
      method.addRequestHeader("Cookie", cookieHandler.getCookiez());
      method.addRequestHeader("Referer", "http://rt.miran.ru/");
      HttpClient httpClient = new HttpClient();

      httpClient.executeMethod(method);

      InputStream in = method.getResponseBodyAsStream();
      System.out.println(in.available());

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #17
0
 /**
  * Gets the url associated with this resource.
  *
  * @return the URL
  */
 public URL getURL() {
   if (url == null && file != null) {
     String path = getAbsolutePath();
     try {
       if (path.startsWith("/")) { // $NON-NLS-1$
         url = new URL("file:" + path); // $NON-NLS-1$
       } else {
         url = new URL("file:/" + path); // $NON-NLS-1$
       }
     } catch (MalformedURLException ex) {
       ex.printStackTrace();
     }
   }
   return url;
 }
Example #18
0
  /**
   * opens existing file
   *
   * @param a_file
   */
  public GlyphFile(File a_file) {
    super();

    m_fileName = a_file;

    URL url = null;

    try {
      url = a_file.toURI().toURL();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

    init(url);
  }
Example #19
0
 private InputStream openStream(String urlpath) {
   InputStream stream = null;
   try {
     URL url = new URL(urlpath);
     stream = url.openStream();
     return stream;
   } catch (MalformedURLException e) {
     System.out.println("Something's wrong with the URL:  " + urlpath);
     e.printStackTrace();
   } catch (IOException e) {
     System.out.println("there's a problem downloading from:  " + urlpath);
     e.printStackTrace();
   }
   return stream;
 }
Example #20
0
  // добавить продукт в базу json server
  public static void add(ProductREST product) throws NotValidProductException, IOException {
    try {
      check(product); // рповеряем продукт
      // connection к серверу
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("POST"); // метод post для добавления

      // генерируем запрос
      StringBuilder urlParameters = new StringBuilder();
      urlParameters
          .append("name=")
          .append(URLEncoder.encode(product.getName(), "UTF8"))
          .append("&");
      urlParameters.append("price=").append(product.getPrice()).append("&");
      urlParameters.append("weight=").append(product.getWeight()).append("&");
      urlParameters
          .append("manufacturer=")
          .append(product.getManufacturer().getCountry())
          .append("&");
      urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8"));

      con.setDoOutput(true); // разрешаем отправку данных
      // отправляем
      try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
        out.writeBytes(urlParameters.toString());
      }
      // код ответа
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL);
      System.out.println("Response Code : " + responseCode);

    } catch (NotValidProductException e) {
      e.printStackTrace();
      throw e;
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new UnsupportedEncodingException("cannot recognize encoding");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc.");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot write information to server");
    }
  }
Example #21
0
  protected static URL createURL(Properties headers) throws IOException {
    try {
      File file = new File(headers.getProperty("PATH_TRANSLATED"));

      while (file != null && !file.exists()) {
        file = file.getParentFile();
      }

      if (file.isDirectory()) {
        throw new IOException(
            "Unable to find a file in path " + headers.getProperty("PATH_TRANSLATED"));
      }

      return new URL("file", "", file.getAbsolutePath());
    } catch (MalformedURLException ex) {
      ex.printStackTrace();
      return null;
    }
  }
Example #22
0
  /**
   * Closes the applet. This method can be implemented by invoking <code>
   * getAppletContext().showDocument(...)</code>.
   */
  protected void close() {
    AppletContext appletContext;
    try {
      appletContext = getAppletContext();
    } catch (Throwable e) {
      appletContext = null;
    }

    if (appletContext == null) {
      System.exit(0);
    } else {
      getContentPane().removeAll();
      ((JComponent) getContentPane()).revalidate();
      try {
        appletContext.showDocument(new URL(getDocumentBase(), getParameter("PageURL")));
      } catch (MalformedURLException ex) {
        ex.printStackTrace();
      }
    }
  }
 /**
  * Discover WS device on the local network with specified filter
  *
  * @param regexpProtocol url protocol matching regexp like "^http$", might be empty ""
  * @param regexpPath url path matching regexp like "onvif", might be empty ""
  * @return list of unique device urls filtered
  */
 public static Collection<URL> discoverWsDevicesAsUrls(String regexpProtocol, String regexpPath) {
   final Collection<URL> urls =
       new TreeSet<>(
           new Comparator<URL>() {
             public int compare(URL o1, URL o2) {
               return o1.toString().compareTo(o2.toString());
             }
           });
   for (String key : discoverWsDevices()) {
     try {
       final URL url = new URL(key);
       boolean ok = true;
       if (regexpProtocol.length() > 0 && !url.getProtocol().matches(regexpProtocol)) ok = false;
       if (regexpPath.length() > 0 && !url.getPath().matches(regexpPath)) ok = false;
       if (ok) urls.add(url);
     } catch (MalformedURLException e) {
       e.printStackTrace();
     }
   }
   return urls;
 }
  /** @param args */
  public static void main(String[] args) {
    String url = "rtp://192.168.1.1:22224/audio/16";

    MediaLocator mrl = new MediaLocator(url);

    // Create a player for this rtp session
    Player player = null;
    try {
      player = Manager.createPlayer(mrl);
    } catch (NoPlayerException e) {
      e.printStackTrace();
      System.exit(-1);
    } catch (MalformedURLException e) {
      e.printStackTrace();
      System.exit(-1);
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(-1);
    }

    if (player != null) {
      System.out.println("Player created.");
      player.realize();
      // wait for realizing
      while (player.getState() != Controller.Realized) {
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println("Starting player");
      player.start();
    } else {
      System.err.println("Player doesn't created.");
      System.exit(-1);
    }

    System.out.println("Exiting.");
  }
Example #25
0
  /**
   * @deprecated - use getDocBase and URLUtil if you need it as URL NOT USED INSIDE TOMCAT - ONLY IN
   *     OLD J2EE CONNECTORS !
   */
  public URL getDocumentBase() {
    if (documentBase == null) {
      if (docBase == null) return null;
      try {
        String absPath = docBase;

        // detect absolute path ( use the same logic in all tomcat )
        if (FileUtil.isAbsolute(docBase)) absPath = docBase;
        else absPath = contextM.getHome() + File.separator + docBase;

        try {
          absPath = new File(absPath).getCanonicalPath();
        } catch (IOException npe) {
        }

        documentBase = new URL("file", "", absPath);

      } catch (MalformedURLException ex) {
        ex.printStackTrace();
      }
    }
    return documentBase;
  }
Example #26
0
 public Value apply(Value v1) throws ContinuationException {
   switch (id) {
     case DIRECTORYQ:
       return SchemeBoolean.get(fileHandle(v1).isDirectory());
     case FILEQ:
       return SchemeBoolean.get(fileHandle(v1).isFile());
     case HIDDENQ:
       return SchemeBoolean.get(fileHandle(v1).isHidden());
     case READABLE:
       return SchemeBoolean.get(fileHandle(v1).canRead());
     case WRITEABLE:
       return SchemeBoolean.get(fileHandle(v1).canWrite());
     case DIRLIST:
       Pair p = EMPTYLIST;
       String[] contents = fileHandle(v1).list();
       if (contents == null)
         throwPrimException(liMessage(IO.IOB, "nosuchdirectory", SchemeString.asString(v1)));
       for (int i = contents.length - 1; i >= 0; i--)
         p = new Pair(new SchemeString(contents[i]), p);
       return p;
     case LENGTH:
       return Quantity.valueOf(fileHandle(v1).length());
     case LASTMODIFIED:
       return Quantity.valueOf(fileHandle(v1).lastModified());
     case GETPARENTURL:
       try {
         return new SchemeString(fileHandle(v1).getParentFile().toURI().toURL().toString());
       } catch (MalformedURLException m) {
         m.printStackTrace();
       }
       break;
     default:
       throwArgSizeException();
   }
   return VOID;
 }
Example #27
0
  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
  }
Example #28
0
  public static String httpPost(String urlAddress, String[] params) {
    URL url = null;
    HttpURLConnection conn = null;
    BufferedReader in = null;
    StringBuffer sb = new StringBuffer();

    try {
      url = new URL(urlAddress);
      conn = (HttpURLConnection) url.openConnection(); // 建立连接
      // 设置通用的请求属性
      /*
       * conn.setRequestProperty("user-agent",
       * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
       */
      conn.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
      conn.setRequestProperty("Accept", "*/*");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      conn.setUseCaches(false);
      conn.setDoInput(true);
      // conn.setConnectTimeout(5 * 1000);
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      String paramsTemp = "";
      for (String param : params) {
        if (param != null && !"".equals(param)) {
          if (params.length > 1) {
            paramsTemp += "&" + param;
          } else if (params.length == 1) {
            paramsTemp = params[0];
          }
        }
      }

      byte[] b = paramsTemp.getBytes();
      System.out.println("btye length:" + b.length);
      // conn.setRequestProperty("Content-Length",
      // String.valueOf(b.length));
      conn.getOutputStream().write(b, 0, b.length);
      conn.getOutputStream().flush();
      conn.getOutputStream().close();
      int count = conn.getResponseCode();
      if (200 == count) {
        in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 发送请求
      } else {
        System.out.println("错误类型:" + count);
        return "server no start-up";
      }

      while (true) {
        String line = in.readLine();
        if (line == null) {
          break;
        } else {
          sb.append(line);
        }
      }
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("error ioexception:" + e.getMessage());
      e.printStackTrace();
      return "server no start-up";
    } finally {
      try {
        if (in != null) {
          in.close();
        }
        if (conn != null) {
          conn.disconnect();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return sb.toString();
  }