Java Code Examples for java.net.MalformedURLException

The following are top voted examples for showing how to use java.net.MalformedURLException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OpenJSharp   File: JavacFileManager.java   View source code 6 votes vote down vote up
public ClassLoader getClassLoader(Location location) {
    nullCheck(location);
    Iterable<? extends File> path = getLocation(location);
    if (path == null)
        return null;
    ListBuffer<URL> lb = new ListBuffer<URL>();
    for (File f: path) {
        try {
            lb.append(f.toURI().toURL());
        } catch (MalformedURLException e) {
            throw new AssertionError(e);
        }
    }

    return getClassLoader(lb.toArray(new URL[lb.size()]));
}
 
Example 2
Project: android-dev-challenge   File: NetworkUtils.java   View source code 6 votes vote down vote up
/**
 * Builds the URL used to talk to the weather server using a location. This location is based
 * on the query capabilities of the weather provider that we are using.
 *
 * @param locationQuery The location that will be queried for.
 * @return The URL to use to query the weather server.
 */
private static URL buildUrlWithLocationQuery(String locationQuery) {
    Uri weatherQueryUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
            .appendQueryParameter(QUERY_PARAM, locationQuery)
            .appendQueryParameter(FORMAT_PARAM, format)
            .appendQueryParameter(UNITS_PARAM, units)
            .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
            .build();

    try {
        URL weatherQueryUrl = new URL(weatherQueryUri.toString());
        Log.v(TAG, "URL: " + weatherQueryUrl);
        return weatherQueryUrl;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 3
Project: Equella   File: IframePortletEditorSection.java   View source code 6 votes vote down vote up
@Override
protected void customValidate(SectionInfo info, PortletEditingBean portlet, Map<String, Object> errors)
{
	try
	{
		final URL u = new URL(url.getValue(info));
		try
		{
			u.openConnection().connect();
		}
		catch( Exception e )
		{
			errors.put(
				"url",
				resources.getString("editor.rss.error.url.notreachable",
					e.getClass().getName() + ' ' + e.getMessage()));
		}
	}
	catch( MalformedURLException mal )
	{
		errors.put("url", resources.getString("editor.rss.error.url.notvalid"));
	}
}
 
Example 4
Project: VirusTotal-public-and-private-API-2.0-implementation-in-pure-Java   File: HttpsPost.java   View source code 6 votes vote down vote up
/**
 *
 * @param requestURL
 * @param entity
 * @throws MalformedURLException
 * @throws IOException
 */
public HttpsPost(String requestURL, MultipartEntity entity) throws MalformedURLException, IOException {
    String boundary = "e2a540ab4e6c5ed79c01157c255a2b5007e157d7";
    URL url = new URL(requestURL);
    connection = (HttpsURLConnection) url.openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    process(entity, connection);
}
 
Example 5
Project: k-framework   File: AlipaySubmit.java   View source code 6 votes vote down vote up
/**
    * 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数
    * 注意:远程解析XML出错,与服务器是否支持SSL等配置有关
    * @return 时间戳字符串
    * @throws IOException
    * @throws DocumentException
    * @throws MalformedURLException
    */
public static String query_timestamp(AlipayConfig config) throws MalformedURLException,
                                                       DocumentException, IOException {

       //构造访问query_timestamp接口的URL串
       String strUrl = ALIPAY_GATEWAY_NEW + "service=query_timestamp&partner=" + config.getPartnerId() + "&_input_charset" +AlipayConfig.inputCharset;
       StringBuffer result = new StringBuffer();

       SAXReader reader = new SAXReader();
       Document doc = reader.read(new URL(strUrl).openStream());

       List<Node> nodeList = doc.selectNodes("//alipay/*");

       for (Node node : nodeList) {
           // 截取部分不需要解析的信息
           if (node.getName().equals("is_success") && node.getText().equals("T")) {
               // 判断是否有成功标示
               List<Node> nodeList1 = doc.selectNodes("//response/timestamp/*");
               for (Node node1 : nodeList1) {
                   result.append(node1.getText());
               }
           }
       }

       return result.toString();
   }
 
Example 6
Project: improved-journey   File: SolrCloudSolrJSearcher.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws MalformedURLException, SolrServerException {
		String zkHost = "localhost:2181";
		String defaultCollection = "collection1";
		CloudSolrServer solr = new CloudSolrServer(zkHost);
		solr.setDefaultCollection(defaultCollection);
        
/*		ModifiableSolrParams params = new ModifiableSolrParams();
        params.set("q", "cat:electronics");
    	params.set("defType", "edismax");
    	params.set("start", "0");*/
		
		SolrQuery params = new SolrQuery();
		params.setQuery("*:*");
		params.setSort("score ",ORDER.desc);
		params.setStart(Integer.getInteger("0"));
		params.setRows(Integer.getInteger("100"));
		
    

		QueryResponse response = solr.query(params);
		SolrDocumentList results = response.getResults();
		for (int i = 0; i < results.size(); ++i) {
			System.out.println(results.get(i));
		}
	}
 
Example 7
Project: exam   File: OrganisationController.java   View source code 6 votes vote down vote up
@Restrict({@Group("STUDENT")})
public CompletionStage<Result> listOrganisations() throws MalformedURLException {
    URL url = parseUrl();
    WSRequest request = wsClient.url(url.toString());
    String localRef = ConfigFactory.load().getString("sitnet.integration.iop.organisationRef");

    Function<WSResponse, Result>  onSuccess = response -> {
        JsonNode root = response.asJson();
        if (response.getStatus() != 200) {
            return internalServerError(root.get("message").asText("Connection refused"));
        }
        if (root instanceof ArrayNode) {
            ArrayNode node = (ArrayNode) root;
            for (JsonNode n : node) {
                ((ObjectNode) n).put("homeOrg", n.get("_id").asText().equals(localRef));
            }
        }
        return ok(root);
    };
    return request.get().thenApplyAsync(onSuccess);
}
 
Example 8
Project: parabuild-ci   File: HttpServletRequestTest.java   View source code 6 votes vote down vote up
public void testGetSessionForFirstTime() throws MalformedURLException {
    WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
    ServletUnitContext context = new ServletUnitContext();
    assertEquals( "Initial number of sessions in context", 0, context.getSessionIDs().size() );

    ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );
    assertNull( "New request should not have a request session ID", request.getRequestedSessionId() );
    assertNull( "New request should not have a session", request.getSession( /* create */ false ) );
    assertEquals( "Number of sessions in the context after request.getSession(false)", 0, context.getSessionIDs().size() );

    HttpSession session = request.getSession();
    assertNotNull( "No session created", session );
    assertTrue( "Session not marked as new", session.isNew() );
    assertEquals( "Number of sessions in context after request.getSession()", 1, context.getSessionIDs().size() );
    assertSame( "Session with ID", session, context.getSession( session.getId() ) );
    assertNull( "New request should still not have a request session ID", request.getRequestedSessionId() );
}
 
Example 9
Project: SugarOnRest   File: Generators.java   View source code 6 votes vote down vote up
private static STGroupFile getTemplateGroupFile(String templatePath) throws MalformedURLException {

        if (templatePath == null) {
             return null;
        }

        if (!templatePath.contains(".jar!")) {
            return new STGroupFile(templatePath);
        }

        String protocol = "jar:";
        if (templatePath.startsWith(protocol)) {
            protocol = "";
        }

        URL url = new URL(protocol + templatePath);
        return  new STGroupFile(url, "US-ASCII", '%', '%');
    }
 
Example 10
Project: caoutchouc   File: Caoutchouc.java   View source code 6 votes vote down vote up
private String[] addServerInClasspath(String[] args) {
    return Arrays.stream(args).filter(arg -> {
        if(arg.startsWith("--serverJar=")) {
            String serverURL = arg.substring("--serverJar=".length());
            File serverFile = new File(serverURL);

            if(!serverFile.exists())
                throw new IllegalArgumentException("Cannot found server jar.");

            try {
                this.classLoader.addURL(serverFile.toURI().toURL());
            } catch(MalformedURLException exc) {
                exc.printStackTrace();
            }
            return false;
        } else {
            return true;
        }
    }).toArray(String[]::new);
}
 
Example 11
Project: incubator-netbeans   File: ConnectionType.java   View source code 6 votes vote down vote up
@Override
protected void storeConfigValues() {
    RepositoryConnection rc = repository.getSelectedRCIntern();
    if(rc == null) {
        return; // uups
    }

    try {
        SVNUrl repositoryUrl = rc.getSvnUrl();
        if(repositoryUrl.getProtocol().startsWith("svn+")) {
            SvnConfigFiles.getInstance().setExternalCommand(SvnUtils.getTunnelName(repositoryUrl.getProtocol()), panel.tunnelCommandTextField.getText());
        }
    } catch (MalformedURLException mue) {
        // should not happen
        Subversion.LOG.log(Level.INFO, null, mue);
    }
}
 
Example 12
Project: jaffa-framework   File: URLHelper.java   View source code 6 votes vote down vote up
/** Search for the input resource in the filesystem */
private static URL getUrlFromFilesystem(String resourceName) {
    URL url = null;
    File f = new File(resourceName);
    try {
        if (f.exists() && f.isFile()) {
            // The following works in Java1.6
            //// The following does not work if the filename contains space-characters and if we do a url.openStream() on it.
            ////url = f.toURI().toURL();
            //url = f.toURL();
            url = f.toURI().toURL();
        }
    } catch (MalformedURLException e) {
        // do nothing
        url = null;
    }
    return url;
}
 
Example 13
Project: incubator-netbeans   File: BasicBrandingPanel.java   View source code 6 votes vote down vote up
private URL browseIcon( ImagePreview preview ) {
    URL res = null;
    JFileChooser chooser = UIUtil.getIconFileChooser();
    int ret = chooser.showDialog(this, NbBundle.getMessage(getClass(), "LBL_Select")); // NOI18N
    if (ret == JFileChooser.APPROVE_OPTION) {
        File file =  chooser.getSelectedFile();
        try {
            res = Utilities.toURI(file).toURL();
            preview.setImage(new ImageIcon(res));
            setModified();
        } catch (MalformedURLException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return res;
}
 
Example 14
Project: skyscanner-business-client-java   File: TravelCommon.java   View source code 6 votes vote down vote up
/**
 *
 * @param locale
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public JSONObject getMarkets(String locale) throws MalformedURLException,
		IOException, JSONException {
	ArrayList<String> crumbs = new ArrayList<String>();
	crumbs.add("reference");
	crumbs.add(version);
	crumbs.add("countries");
	crumbs.add(locale);

	HashMap<String, String> parameters = new HashMap<String, String>();
	parameters.put("apiKey", apiKey);

	HashMap<String, String> properties = new HashMap<String, String>();
	properties.put("charset", "utf-8");
	properties.put("Accept", "application/json");

	request.buildUrl(baseUrl, crumbs, parameters);
	request.connect(properties);
	parsed = new JSONObject(request.get());

	return parsed;
}
 
Example 15
Project: RA-Reader   File: Pagescrap.java   View source code 6 votes vote down vote up
public ArrayList getRegisterNr() throws MalformedURLException, IOException {
    TextFormatter tf = new TextFormatter();
    URLConnection connection = new URL("http://pmg.ages.at/pls/psmlfrz/pmgweb2$.Startup").openConnection();
    ArrayList<Integer> numbers;
    try (Scanner regis = new Scanner(connection.getInputStream())) {
        regis.useDelimiter("\\Z");
        String helpi = searchDeli;
        searchDeli = "Registernummer:";
        String numbersText = tf.htmlToText(getRegValues(regis));
        String[] numbersField = numbersText.split("#");
        numbers = new ArrayList<>();
        for (String number : numbersField) {
            numbers.add(Integer.parseInt(number));
        }   searchDeli = helpi;
    }
    return numbers;
}
 
Example 16
Project: monarch   File: AbstractTierStoreWriter.java   View source code 6 votes vote down vote up
protected static Configuration getConfiguration(final Properties props) {
  Configuration conf = new Configuration();
  try {
    String hdfsSiteXMLPath = props.getProperty(CommonConfig.HDFS_SITE_XML_PATH);
    String hadoopSiteXMLPath = props.getProperty(CommonConfig.HADOOP_SITE_XML_PATH);
    if (hdfsSiteXMLPath != null) {
      conf.addResource(Paths.get(hdfsSiteXMLPath).toUri().toURL());
    }
    if (hadoopSiteXMLPath != null) {
      conf.addResource(Paths.get(hadoopSiteXMLPath).toUri().toURL());
    }
  } catch (MalformedURLException mue) {
    logger.error("Error while parsing hadoop paths.", mue);
  }
  return conf;
}
 
Example 17
Project: jmx-prometheus-exporter   File: SchemaGenerator.java   View source code 6 votes vote down vote up
private void generate() {
  try {
    JAXBContext.newInstance(Configuration.class).generateSchema(new SchemaOutputResolver() {
      @Override
      public @NotNull Result createOutput(@NotNull String namespace, @NotNull String suggestedFileName) throws MalformedURLException {
        final File file = new File(filename);
        final StreamResult result = new StreamResult(file);
        result.setSystemId(file.toURI().toURL().toString());
        return result;
      }
    });
    logger.info("Schema successfully generated to " + filename);
  } catch (JAXBException | IOException e) {
    logger.error("Failed to generate schema", e);
  }
}
 
Example 18
Project: lazycat   File: ApplicationContextFacade.java   View source code 6 votes vote down vote up
@Override
public URL getResource(String path) throws MalformedURLException {
	if (Globals.IS_SECURITY_ENABLED) {
		try {
			return (URL) invokeMethod(context, "getResource", new Object[] { path });
		} catch (Throwable t) {
			ExceptionUtils.handleThrowable(t);
			if (t instanceof MalformedURLException) {
				throw (MalformedURLException) t;
			}
			return null;
		}
	} else {
		return context.getResource(path);
	}
}
 
Example 19
Project: ge-export   File: HttpClientFactory.java   View source code 6 votes vote down vote up
public static HttpClient<ByteBuf, ByteBuf> create(String server, final String portStr) {
    int port = 0;

    try {

        URL url = new URL(defaultToHttps(server));
        if (portStr == null) {
            port = url.getDefaultPort();
        } else if (Integer.parseInt(portStr) > 0){
            port = Integer.parseInt(portStr);
        }
        final HttpClient<ByteBuf, ByteBuf> httpClient = HttpClient.newClient(new InetSocketAddress(
                url.getHost(), port));
        if(url.getProtocol().equals("https")) {
            return httpClient.unsafeSecure();
        } else if (url.getProtocol().equals("http")) {
            return httpClient;
        } else {
            throw new RuntimeException("Unsuported protocol");
        }
    }

    catch(MalformedURLException e){
        throw new RuntimeException(e);
    }
}
 
Example 20
Project: bskyblock   File: BSBLocale.java   View source code 6 votes vote down vote up
/**
 * Provides localization
 * Locale files are .yml and have the filename "bsb_[country and language tag].yml", e.g. bsb_en_GB.yml
 * @param plugin
 * @throws MalformedURLException
 */
public BSBLocale(Plugin plugin, String localeId) throws MalformedURLException {
    this.plugin = plugin;
    //this.localeId = localeId;
    // Check if the folder exists
    File localeDir = new File(plugin.getDataFolder(), LOCALE_FOLDER);
    if (!localeDir.exists()) {
        localeDir.mkdirs();
    }
    // Check if this file does not exist
    File localeFile = new File(localeDir, localeId);
    if (!localeFile.exists()) {
        // Does not exist - look in JAR and save if possible
        plugin.saveResource(LOCALE_FOLDER + localeId, false);
    }
    languageTag = localeId.substring(4, localeId.length() - 4).replace('_', '-');
    URL[] urls = {localeDir.toURI().toURL()};
    ClassLoader loader = new URLClassLoader(urls);
    localeObject = Locale.forLanguageTag(languageTag);
    rb = ResourceBundle.getBundle("bsb", localeObject, loader, YamlResourceBundle.Control.INSTANCE);
}
 
Example 21
Project: incubator-netbeans   File: SourcePathProviderImpl.java   View source code 6 votes vote down vote up
private ClassPath getAdditionalClassPath(File baseDir) {
    try {
        String root = BaseUtilities.toURI(baseDir).toURL().toExternalForm();
        Properties sourcesProperties = Properties.getDefault ().getProperties ("debugger").getProperties ("sources");
        List<String> additionalSourceRoots = (List<String>) sourcesProperties.
                getProperties("additional_source_roots").
                getMap("project", Collections.emptyMap()).
                get(root);
        if (additionalSourceRoots == null || additionalSourceRoots.isEmpty()) {
            return null;
        }
        List<FileObject> additionalSourcePath = new ArrayList<FileObject>(additionalSourceRoots.size());
        for (String ar : additionalSourceRoots) {
            FileObject fo = getFileObject(ar);
            if (fo != null && fo.canRead()) {
                additionalSourcePath.add(fo);
            }
        }
        this.additionalSourceRoots = new LinkedHashSet<String>(additionalSourceRoots);
        return createClassPath(
                additionalSourcePath.toArray(new FileObject[0]));
    } catch (MalformedURLException ex) {
        Exceptions.printStackTrace(ex);
        return null;
    }
}
 
Example 22
Project: ripme   File: FlickrRipper.java   View source code 6 votes vote down vote up
public String getAlbumTitle(URL url) throws MalformedURLException {
    if (!url.toExternalForm().contains("/sets/")) {
        return super.getAlbumTitle(url);
    }
    try {
        // Attempt to use album title as GID
        Document doc = getFirstPage();
        String user = url.toExternalForm();
        user = user.substring(user.indexOf("/photos/") + "/photos/".length());
        user = user.substring(0, user.indexOf("/"));
        String title = doc.select("meta[name=description]").get(0).attr("content");
        if (!title.equals("")) {
            return getHost() + "_" + user + "_" + title;
        }
    } catch (Exception e) {
        // Fall back to default album naming convention
    }
    return super.getAlbumTitle(url);
}
 
Example 23
Project: manifold-ij   File: ManProject.java   View source code 5 votes vote down vote up
private String maybeGetProcessorPath()
{
  int jdkVersion = findJdkVersion();
  if( jdkVersion >= 9 )
  {
    PathsList pathsList = ProjectRootManager.getInstance( _ijProject ).orderEntries().withoutSdk().librariesOnly().getPathsList();
    for( VirtualFile path: pathsList.getVirtualFiles() )
    {
      String extension = path.getExtension();
      if( extension != null && extension.equals( "jar" ) && path.getNameWithoutExtension().contains( "manifold-" ) )
      {
        try
        {
          return " -processorpath " + new File( new URL( path.getUrl() ).getFile() ).getAbsolutePath() ;
        }
        catch( MalformedURLException e )
        {
          return "";
        }
      }
    }
  }
  return "";
}
 
Example 24
Project: incubator-netbeans   File: SvnModuleConfig.java   View source code 5 votes vote down vote up
public RepositoryConnection getRepositoryConnection(String url) {
    RepositoryConnection rc = getRepositoryConnectionIntern(url.toString());
    if (rc == null) {
        try {
            // this will remove username from the hostname
            rc = getRepositoryConnectionIntern(new RepositoryConnection(url).getSvnUrl().toString());
        } catch (MalformedURLException ex) {
            // not interested
        }
    }
    return rc;
}
 
Example 25
Project: eZooKeeper   File: JmxConnectionNewWizardPage1.java   View source code 5 votes vote down vote up
public JMXServiceURL getServiceUrl() {
    Text jmxUrlText = (Text) getGridComposite().getControl(CONTROL_NAME_JMX_URL_TEXT);
    String jmxServiceUrlString = jmxUrlText.getText();

    try {
        return new JMXServiceURL(jmxServiceUrlString);
    }
    catch (MalformedURLException e) {
        // Validation should ensure that this should never happen
        return null;
    }
}
 
Example 26
Project: monarch   File: DtdResolver.java   View source code 5 votes vote down vote up
/***
 * Gets the URL for Cache dtd
 * 
 * @return dtd url as string
 * @throws MalformedURLException
 */
@Deprecated
public URL getDtdUrl() throws MalformedURLException {
  if (isHttpUrlOK(CacheXml.LATEST_SYSTEM_ID)) {
    return new URL(CacheXml.LATEST_SYSTEM_ID);
  } else {
    URL dtdURL = getClass().getResource(CacheXml.LATEST_DTD_LOCATION);
    return dtdURL;
  }
}
 
Example 27
Project: incubator-netbeans   File: J2SEPlatformCustomizer.java   View source code 5 votes vote down vote up
private boolean addPath (File f) {
    try {
        return this.addPath (findRoot(f, type));
    } catch (MalformedURLException mue) {
        return false;
    }
}
 
Example 28
Project: marathonv5   File: JavaDriverCommandExecutor.java   View source code 5 votes vote down vote up
private static URL getURL(JavaProfile profile) {
    try {
        return new URL("http", "localhost", profile.getPort(), "/");
    } catch (MalformedURLException e) {
        throw new WebDriverException("Unable to create URL for the server", e);
    }
}
 
Example 29
Project: ixortalk.aws.cognito.jwt.security.filter   File: JwtAutoConfiguration.java   View source code 5 votes vote down vote up
@Bean
public ConfigurableJWTProcessor configurableJWTProcessor() throws MalformedURLException {
    ResourceRetriever resourceRetriever = new DefaultResourceRetriever(jwtConfiguration.getConnectionTimeout(), jwtConfiguration.getReadTimeout());
    URL jwkSetURL = new URL(jwtConfiguration.getJwkUrl());
    JWKSource keySource = new RemoteJWKSet(jwkSetURL, resourceRetriever);
    ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor();
    JWSKeySelector keySelector = new JWSVerificationKeySelector(RS256, keySource);
    jwtProcessor.setJWSKeySelector(keySelector);
    return jwtProcessor;
}
 
Example 30
Project: cdep   File: TestMergeCDepManifestYmls.java   View source code 5 votes vote down vote up
@Test
public void testMergeAndroidiOS() throws MalformedURLException {
  CDepManifestYml iOSManifest = ResolvedManifests.sqliteiOS().manifest.cdepManifestYml;
  CDepManifestYml androidManifest = ResolvedManifests.sqliteAndroid().manifest.cdepManifestYml;
  CDepManifestYml result = MergeCDepManifestYmls.merge(androidManifest, iOSManifest);
  iOS iOS = result.iOS;
  assert iOSManifest.iOS != null;
  assert iOSManifest.iOS.archives != null;
  assertThat(iOS.archives).hasLength(iOSManifest.iOS.archives.length);
  Android android = result.android;
  assert androidManifest.android != null;
  assert androidManifest.android.archives != null;
  assertThat(android.archives).hasLength(androidManifest.android.archives.length);
}
 
Example 31
Project: siiMobilityAppKit   File: Whitelist.java   View source code 5 votes vote down vote up
public URLPattern(String scheme, String host, String port, String path) throws MalformedURLException {
    try {
        if (scheme == null || "*".equals(scheme)) {
            this.scheme = null;
        } else {
            this.scheme = Pattern.compile(regexFromPattern(scheme, false), Pattern.CASE_INSENSITIVE);
        }
        if ("*".equals(host)) {
            this.host = null;
        } else if (host.startsWith("*.")) {
            this.host = Pattern.compile("([a-z0-9.-]*\\.)?" + regexFromPattern(host.substring(2), false), Pattern.CASE_INSENSITIVE);
        } else {
            this.host = Pattern.compile(regexFromPattern(host, false), Pattern.CASE_INSENSITIVE);
        }
        if (port == null || "*".equals(port)) {
            this.port = null;
        } else {
            this.port = Integer.parseInt(port,10);
        }
        if (path == null || "/*".equals(path)) {
            this.path = null;
        } else {
            this.path = Pattern.compile(regexFromPattern(path, true));
        }
    } catch (NumberFormatException e) {
        throw new MalformedURLException("Port must be a number");
    }
}
 
Example 32
Project: the-vigilantes   File: InternalXmlRpcMethodCaller.java   View source code 5 votes vote down vote up
public InternalXmlRpcMethodCaller(String url) throws FabricCommunicationException {
    try {
        this.xmlRpcClient = new Client(url);
    } catch (MalformedURLException ex) {
        throw new FabricCommunicationException(ex);
    }
}
 
Example 33
Project: smb-nio   File: SMBFileSystem.java   View source code 5 votes vote down vote up
/**
 * Returns the root directories, i.e. the list of shares, provided by the current {@link SMBFileSystem}.
 *
 * @return List of shares for the current {@link SMBFileSystem}.
 */
@Override
public Iterable<Path> getRootDirectories() {
    if (!this.isOpen()) throw new ClosedFileSystemException();
    try {
        SmbFile file = new SmbFile(SMBFileSystem.SMB_SCHEME + SMBFileSystem.SCHEME_SEPARATOR + this.identifier, "/");
        return Arrays.stream(file.list()).map(s -> (Path)(new SMBPath(this, "/" + s))).collect(Collectors.toList());
    } catch (MalformedURLException | SmbException e) {
        return new ArrayList<>(0);
    }
}
 
Example 34
Project: ripme   File: TwodgalleriesRipper.java   View source code 5 votes vote down vote up
@Override
public String getGID(URL url) throws MalformedURLException {
    Pattern p; Matcher m;

    p = Pattern.compile("^.*2dgalleries.com/artist/([a-zA-Z0-9\\-]+).*$");
    m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return m.group(1);
    }
    throw new MalformedURLException(
            "Expected 2dgalleries.com album format: "
                    + "2dgalleries.com/artist/..."
                    + " Got: " + url);
}
 
Example 35
Project: WurstSDK   File: GuiInstallScreen.java   View source code 5 votes vote down vote up
InstallThread(String url) {
    if (!url.startsWith("http")) {
        String artifact = url.split("/")[2];
        this.artifact = artifact;
        url = REPO_URL + url + "/LATEST/" + artifact + "-LATEST.jar";
    }
    try {
        this.url = new URL(url);
        if (artifact == null)
            artifact = Paths.get(this.url.toURI()).toFile().getName();
    } catch (MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
    }
}
 
Example 36
Project: parabuild-ci   File: CheckMessages.java   View source code 5 votes vote down vote up
public CheckMessages(String pluginDescriptorFilename)
	throws DocumentException, MalformedURLException {

	pluginDescriptorDoc = new XMLFile(pluginDescriptorFilename);

	declaredDetectorsSet =
		pluginDescriptorDoc.collectAttributes("/FindbugsPlugin/Detector", "class");

	declaredAbbrevsSet =
		pluginDescriptorDoc.collectAttributes("/FindbugsPlugin/BugPattern", "abbrev");
}
 
Example 37
Project: incubator-netbeans   File: Merge.java   View source code 5 votes vote down vote up
public SVNUrl getMergeEndUrl() {
    try {
        return mergeEndRepositoryPaths.getRepositoryFiles()[0].getFileUrl();
    } catch (MalformedURLException ex) {
        // should be already checked and
        // not happen at this place anymore
        Subversion.LOG.log(Level.INFO, null, ex);
    }
    return null;
}
 
Example 38
Project: AutomationFrameworkTPG   File: TestBase.java   View source code 5 votes vote down vote up
@BeforeMethod(alwaysRun = true)
public void baseSetup(Method method, Object[] params) throws MalformedURLException, NoSuchFieldException, NotDirectoryException, JsonProcessingException {
	if (params.length > 0 && params[0] instanceof WebDriverInstance){
		webDriverInstance = (WebDriverInstance)params[0];
	}
	String tag = UUID.randomUUID().toString();
	logger.info("Tagging test thread with [{}]...", tag);
	ThreadContext.put(THREAD_TAG, tag);
	logTestSetup(method);
	logger.info("Base setup complete!");
}
 
Example 39
Project: gemoc-studio   File: OptionTemplateSection.java   View source code 5 votes vote down vote up
/**
 * Implements the abstract method by looking for templates using the
 * following path:
 * <p>
 * [install location]/[templateDirectory]/[sectionId]
 * 
 * @return the URL of the location where files to be emitted by this
 *         template are located.
 */
public URL getTemplateLocation() {
	URL url = getInstallURL();
	try {
		String location = getTemplateDirectory() + "/" //$NON-NLS-1$
				+ getSectionId() + "/"; //$NON-NLS-1$
		return new URL(url, location);
	} catch (MalformedURLException e) {
		return null;
	}
}
 
Example 40
Project: incubator-netbeans   File: ClusteredIndexablesTest.java   View source code 5 votes vote down vote up
public URL getURL() {
    try {
        return new URL(relativePath);
    } catch (MalformedURLException ex) {
        return null;
    }
}