예제 #1
29
 /** Check if an URL is relative to another URL. */
 public static boolean relativeURL(URL url1, URL url2) {
   return ((url1.getProtocol() == null && url2.getProtocol() == null)
           || url1.getProtocol().equals(url2.getProtocol()))
       && ((url1.getAuthority() == null && url2.getAuthority() == null)
           || url1.getAuthority().equals(url2.getAuthority()))
       && ((url1.getPath() == null && url2.getPath() == null)
           || url2.getPath().startsWith(url1.getPath()));
 }
예제 #2
0
 private List<String> searchDependencyEngineConfigFiles(
     String prefixPackageName, Class<?> contentLoaderClass) {
   List<String> fileNames = new ArrayList<String>();
   Enumeration<?> enumFiles = findConfigFileUrls(prefixPackageName, contentLoaderClass);
   while (enumFiles != null && enumFiles.hasMoreElements()) {
     URL url = (URL) enumFiles.nextElement();
     if (url == null || url.getFile() == null || url.getFile().length() <= 1) continue;
     String fileName = getFileName(url.getPath());
     if (url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("jar")) {
       String elementInJar = getJarFileEntryName(url.getPath());
       JarFile jarFile = openJar(url);
       List<JarEntry> entries = Collections.list(jarFile.entries());
       for (JarEntry entry : entries) {
         String entryName = entry.getName();
         if (entryName.startsWith(elementInJar)) {
           if (!entry.isDirectory() && entryName.matches(dependencyEngineConfigFileRegex)) {
             fileNames.add(fileName + "!" + "/" + entry.toString());
           }
         }
       }
     } else {
       List<String> list = searchDependencyEngineConfigFiles(new File(fileName));
       if (list != null && list.size() > 0) {
         fileNames.addAll(list);
       }
     }
   }
   return fileNames;
 }
예제 #3
0
 protected static String getPath(URL url) {
   if (url.getProtocol().equals("mvn")) {
     String[] parts = url.toExternalForm().substring(4).split("/");
     String groupId;
     String artifactId;
     String version;
     String type;
     String qualifier;
     if (parts.length < 3 || parts.length > 5) {
       return url.getPath();
     }
     groupId = parts[0];
     artifactId = parts[1];
     version = parts[2];
     type = (parts.length >= 4) ? "." + parts[3] : ".jar";
     qualifier = (parts.length >= 5) ? "-" + parts[4] : "";
     return groupId.replace('.', '/')
         + "/"
         + artifactId
         + "/"
         + version
         + "/"
         + artifactId
         + "-"
         + version
         + qualifier
         + type;
   }
   return url.getPath();
 }
 static {
   try {
     logger =
         Logger.getLogger(
             "br.gov.se.seplag.anexoprocessosatendimento.AnexoProcessosAtendimento_Service");
     URL baseUrl = AnexoProcessosAtendimento_Service.class.getResource(".");
     if (baseUrl == null) {
       wsdlLocationURL =
           AnexoProcessosAtendimento_Service.class.getResource(
               RequestFixo.WSDL_LOCATION + "V1/AnexoProcessosAtendimento?wsdl");
       if (wsdlLocationURL == null) {
         baseUrl = new File(".").toURL();
         wsdlLocationURL =
             new URL(baseUrl, RequestFixo.WSDL_LOCATION + "V1/AnexoProcessosAtendimento?wsdl");
       }
     } else {
       if (!baseUrl.getPath().endsWith("/")) {
         baseUrl = new URL(baseUrl, baseUrl.getPath() + "/");
       }
       wsdlLocationURL =
           new URL(baseUrl, RequestFixo.WSDL_LOCATION + "V1/AnexoProcessosAtendimento?wsdl");
     }
   } catch (MalformedURLException e) {
     logger.log(
         Level.ALL,
         "Failed to create wsdlLocationURL using http://osb.itconsulting.com.br:8011/V1/AnexoProcessosAtendimento?wsdl",
         e);
   }
 }
예제 #5
0
  private void addPluginArtifact(Set<URI> artifactsPath) {
    // for Maven 2.x, the actual artifact isn't in the list....  need to try and find it
    URL url = getClass().getResource(getClass().getSimpleName() + ".class");

    try {
      if ("jar".equals(url.getProtocol())) {
        String s = url.getPath();
        if (s.contains("!")) {
          s = s.substring(0, s.indexOf('!'));
          url = new URL(s);
        }
      }
      URI uri = new URI(url.getProtocol(), null, url.getPath(), null, null);
      if (uri.getSchemeSpecificPart().endsWith(".class")) {
        String s = uri.toString();
        s = s.substring(0, s.length() - 6 - getClass().getName().length());
        uri = new URI(s);
      }
      File file = new File(uri);
      if (file.exists()) {
        artifactsPath.add(file.toURI());
      }
    } catch (Exception ex) {
      // ex.printStackTrace();
    }
  }
 static {
   try {
     logger =
         Logger.getLogger(
             "au.com.leighton.portal.peoplefinder.model.peopledetail.Phogetpersondetail_client_ep");
     URL baseUrl = Phogetpersondetail_client_ep.class.getResource(".");
     if (baseUrl == null) {
       wsdlLocationURL =
           Phogetpersondetail_client_ep.class.getResource(
               "http://lclxsoa11gdev.lc.local:7001/soa-infra/services/default/PhoGetPersonDetail/phogetpersondetail_client_ep?WSDL");
       if (wsdlLocationURL == null) {
         baseUrl = new File(".").toURL();
         wsdlLocationURL =
             new URL(
                 baseUrl,
                 "http://lclxsoa11gdev.lc.local:7001/soa-infra/services/default/PhoGetPersonDetail/phogetpersondetail_client_ep?WSDL");
       }
     } else {
       if (!baseUrl.getPath().endsWith("/")) {
         baseUrl = new URL(baseUrl, baseUrl.getPath() + "/");
       }
       wsdlLocationURL =
           new URL(
               baseUrl,
               "http://lclxsoa11gdev.lc.local:7001/soa-infra/services/default/PhoGetPersonDetail/phogetpersondetail_client_ep?WSDL");
     }
   } catch (MalformedURLException e) {
     logger.log(
         Level.ALL,
         "Failed to create wsdlLocationURL using http://lclxsoa11gdev.lc.local:7001/soa-infra/services/default/PhoGetPersonDetail/phogetpersondetail_client_ep?WSDL",
         e);
   }
 }
예제 #7
0
  /**
   * Checks if a domain should be filtered or not: returns true if the target domain ends with the
   * comparison domain and if supplied, target path begins with the comparison path
   *
   * @param target URL to check
   * @param strings The URLs to check against
   * @return If the target is covered by any strings
   * @throws MalformedURLException
   */
  public static boolean isDomain(String target, String[] strings) throws MalformedURLException {
    URL domain = new URL(target);
    for (String s : strings) {
      if (!s.contains("/")) {
        if (ContentType.hostContains(domain.getHost(), s)) {
          return true;
        } else {
          continue;
        }
      }

      if (!s.contains("://")) {
        s = "http://" + s;
      }

      try {
        URL comparison = new URL(s.toLowerCase());

        if (ContentType.hostContains(domain.getHost(), comparison.getHost())
            && domain.getPath().startsWith(comparison.getPath())) {
          return true;
        }
      } catch (MalformedURLException ignored) {
      }
    }
    return false;
  }
예제 #8
0
 /**
  * Find in the url the filename
  *
  * @param url
  * @return
  */
 private String findFileName(URL url) {
   String name = FilenameUtils.getName(url.getPath());
   if (isWellFormedFileName(name)) return name;
   name = FilenameUtils.getName(url.toString());
   if (isWellFormedFileName(name)) return name;
   return FilenameUtils.getName(url.getPath());
 }
 static {
   try {
     logger = Logger.getLogger("com.oracle.pts.opp.wsclient.OpportunityService_Service");
     URL baseUrl = OpportunityService_Service.class.getResource(".");
     if (baseUrl == null) {
       wsdlLocationURL =
           OpportunityService_Service.class.getResource(
               "https://fap0930-crm.oracleads.com/opptyMgmtOpportunities/OpportunityService?WSDL");
       if (wsdlLocationURL == null) {
         baseUrl = new File(".").toURL();
         wsdlLocationURL =
             new URL(
                 baseUrl,
                 "https://fap0930-crm.oracleads.com/opptyMgmtOpportunities/OpportunityService?WSDL");
       }
     } else {
       if (!baseUrl.getPath().endsWith("/")) {
         baseUrl = new URL(baseUrl, baseUrl.getPath() + "/");
       }
       wsdlLocationURL =
           new URL(
               baseUrl,
               "https://fap0930-crm.oracleads.com/opptyMgmtOpportunities/OpportunityService?WSDL");
     }
   } catch (MalformedURLException e) {
     logger.log(
         Level.ALL,
         "Failed to create wsdlLocationURL using https://fap0930-crm.oracleads.com/opptyMgmtOpportunities/OpportunityService?WSDL",
         e);
   }
 }
예제 #10
0
  /** Load the config parameters from fortress.properties file. */
  private void loadLocalConfig() {
    try {
      // Load the system config file.
      URL fUrl = Config.class.getClassLoader().getResource(PROP_FILE);
      config.setDelimiterParsingDisabled(true);
      if (fUrl == null) {
        String error = "static init: Error, null cfg file: " + PROP_FILE;
        LOG.warn(error);
      } else {
        LOG.info("static init: found from: {} path: {}", PROP_FILE, fUrl.getPath());
        config.load(fUrl);
        LOG.info("static init: loading from: {}", PROP_FILE);
      }

      URL fUserUrl = Config.class.getClassLoader().getResource(USER_PROP_FILE);
      if (fUserUrl != null) {
        LOG.info(
            "static init: found user properties from: {} path: {}",
            USER_PROP_FILE,
            fUserUrl.getPath());
        config.load(fUserUrl);
      }
    } catch (org.apache.commons.configuration.ConfigurationException ex) {
      String error =
          "static init: Error loading from cfg file: ["
              + PROP_FILE
              + "] ConfigurationException="
              + ex;
      LOG.error(error);
      throw new CfgRuntimeException(GlobalErrIds.FT_CONFIG_BOOTSTRAP_FAILED, error, ex);
    }
  }
  @NotNull
  public static String convertFromUrl(@NotNull URL url) {
    String protocol = url.getProtocol();
    String path = url.getPath();
    if (protocol.equals(JAR)) {
      if (StringUtil.startsWithConcatenationOf(path, FILE, PROTOCOL_DELIMITER)) {
        try {
          URL subURL = new URL(path);
          path = subURL.getPath();
        } catch (MalformedURLException e) {
          throw new RuntimeException(VfsBundle.message("url.parse.unhandled.exception"), e);
        }
      } else {
        throw new RuntimeException(
            new IOException(VfsBundle.message("url.parse.error", url.toExternalForm())));
      }
    }
    if (SystemInfo.isWindows || SystemInfo.isOS2) {
      while (path.length() > 0 && path.charAt(0) == '/') {
        path = path.substring(1, path.length());
      }
    }

    path = URLUtil.unescapePercentSequences(path);
    return protocol + "://" + path;
  }
예제 #12
0
  /** initialization. load all files. */
  private void init() {
    URL home = getClass().getResource("..");
    File local;
    if (home != null) {
      System.out.println("looks like you are not starting from a jar-package");
      local = new File(home.getPath() + "/" + helproot + "/" + language + "/");
      System.out.println("local: " + local.getAbsolutePath());
      initFile(local);
      try {
        local =
            new File(
                new File(home.getPath()).getParentFile().getParentFile(),
                helproot + "/" + language);
        System.out.println("local: " + local.getAbsolutePath());
        initFile(local);
      } catch (Exception e) {
        System.out.println("but not loading from the developer workbench?!");
      }

    } else {
      System.out.println("looks like you are starting from a jar-package");
      local = CommandLoader.getLocation();
      initJar(local);
    }
    List<String> l = getLanguages();
    for (String aL : l) {
      System.out.println("language found: " + aL);
    }
  }
  @Test
  public void testGetURLPrincipal() throws KettleDatabaseException, MalformedURLException {
    String testHostname = "testHostname";
    int port = 9429;
    String testDbName = "testDbName";
    impalaDatabaseMeta.getAttributes().put("principal", "testP");
    String urlString = impalaDatabaseMeta.getURL(testHostname, "" + port, testDbName);
    assertTrue(urlString.startsWith(ImpalaDatabaseMeta.URL_PREFIX));
    // Use known prefix
    urlString = "http://" + urlString.substring(ImpalaDatabaseMeta.URL_PREFIX.length());
    URL url = new URL(urlString);
    assertEquals(testHostname, url.getHost());
    assertEquals(port, url.getPort());
    assertEquals("/" + testDbName, url.getPath());

    impalaDatabaseMeta.getAttributes().remove("principal");
    impalaDatabaseMeta
        .getAttributes()
        .put(
            ImpalaDatabaseMeta.ATTRIBUTE_PREFIX_EXTRA_OPTION
                + impalaDatabaseMeta.getPluginId()
                + ".principal",
            "testP");
    urlString = impalaDatabaseMeta.getURL(testHostname, "" + port, testDbName);
    assertTrue(urlString.startsWith(ImpalaDatabaseMeta.URL_PREFIX));
    // Use known prefix
    urlString = "http://" + urlString.substring(ImpalaDatabaseMeta.URL_PREFIX.length());
    url = new URL(urlString);
    assertEquals(testHostname, url.getHost());
    assertEquals(port, url.getPort());
    assertEquals("/" + testDbName, url.getPath());
  }
 static {
   try {
     logger =
         Logger.getLogger("co.com.losalpes.marketplace.ws.avisoDespacho.Dispatchadvice_client_ep");
     URL baseUrl = Dispatchadvice_client_ep.class.getResource(".");
     if (baseUrl == null) {
       wsdlLocationURL =
           Dispatchadvice_client_ep.class.getResource(
               "http://portal.marketplace.losalpes.com.co:7001/soa-infra/services/default/ProcesoAvisoDespacho/dispatchadvice_client_ep?WSDL");
       if (wsdlLocationURL == null) {
         baseUrl = new File(".").toURL();
         wsdlLocationURL =
             new URL(
                 baseUrl,
                 "http://portal.marketplace.losalpes.com.co:7001/soa-infra/services/default/ProcesoAvisoDespacho/dispatchadvice_client_ep?WSDL");
       }
     } else {
       if (!baseUrl.getPath().endsWith("/")) {
         baseUrl = new URL(baseUrl, baseUrl.getPath() + "/");
       }
       wsdlLocationURL =
           new URL(
               baseUrl,
               "http://portal.marketplace.losalpes.com.co:7001/soa-infra/services/default/ProcesoAvisoDespacho/dispatchadvice_client_ep?WSDL");
     }
   } catch (MalformedURLException e) {
     logger.log(
         Level.ALL,
         "Failed to create wsdlLocationURL using http://portal.marketplace.losalpes.com.co:7001/soa-infra/services/default/ProcesoAvisoDespacho/dispatchadvice_client_ep?WSDL",
         e);
   }
 }
예제 #15
0
  public String getBamIndexPath() {

    if (indexPath != null) return indexPath;

    if (path.toLowerCase().startsWith("http://") || path.toLowerCase().startsWith("https://")) {
      // See if bam file is specified by parameter
      try {
        URL url = new URL(path);
        String queryString = url.getQuery();
        if (queryString != null) {
          Map<String, String> parameters = HttpUtils.parseQueryString(queryString);
          if (parameters.containsKey("index")) {
            return parameters.get("index");
          } else if (parameters.containsKey("file")) {
            String bamFile = parameters.get("file");
            String bamIndexFile = bamFile + ".bai";
            String newQueryString = queryString.replace(bamFile, bamIndexFile);
            return path.replace(queryString, newQueryString);
          } else {
            String ip = path.replace(url.getPath(), url.getPath() + ".bai");
            return ip;
          }
        }
      } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
      }
    }

    return path + ".bai";
  }
 static {
   try {
     logger =
         Logger.getLogger(
             "oracle.cloud.sampleapps.salesmerchtracker.model.proxy.SalesPartyService_Service");
     URL baseUrl = SalesPartyService_Service.class.getResource(".");
     if (baseUrl == null) {
       wsdlLocationURL =
           SalesPartyService_Service.class.getResource(
               "https://your_sales_cloud_URL/crmCommonSalesParties/SalesPartyService?WSDL");
       if (wsdlLocationURL == null) {
         baseUrl = new File(".").toURL();
         wsdlLocationURL =
             new URL(
                 baseUrl,
                 "https://your_sales_cloud_URL/crmCommonSalesParties/SalesPartyService?WSDL");
       }
     } else {
       if (!baseUrl.getPath().endsWith("/")) {
         baseUrl = new URL(baseUrl, baseUrl.getPath() + "/");
       }
       wsdlLocationURL =
           new URL(
               baseUrl,
               "https://your_sales_cloud_URL/crmCommonSalesParties/SalesPartyService?WSDL");
     }
   } catch (MalformedURLException e) {
     logger.log(
         Level.ALL,
         "Failed to create wsdlLocationURL using https://your_sales_cloud_URL/crmCommonSalesParties/SalesPartyService?WSDL",
         e);
   }
 }
예제 #17
0
  /** Creates a new instance of SysConfig */
  public SysConfig() {
    try {
      File dir = new File(System.getProperty("user.dir"));
      URL url = dir.toURI().toURL(); // file:/c:/almanac1.4/examples/
      System.out.println("Direktory :" + url.getPath());

      // BufferedReader in = new BufferedReader(new
      // FileReader(url.getPath()+File.separator+"dist"+File.separator+"sn.ini"));
      BufferedReader in =
          new BufferedReader(new FileReader(url.getPath() + File.separator + "sn.ini"));
      String str;
      while ((str = in.readLine()) != null) {
        System.out.println(str);
        if (str.toUpperCase().indexOf("SERVER") >= 0) {
          ServerLoc = str.substring(7, str.length());
          System.out.println("Server = " + ServerLoc);
        }

        if (str.toUpperCase().indexOf("DB") >= 0) {
          DBName = str.substring(3, str.length());
          System.out.println("DB = " + DBName);
        }

        if (str.toUpperCase().indexOf("PRINT_LABEL") >= 0) {
          PrintTextName = str.substring(12, str.length());
          System.out.println("print_label = " + PrintTextName);
        }

        if (str.toUpperCase().indexOf("PRINT_KWITANSI") >= 0) {
          PrintKwtName = str.substring(15, str.length()).trim();
          System.out.println("print_kwitansi = " + PrintKwtName);
        }

        if (str.toUpperCase().indexOf("PRINT_REPORT") >= 0) {
          PrintGraphName = str.substring(13, str.length());
          System.out.println("print_report = " + PrintGraphName);
        }

        if (str.toUpperCase().indexOf("SITE_ID") >= 0) {
          Site_Id = str.substring(8, str.length());
          System.out.println("Site_Id = " + Site_Id);
        }

        if (str.toUpperCase().indexOf("USR") >= 0) {
          sUser = str.substring(4, str.length());
          // System.out.println("Usr = "******"PAS") >= 0) {
          sPass = str.substring(4, str.length());
          // System.out.println("Pas = "******"SHS Go Open Source Err", JOptionPane.ERROR_MESSAGE);
    }
  }
예제 #18
0
 public static String getFileName(URL url) {
   int indexes = url.getPath().lastIndexOf(File.separator);
   if (indexes == -1) {
     indexes = url.getPath().lastIndexOf("/");
   }
   String fileName = url.getPath().substring(indexes + 1);
   return fileName;
 }
예제 #19
0
  public void testSimpleFileObject() throws IOException {

    FileSystemManager fs = new FileSystemManager();
    //
    String pathFile = "com/sinosoft/one/mvc/scanning/vfs/SimpleFileObject.class";
    URL urlFile = loader.getResource(pathFile);
    assertNotNull(urlFile);
    FileObject fileObjectFile = fs.resolveFile(urlFile);
    assertEquals(SimpleFileObject.class, fileObjectFile.getClass());
    //
    String pathDir = new File(urlFile.getPath()).getParent().replace('\\', '/');
    pathDir = StringUtils.removeEnd(pathDir, "/");
    URL urlDir = ResourceUtils.getURL(pathDir);
    assertNotNull(urlDir);
    File fileDir = new File(urlDir.getFile());
    assertTrue(fileDir.exists());
    FileObject fileObjectDir = fs.resolveFile(urlDir);
    assertEquals(SimpleFileObject.class, fileObjectDir.getClass());

    File dirFile = ResourceUtils.getFile(urlDir);
    assertTrue(urlDir.toString().endsWith("/"));
    assertTrue(urlDir.getPath().endsWith("/"));
    assertFalse(dirFile.getPath().endsWith("/"));
    assertTrue(fileObjectDir.toString().endsWith("/"));

    // exists
    assertTrue(fileObjectFile.exists());
    assertTrue(fileObjectDir.exists());
    assertFalse(fileObjectDir.getChild("a_not_exists_file.txt").exists());

    // getName
    assertEquals("vfs", fileObjectDir.getName().getBaseName());
    assertEquals("SimpleFileObject.class", fileObjectFile.getName().getBaseName());

    // getRelativeName
    assertEquals(
        "SimpleFileObject.class",
        fileObjectDir.getName().getRelativeName(fileObjectFile.getName()));
    assertEquals("", fileObjectDir.getName().getRelativeName(fileObjectDir.getName()));
    assertEquals("", fileObjectFile.getName().getRelativeName(fileObjectFile.getName()));

    // getType
    assertSame(FileType.FOLDER, fileObjectDir.getType());
    assertSame(FileType.FILE, fileObjectFile.getType());

    // getChild, getParent, and equals, getChildren
    assertEquals(fileObjectFile, fileObjectDir.getChild("SimpleFileObject.class"));
    assertEquals(fileObjectDir, fileObjectFile.getParent());
    assertSame(fileObjectFile, fileObjectDir.getChild("SimpleFileObject.class"));
    assertSame(fileObjectDir, fileObjectFile.getParent());
    assertTrue(ArrayUtils.contains(fileObjectDir.getChildren(), fileObjectFile));

    // getURL
    assertEquals(urlDir, fileObjectDir.getURL());
    assertEquals(urlFile, fileObjectFile.getURL());
  }
예제 #20
0
  /**
   * Open the connection for the given URL.
   *
   * @param url the url from which to open a connection.
   * @return a connection on the specified URL.
   * @throws java.io.IOException if an error occurs or if the URL is malformed.
   */
  @Override
  public URLConnection openConnection(URL url) throws IOException {
    if (url.getPath() == null || url.getPath().trim().length() == 0) {
      throw new MalformedURLException("Path can not be null or empty. Syntax: " + SYNTAX);
    }
    featureXmlURL = new URL(url.getPath());

    logger.debug("Blueprint xml URL is: [" + featureXmlURL + "]");
    return new Connection(url);
  }
예제 #21
0
  /*
   * Creates a HttpContext at the given address. If there is already a server
   * it uses that server to create a context. Otherwise, it creates a new
   * HTTP server. This sever is added to servers Map.
   */
  /*package*/ HttpContext createContext(String address) {
    try {
      HttpServer server;
      ServerState state;
      URL url = new URL(address);
      int port = url.getPort();
      if (port == -1) {
        port = url.getDefaultPort();
      }
      InetSocketAddress inetAddress = new InetSocketAddress(url.getHost(), port);
      synchronized (servers) {
        state = servers.get(inetAddress);
        if (state == null) {
          logger.fine("Creating new HTTP Server at " + inetAddress);
          // Creates server with default socket backlog
          server = HttpServer.create(inetAddress, 0);
          server.setExecutor(Executors.newCachedThreadPool());
          String path = url.toURI().getPath();
          logger.fine("Creating HTTP Context at = " + path);
          HttpContext context = server.createContext(path);
          server.start();

          // we have to get actual inetAddress from server, which can differ from the original in
          // some cases.
          // e.g. A port number of zero will let the system pick up an ephemeral port in a bind
          // operation,
          // or IP: 0.0.0.0 - which is used to monitor network traffic from any valid IP address
          inetAddress = server.getAddress();

          logger.fine("HTTP server started = " + inetAddress);
          state = new ServerState(server, path);
          servers.put(inetAddress, state);
          return context;
        }
      }
      server = state.getServer();

      if (state.getPaths().contains(url.getPath())) {
        String err =
            "Context with URL path "
                + url.getPath()
                + " already exists on the server "
                + server.getAddress();
        logger.fine(err);
        throw new IllegalArgumentException(err);
      }

      logger.fine("Creating HTTP Context at = " + url.getPath());
      HttpContext context = server.createContext(url.getPath());
      state.oneMoreContext(url.getPath());
      return context;
    } catch (Exception e) {
      throw new ServerRtException("server.rt.err", e);
    }
  }
예제 #22
0
 /**
  * Converts a URL to file.
  *
  * @param url a URL
  * @return the file
  */
 public static File toFile(URL url) {
   File file = null;
   try {
     /* TODO: this used to be new File(url.toURI()), but that didn't work?!?! Needs testing. */
     file = new File(url.getPath().replace("%20", " "));
     if (file.isDirectory()) {
       return file;
     }
   } catch (IllegalArgumentException iae) {
     throw iae;
   }
   return new File(url.getPath().replace("%20", " "));
 }
예제 #23
0
 private static String getTestResDir() {
   String resourceDir = System.getProperty(RESOURCE_DIR_PROPERTY);
   if (resourceDir != null && !resourceDir.isEmpty() && new File(resourceDir).isDirectory()) {
     return resourceDir;
   }
   // TEST_RES_DIR not explicitly set. Fallback to the class's source location.
   try {
     URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();
     return new File(location.getPath()).exists() ? location.getPath() : null;
   } catch (NullPointerException e) {
     // Prevent a lot of null checks by just catching the exception.
     return null;
   }
 }
 protected void updateURLComponents(String urlStr) {
   try {
     URL url = new URL(urlStr);
     String port = url.getPort() == -1 ? "" : ":" + url.getPort(); // $NON-NLS-1$ //$NON-NLS-2$
     fURLHost.setText(
         url.getProtocol() + "://" + url.getHost() + port + "/"); // $NON-NLS-1$ //$NON-NLS-2$
     if (url.getQuery() != null) {
       fURLPath.setText(url.getPath() + "?" + url.getQuery()); // $NON-NLS-1$
     } else {
       fURLPath.setText(url.getPath());
     }
   } catch (MalformedURLException e) {
     Logger.logException(e);
   }
 }
예제 #25
0
  /**
   * this method uses the appropriate lookup strategy to find a file. It is used by Kernel#require.
   *
   * @mri rb_find_file
   * @param name the file to find, this is a path name
   * @return the correct file
   */
  protected LoadServiceResource findFileInClasspath(String name) {
    // Look in classpath next (we do not use File as a test since UNC names will match)
    // Note: Jar resources must NEVER begin with an '/'. (previous code said "always begin with a
    // /")
    ClassLoader classLoader = runtime.getJRubyClassLoader();

    // handle security-sensitive case
    if (Ruby.isSecurityRestricted() && classLoader == null) {
      classLoader = runtime.getInstanceConfig().getLoader();
    }

    for (Iterator pathIter = loadPath.getList().iterator(); pathIter.hasNext(); ) {
      String entry = pathIter.next().toString();

      // if entry is an empty string, skip it
      if (entry.length() == 0) continue;

      // if entry starts with a slash, skip it since classloader resources never start with a /
      if (entry.charAt(0) == '/' || (entry.length() > 1 && entry.charAt(1) == ':')) continue;

      // otherwise, try to load from classpath (Note: Jar resources always uses '/')
      debugLogTry("fileInClasspath", entry + "/" + name);
      URL loc = classLoader.getResource(entry + "/" + name);

      // Make sure this is not a directory or unavailable in some way
      if (isRequireable(loc)) {
        LoadServiceResource foundResource = new LoadServiceResource(loc, loc.getPath());
        debugLogFound(foundResource);
        return foundResource;
      }
    }

    // if name starts with a / we're done (classloader resources won't load with an initial /)
    if (name.charAt(0) == '/' || (name.length() > 1 && name.charAt(1) == ':')) return null;

    // Try to load from classpath without prefix. "A/b.rb" will not load as
    // "./A/b.rb" in a jar file.
    debugLogTry("fileInClasspath", name);
    URL loc = classLoader.getResource(name);

    if (isRequireable(loc)) {
      LoadServiceResource foundResource = new LoadServiceResource(loc, loc.getPath());
      debugLogFound(foundResource);
      return foundResource;
    }

    return null;
  }
예제 #26
0
  public String evaluate(String urlStr, String partToExtract) {
    if (urlStr == null || partToExtract == null) {
      return null;
    }

    if (lastUrlStr == null || !urlStr.equals(lastUrlStr)) {
      try {
        url = new URL(urlStr);
      } catch (Exception e) {
        return null;
      }
    }
    lastUrlStr = urlStr;

    if (partToExtract.equals("HOST")) return url.getHost();
    if (partToExtract.equals("PATH")) return url.getPath();
    if (partToExtract.equals("QUERY")) return url.getQuery();
    if (partToExtract.equals("REF")) return url.getRef();
    if (partToExtract.equals("PROTOCOL")) return url.getProtocol();
    if (partToExtract.equals("FILE")) return url.getFile();
    if (partToExtract.equals("AUTHORITY")) return url.getAuthority();
    if (partToExtract.equals("USERINFO")) return url.getUserInfo();

    return null;
  }
예제 #27
0
 @Override
 public String getConfirmationMessage(URL url) {
   if (url != null) {
     String urlString = url.toExternalForm();
     if (urlString.matches(PATTERN_OSM_API_URL)) {
       // TODO: proper i18n after stabilization
       String message =
           "<ul><li>"
               + tr("OSM Server URL:")
               + " "
               + url.getHost()
               + "</li><li>"
               + tr("Command")
               + ": "
               + url.getPath()
               + "</li>";
       if (url.getQuery() != null) {
         message +=
             "<li>"
                 + tr("Request details: {0}", url.getQuery().replaceAll(",\\s*", ", "))
                 + "</li>";
       }
       message += "</ul>";
       return message;
     }
     // TODO: other APIs
   }
   return null;
 }
예제 #28
0
 private File stubTestConfigOutputPropsFile() throws Exception {
   URL turl = getClass().getResource("/");
   File f = new File(turl.getPath() + TEST_PROPS_FILE);
   f.createNewFile();
   f.deleteOnExit();
   return f;
 }
예제 #29
0
 public static void switch_chan(String httpurl, String hotlink, String userid, Handler handler) {
   try {
     String param = "http://127.0.0.1:9898/cmd.xml?cmd=switch_chan&";
     URL url = new URL(httpurl.replace("p2p", "http"));
     String server = url.getAuthority();
     String videoId = url.getPath();
     videoId = videoId.subSequence(1, videoId.length() - 3).toString();
     param += "id=" + videoId;
     param += "&server=" + server;
     param += "&link=" + hotlink;
     param += "&userid=" + userid;
     String playurl = "http://127.0.0.1:9898/" + videoId + ".ts";
     // String playurl="http://111.11.28.16/mrtpweb/aaaa.mp4";
     if (tvthread != null) {
       tvthread.stopreq();
     }
     LogUtils.write(TAG, param);
     LogUtils.write(TAG, playurl);
     tvthread = new ForceTvThread(param, playurl, handler);
     tvthread.start();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  public void checkJParse(String filename) throws Exception {
    URL testFolderURL = TestParser.class.getClassLoader().getResource(SAMPLES_DIR);
    String testFolder = testFolderURL.getPath();

    String J_pathToFile = testFolder + "/" + filename;

    ANTLRInputStream input = new ANTLRFileStream(J_pathToFile);
    JLexer l = new JLexer(input);
    TokenStream tokens = new CommonTokenStream(l);

    JParser parser = new JParser(tokens);
    parser.removeErrorListeners();
    int[] errors = {0};
    parser.addErrorListener(
        new BaseErrorListener() {
          @Override
          public void syntaxError(
              Recognizer<?, ?> recognizer,
              Object offendingSymbol,
              int line,
              int charPositionInLine,
              String msg,
              RecognitionException e) {
            errors[0]++;
          }
        });
    ParserRuleContext tree = parser.file();
    assertTrue(tree != null);
    assertEquals(Token.EOF, tree.getStop().getType());
    assertEquals(0, errors[0]);
  }