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 product more good examples.

Example 1
Project: btpka3.github.com   File: SecurityPolicySpi.java View source code Vote up 7 votes
/**
 *	?????? "java.ext.dirs"????????????URL?
 */
public static String[] parseExtDirs() throws IOException {
	final String extDir = "java.ext.dirs";
	String s = System.getProperty(extDir);
	List<String> dirs = new ArrayList<String>();
	if (s != null) {
		StringTokenizer st = new StringTokenizer(s, File.pathSeparator);
		int count = st.countTokens();
		for (int i = 0; i < count; i++) {
			String nextToken = st.nextToken();
			if (nextToken == null || nextToken.matches("^\\s*$")) {
				continue;
			}
			File file = new File(nextToken);
			String dir = null;
			try {
				dir = file.getCanonicalFile().toURI().toURL().toString();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			dir += dir.endsWith("/") ? "*" : "/*";
			dirs.add(dir);
		}
	}
	return dirs.toArray(new String[0]);
}
 
Example 2
Project: felinx   File: Activator.java View source code Vote up 6 votes
@Override
protected void initializeImageRegistry(ImageRegistry registry) {
	super.initializeImageRegistry(registry);
	try {
		registry.put(IMAGE_RUN, createDescriptor(IMAGE_RUN));
		registry.put(IMAGE_DEBUG, createDescriptor(IMAGE_DEBUG));
	} catch (MalformedURLException e) {
		e.printStackTrace();
	}
}
 
Example 3
Project: AmazeFileManager   File: Main.java View source code Vote up 6 votes
public void goBack() {
    if(openMode==3){
        //// TODO: 07-11-2015
        return;
    }
    if (openMode == 2) {
        loadlist(home, false, 0);
        return;
    }
    File f = new File(CURRENT_PATH);
    if (!results) {
        if (selection) {
            adapter.toggleChecked(false);
        } else {
            if (openMode == 1)
                try {
                    if (!MAIN_ACTIVITY.Servers.contains(CURRENT_PATH)) {
                        String path = (new SmbFile(CURRENT_PATH).getParent());
                        loadlist((path), true,openMode);
                    } else loadlist(home, false, 0);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            else if (CURRENT_PATH.equals("/") || CURRENT_PATH.equals(home))
                MAIN_ACTIVITY.exit();
            else if (utils.canGoBack(f)) {
                loadlist(f.getParent(), true, openMode);
            } else MAIN_ACTIVITY.exit();
        }
    } else {
        if (searchTask != null) {
            if (searchTask.getStatus() == AsyncTask.Status.RUNNING)
                searchTask.cancel(true);
            searchTask = null;
        }
        loadlist(f.getPath(), true, 0);
    }
}
 
Example 4
Project: eadventure   File: ZipInputStreamCreator.java View source code Vote up 6 votes
@Override
public URL buildURL(String path) {
	try {
		return createAssetURL(zipFile, zipPath, path);
	} catch (MalformedURLException e) {
		e.printStackTrace();
	}
	return null;

}
 
Example 5
Project: abmash   File: Window.java View source code Vote up 6 votes
/**
 * Gets content type of current page.
 * 
 * @return content type
 */
public String getCurrentContentType() {
	String contentType = null;
	try {
		contentType = getContentTypeOfURL(new URL(browser.getWebDriver().getCurrentUrl()));
	} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return contentType;
}
 
Example 6
Project: jogltest   File: ResourceUtil.java View source code Vote up 6 votes
public static URL getURL(String internalPath) {
	try {
		return new URL(getInternalBaseURL(), internalPath);
	} catch (MalformedURLException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 7
Project: fiji   File: CCellRenderer.java View source code Vote up 6 votes
/**
 * Returns an icon.
 *
 * @param resource The icon to retrieve.  This should either be a file,
 *        or a resource loadable by the current ClassLoader.
 * @return The icon.
 */
private Icon getIcon(String resource) {
	ClassLoader cl = getClass().getClassLoader();
	URL url = cl.getResource(resource);
	if (url == null) {
		File file = new File(resource);
		try {
			url = file.toURI().toURL();
		} catch (MalformedURLException mue) {
			mue.printStackTrace(); // Never happens
		}
	}
	return url != null ? new ImageIcon(url) : null;
}
 
Example 8
Project: p4   File: SetCurrentP4ServiceServlet.java View source code Vote up 6 votes
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		User user = Tools.getSessionAttribute(request.getSession(), P4GUI.USER_BEAN_NAME, User.class);

		if (user.isLogged()) {
			String p4url = request.getParameter("p4service");
			if (p4url != null) {
				try {
					P4Service p4service = new P4Service(new URL(p4url), null);
					for (P4Service service : user.getP4Services()) {
						if (service.equals(p4service)) {
							user.setCurrentP4Service(service);
						}
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
		}
		Tools.servletInclude(this, request, response, "?_b=");
	}
 
Example 9
Project: NewsSpeakServer   File: Thumbelina.java View source code Vote up 6 votes
/**
 * Handles the history list events.
 * @param event The event describing the list activity.
 */
public void valueChanged (final ListSelectionEvent event)
{
    JList source;
    Object[] hrefs;
    Picture picture;
    URL url;
    Image image;
    Tracker tracker;

    source = (JList)event.getSource ();
    if (source == mHistory && !event.getValueIsAdjusting ())
    {
        hrefs = source.getSelectedValues ();
        for (int i = 0; i < hrefs.length; i++)
        {
            picture = mPicturePanel.find ("http://" + (String)hrefs[i]);
            if (null != picture)
                mPicturePanel.bringToTop (picture);
            else
                try
                {
                    url = new URL ("http://" + (String)hrefs[i]);
                    image = getToolkit ().createImage (url);
                    tracker = new Tracker (url);
                    image.getWidth (tracker);
                    System.out.println ("refetching " + hrefs[i]);
                }
                catch (MalformedURLException murle)
                {
                    murle.printStackTrace ();
                }
        }
    }
}
 
Example 10
Project: selenium-video-node   File: BasicWebDAVStore.java View source code Vote up 6 votes
@Override
public Map<String, Object> additionalInformation() {
	Map<String, Object> info = new HashMap<String, Object>();
	try {
		info.put("url", request.getURI().toURL().toExternalForm());
	} catch (MalformedURLException e) {
		e.printStackTrace();
	}
	return info;
}
 
Example 11
Project: SimplePortables   File: CloakRender.java View source code Vote up 6 votes
@Override
public void run()
{
	try
	{
		Image cape = new ImageIcon(new URL(cloakURL)).getImage();
		BufferedImage bo = new BufferedImage(cape.getWidth(null), cape.getHeight(null), BufferedImage.TYPE_INT_ARGB);
		bo.getGraphics().drawImage(cape, 0, 0, null);
		abstractClientPlayer.getTextureCape().setBufferedImage(bo);
	} catch (MalformedURLException e)
	{
		e.printStackTrace();
	}
}
 
Example 12
Project: 3380-GAS-App   File: StationRequest.java View source code Vote up 6 votes
private static String getPlaceReference(String address, String lat, String lng)
{
    StringBuilder url = new StringBuilder(placeSearch);
    url.append("location=" + lat + "," + lng);
    url.append("&radius=5&sensor=false&key=" + placesKey);
    
    try 
    {
        URL requestUrl = new URL(url.toString());
        JSONObject placeInfo = getJson(requestUrl);
        JSONArray places = (JSONArray) placeInfo.get("results");
        if (places.size() == 0) return null;
        Iterator i = places.iterator();
        while(i.hasNext())
        {
            JSONObject place = (JSONObject) i.next();
            String formattedAddress = (String) place.get("formatted_address");
            if(formattedAddress.equals(address))
            {
                System.out.println("found a ref");
                return (String) place.get("reference");
            }
        }
        return null;
    } 
    catch (MalformedURLException e1) 
    {
        e1.printStackTrace();
    }
    catch (NullPointerException e)
    {
        e.printStackTrace();
    }
    return null;
}
 
Example 13
Project: voms-api-java   File: RESTServiceURLBuilder.java View source code Vote up 6 votes
public URL build(VOMSServerInfo endpoint, VOMSACRequest request) {

    URL url = null;

    try {

      url = new URL("https", endpoint.getURL().getHost(), endpoint.getURL()
        .getPort(), buildPath(endpoint, request));

    } catch (MalformedURLException e) {

      throw new VOMSError("Malformed URI: " + e.getMessage());
    }

    return url;
  }
 
Example 14
Project: eclipse-commons   File: AbstractIOTest.java View source code Vote up 6 votes
public URL getHttpUrl()
{
    try
    {
        return provider.getUrl();
    }
    catch ( MalformedURLException e )
    {
        throw new IllegalStateException( "ServerProvider was not correctly initialized: " + e.getMessage(), e );
    }
}
 
Example 15
Project: mycila   File: ExtendedAssert.java View source code Vote up 6 votes
public static String asString(File file, String encoding) {
    try {
        return asString(file.toURI().toURL(), encoding);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 16
Project: BBAW_CMS   File: EdocUriParser.java View source code Vote up 6 votes
/**
 * Return the [email protected] URL} to the associated index.html file. This contains the
 * metadata.
 * 
 * @param docURI
 *          the (input) uri (the uri to be parsed) of the eDoc.
 * @return the [email protected] URL} to the index.html file
 * @throws ApplicationException
 *           if the resulting URL is invalid.
 */
public static URL getIndexURI(final URL docURI) throws ApplicationException {
  int lastSlash = docURI.toString().lastIndexOf("pdf/");
  String newString = docURI.toString().substring(0, lastSlash) + "index.html";

  URL indexURI;
  try {
    indexURI = new URL(newString);
    return indexURI;
  } catch (MalformedURLException e) {
    throw new ApplicationException(e.getMessage());
  }
}
 
Example 17
Project: elpaaso-core   File: Route.java View source code Vote up 6 votes
public URL getFullHttpAccessUrl() {
	try {
		return new URL("http://" + routeUri.getValue() + ":" + HTTP_PORT + (contextRoot.equals("/") ? "" : contextRoot));
	} catch (MalformedURLException e) {
		throw new TechnicalException("Bad URL: " + e.getMessage(), e);
	}
}
 
Example 18
Project: jadira   File: JdkBaseClasspathUrlLocator.java View source code Vote up 6 votes
@Override
public List<URL> locate() {

       List<URL> classpaths = new ArrayList<URL>();

       String[] endorsedDirs = System.getProperty("java.endorsed.dirs").split(System.getProperty("path.separator"));
       processClasspathDefinition(classpaths, endorsedDirs);

       try {
           // Can't resolve using sun.boot.class.path - vendor specific
           if (includeRtJar) {
               URL javaClasspath = new java.io.File(System.getProperty("java.home") + System.getProperty("file.separator") + "lib" + System.getProperty("file.separator") + "rt.jar").toURI().toURL();
               classpaths.add(javaClasspath);
           }
       } catch (MalformedURLException e) {
           throw new ClasspathAccessException("Problem constructing Java classpath: " + e.getMessage(), e);
       }

       String[] extensionDirs = System.getProperty("java.ext.dirs").split(System.getProperty("path.separator"));
       processClasspathDefinition(classpaths, extensionDirs);


       return classpaths;
   }
 
Example 19
Project: TestingStaff   File: LogoutRequestListener.java View source code Vote up 6 votes
@Override
  public void onMalformedURLException(MalformedURLException e,
                                      final Object state) {
final String message = e.getMessage();

mHandler.post(new Runnable() {
	public void run() {
		if(snsService != null)
              {
              	snsService.loggoutStatus(context, false, message);
              }
	}
});
  }
 
Example 20
Project: aws-sdk-android   File: ServiceUtils.java View source code Vote up 6 votes
/**
 * Converts the specified request object into a URL, containing all the
 * specified parameters, the specified request endpoint, etc.
 *
 * @param request The request to convert into a URL.
 * @param removeLeadingSlashInResourcePath Whether the leading slash in
 *            resource-path should be removed before appending to the
 *            endpoint.
 * @return A new URL representing the specified request.
 * @throws AmazonClientException If the request cannot be converted to a
 *             well formed URL.
 */
public static URL convertRequestToUrl(Request<?> request,
        boolean removeLeadingSlashInResourcePath) {

    String resourcePath = HttpUtils.urlEncode(request.getResourcePath(), true);

    // Removed the padding "/" that was already added into the request's
    // resource path.
    if (removeLeadingSlashInResourcePath
            && resourcePath.startsWith("/")) {
        resourcePath = resourcePath.substring(1);
    }

    // Some http client libraries (e.g. Apache HttpClient) cannot handle
    // consecutive "/"s between URL authority and path components.
    // So we escape "////..." into "/%2F%2F%2F...", in the same way as how
    // we treat consecutive "/"s in AmazonS3Client#presignRequest(...)
    String urlPath = "/" + resourcePath;
    urlPath = urlPath.replaceAll("(?<=/)/", "%2F");
    String urlString = request.getEndpoint() + urlPath;

    boolean firstParam = true;
    for (String param : request.getParameters().keySet()) {
        if (firstParam) {
            urlString += "?";
            firstParam = false;
        } else {
            urlString += "&";
        }

        String value = request.getParameters().get(param);
        urlString += param + "=" + HttpUtils.urlEncode(value, false);
    }

    try {
        return new URL(urlString);
    } catch (MalformedURLException e) {
        throw new AmazonClientException(
                "Unable to convert request to well formed URL: " + e.getMessage(), e);
    }
}
 
Example 21
Project: SimpleNews   File: Beans.java View source code Vote up 6 votes
private static URL safeURL(String urlString) throws ClassNotFoundException {
	try {
		return new URL(urlString);
	} catch (MalformedURLException exception) {
		throw new ClassNotFoundException(exception.getMessage());
	}
}
 
Example 22
Project: crawler-commons   File: SimpleHttpFetcher.java View source code Vote up 6 votes
@Override
public FetchedResult get(String url, Payload payload) throws BaseFetchException {
    try {
        URL realUrl = new URL(url);
        String protocol = realUrl.getProtocol();
        if (!protocol.equals("http") && !protocol.equals("https")) {
            throw new BadProtocolFetchException(url);
        }
    } catch (MalformedURLException e) {
        throw new UrlFetchException(url, e.getMessage());
    }

    return request(new HttpGet(), url, payload);
}
 
Example 23
Project: java-client-library   File: RProjectExecutionImpl.java View source code Vote up 6 votes
public URL downloadResults()
throws RClientException, RSecurityException {

String urlPath = this.liveContext.serverurl + REndpoints.RPROJECTEXECUTERESULTDOWNLOAD;
String urlQuery = urlPath + "/" + this.project.id + "/" + this.about.id + ";jsessionid=" + this.liveContext.httpcookie;
log.debug("downloadResults: url=" + urlQuery);
URL downloadURL = null;
try {
    downloadURL = new URL(urlQuery);
} catch(MalformedURLException mex) {
    throw new RClientException("Download project execution results url malformed, ex=" + mex.getMessage());
}
return downloadURL;
   }
 
Example 24
Project: HDP-2.2-Patched   File: TestJettyHelper.java View source code Vote up 6 votes
/**
 * Returns the base URL (SCHEMA://HOST:PORT) of the test Jetty server
 * (see [email protected] #getJettyServer()}) once started.
 *
 * @return the base URL (SCHEMA://HOST:PORT) of the test Jetty server.
 */
public static URL getJettyURL() {
  Server server = TEST_SERVLET_TL.get();
  if (server == null) {
    throw new IllegalStateException("This test does not use @TestJetty");
  }
  try {
    return new URL("http://" + server.getConnectors()[0].getHost() + ":" + server.getConnectors()[0].getPort());
  } catch (MalformedURLException ex) {
    throw new RuntimeException("It should never happen, " + ex.getMessage(), ex);
  }
}
 
Example 25
Project: castor   File: BindingLoader.java View source code Vote up 6 votes
/**
 * Sets the base URL for the binding and related files. If the base URL is
 * known, files can be included using relative names. Any URL can be passed,
 * if the URL can serve as a base URL it will be used.
 *
 * @param url
 *            The base URL
 */
public void setBaseURL(final String url) {
    try {
        _resolver.setBaseURL(new URL(url));
    } catch (MalformedURLException except) {
        throw new IllegalArgumentException(except.getMessage());
    }
}
 
Example 26
Project: yayqueryPad   File: JavaPolicySecurity.java View source code Vote up 6 votes
private URL getUrlObj(String url)
{
    URL urlObj;
    try {
        urlObj = new URL(url);
    } catch (MalformedURLException ex) {
        // Assume as Main.processFileSecure it is file, need to build its
        // URL
        String curDir = System.getProperty("user.dir");
        curDir = curDir.replace('\\', '/');
        if (!curDir.endsWith("/")) {
            curDir = curDir+'/';
        }
        try {
            URL curDirURL = new URL("file:"+curDir);
            urlObj = new URL(curDirURL, url);
        } catch (MalformedURLException ex2) {
            throw new RuntimeException
                ("Can not construct file URL for '"+url+"':"
                 +ex2.getMessage());
        }
    }
    return urlObj;
}
 
Example 27
Project: teiid-designer   File: XmlUrlProfileDetailsWizardPage.java View source code Vote up 6 votes
public String isValidValue( String value ) {
    try {
        new URL(value.toString());
    } catch (MalformedURLException e) {
        return e.getMessage();
    }
    return null;
}
 
Example 28
Project: sql-layer   File: ProtobufReader.java View source code Vote up 6 votes
private void loadSQLJJars(String schema, Collection<AISProtobuf.SQLJJar> pbJars) {
    for (AISProtobuf.SQLJJar pbJar : pbJars) {
        hasRequiredFields(pbJar);
        try {
            SQLJJar sqljJar = SQLJJar.create(destAIS, 
                                             schema,
                                             pbJar.getJarName(),
                                             new URL(pbJar.getUrl()));
            if (pbJar.hasVersion()) {
                sqljJar.setVersion(pbJar.getVersion());
            }
        }
        catch (MalformedURLException ex) {
            throw new ProtobufReadException(
                   pbJar.getDescriptorForType().getFullName(),
                   ex.toString()
            );
        }
    }        
}
 
Example 29
Project: open-mika   File: Handler.java View source code Vote up 6 votes
/**
 * 
 * @param url
 *            URL the context URL
 * @param spec
 *            java.lang.String the spec string
 * @param start
 *            int the location to start parsing from
 * @param limit
 *            int the location where parsing ends
 */
@Override
protected void parseURL(URL url, String spec, int start, int limit) {
    String file = url.getFile();
    if (file == null) {
        file = ""; //$NON-NLS-1$
    }
    if (limit > start) {
        spec = spec.substring(start, limit);
    } else {
        spec = ""; //$NON-NLS-1$
    }
    if (spec.indexOf("!/") == -1 && (file.indexOf("!/") == -1)) { //$NON-NLS-1$ //$NON-NLS-2$
        throw new NullPointerException(Msg.getString("K01b6")); //$NON-NLS-1$
    }
    if (file.equals("")) {
        file = spec;
    } else if (spec.charAt(0) == '/') {
        file = file.substring(0, file.indexOf('!') + 1) + spec;
    } else {
        int idx = file.indexOf('!');
        String tmpFile = file.substring(idx + 1, file.lastIndexOf('/') + 1)
                + spec;
        tmpFile = URLUtil.canonicalizePath(tmpFile);
        file = file.substring(0, idx + 1) + tmpFile;
    }
    try {
        // check that the embedded url is valid
        new URL(file);
    } catch (MalformedURLException e) {
        throw new NullPointerException(e.toString());
    }
    setURL(url, "jar", "", -1, null, null, file, null, null); //$NON-NLS-1$//$NON-NLS-2$
}
 
Example 30
Project: jdkernel-updater   File: ChangelogTask.java View source code Vote up 6 votes
@Override
  public void onPreExecute() {
  	try {
	changelogUrl = new URL(new Preferences(mCtx).getChangelogURL());
} catch (MalformedURLException e) {
	Log.e(TAG, "Exception on parsing URL", e);
	mException = e.toString();
}
Resources res = mCtx.getResources();
d = ProgressDialog.show(mCtx, res.getString(R.string.changelog_progress_title), res.getString(R.string.changelog_progress_body), true);
  }
 
Example 31
Project: spice   File: URLTypeConverter.java View source code Vote up 6 votes
public Object convert( final String value, final TypeLiteral<?> toType )
{
    try
    {
        return new URL( value );
    }
    catch ( final MalformedURLException e )
    {
        throw new ProvisionException( e.toString() );
    }
}
 
Example 32
Project: warmupdater   File: ChangelogTask.java View source code Vote up 6 votes
@Override
  public void onPreExecute() {
  	try {
	changelogUrl = new URL(new Preferences(mCtx).getChangelogURL());
} catch (MalformedURLException e) {
	Log.e(TAG, "Exception on parsing URL", e);
	mException = e.toString();
}
Resources res = mCtx.getResources();
d = ProgressDialog.show(mCtx, res.getString(R.string.changelog_progress_title), res.getString(R.string.changelog_progress_body), true);
  }
 
Example 33
Project: ecgine   File: UIUtils.java View source code Vote up 6 votes
public static String getWebSocketUrl(String customUrl) {
	if (customUrl == null || customUrl.isEmpty()) {
		return getWebSocketConnectionUrl(false);
	}
	URL url = null;
	try {
		url = new URL(customUrl);
	} catch (MalformedURLException e) {
		throw new RuntimeException(e.toString());
	}
	StringBuilder builder = new StringBuilder();
	String hostName = url.getHost();
	String protocol = url.getProtocol().equals("https") ? "wss" : "ws";
	String port = "10011";
	builder.append(protocol);
	builder.append("://" + hostName + ":");
	builder.append(port);
	return builder.toString();
}
 
Example 34
Project: android_platform_libcore   File: JarHandler.java View source code Vote up 6 votes
/**
 *
 * @param url
 *            URL the context URL
 * @param spec
 *            java.lang.String the spec string
 * @param start
 *            int the location to start parsing from
 * @param limit
 *            int the location where parsing ends
 */
@Override
protected void parseURL(URL url, String spec, int start, int limit) {
    String file = url.getFile();
    if (file == null) {
        file = "";
    }
    if (limit > start) {
        spec = spec.substring(start, limit);
    } else {
        spec = "";
    }
    if (spec.indexOf("!/") == -1 && (file.indexOf("!/") == -1)) {
        throw new NullPointerException("Cannot find \"!/\"");
    }
    if (file.isEmpty()) {
        file = spec;
    } else if (spec.charAt(0) == '/') {
        file = file.substring(0, file.indexOf('!') + 1) + spec;
    } else {
        int idx = file.indexOf('!');
        String tmpFile = file.substring(idx + 1, file.lastIndexOf('/') + 1) + spec;
        tmpFile = UrlUtils.canonicalizePath(tmpFile, true);
        file = file.substring(0, idx + 1) + tmpFile;
    }
    try {
        // check that the embedded url is valid
        new URL(file);
    } catch (MalformedURLException e) {
        throw new NullPointerException(e.toString());
    }
    setURL(url, "jar", "", -1, null, null, file, null, null);
}
 
Example 35
Project: xbnjava   File: ATDetectInternet.java View source code Vote up 6 votes
/**
   <p>Do it. Uh huh. Oh yeah.</p>
 */
public void execute() throws BuildException  {
   if(sUrl == null  ||  sUrl.length() == 0)  {
      throw  new BuildException("Parameter url ('" + sUrl + "') is null or empty.");
   }

   if(sProperty == null  ||  sProperty.length() == 0)  {
      throw  new BuildException("Parameter property ('" + sProperty + "') is null or empty.");
   }

   //Copied from xbn.util.Utility.appendWebPageSource

   try  {
      URL url = new URL(sUrl);
      InputStream isUNUSED = url.openStream();
      getProject().setProperty(sProperty, "true");
   }  catch(UnknownHostException uhx)  {
      System.out.println("INTERNET IS NOT AVAILABLE, or provided host is invalid. " + uhx.toString());
   }  catch(MalformedURLException mux)  {
      throw  new BuildException("Parameter url ('" + sUrl + "') is a malformed url. " + mux.toString() + ". (It does seem that we are connected to the internet, otherwise a uhx would have been thrown.)");
   }  catch(FileNotFoundException fnfx)  {
      throw  new BuildException("Parameter url ('" + sUrl + "') is invalid. " + fnfx.toString() + ". (It does seem that we are connected to the internet, otherwise a uhx would have been thrown.)");
   }  catch(IOException iox)  {
      System.out.println("INTERNET IS NOT AVAILABLE. " + iox.toString());
   }
}
 
Example 36
Project: android-libcore64   File: JarHandler.java View source code Vote up 6 votes
/**
 *
 * @param url
 *            URL the context URL
 * @param spec
 *            java.lang.String the spec string
 * @param start
 *            int the location to start parsing from
 * @param limit
 *            int the location where parsing ends
 */
@Override
protected void parseURL(URL url, String spec, int start, int limit) {
    String file = url.getFile();
    if (file == null) {
        file = "";
    }
    if (limit > start) {
        spec = spec.substring(start, limit);
    } else {
        spec = "";
    }
    if (spec.indexOf("!/") == -1 && (file.indexOf("!/") == -1)) {
        throw new NullPointerException("Cannot find \"!/\"");
    }
    if (file.isEmpty()) {
        file = spec;
    } else if (spec.charAt(0) == '/') {
        file = file.substring(0, file.indexOf('!') + 1) + spec;
    } else {
        int idx = file.indexOf('!');
        String tmpFile = file.substring(idx + 1, file.lastIndexOf('/') + 1) + spec;
        tmpFile = UrlUtils.canonicalizePath(tmpFile, true);
        file = file.substring(0, idx + 1) + tmpFile;
    }
    try {
        // check that the embedded url is valid
        new URL(file);
    } catch (MalformedURLException e) {
        throw new NullPointerException(e.toString());
    }
    setURL(url, "jar", "", -1, null, null, file, null, null);
}
 
Example 37
Project: BombusMod   File: Connection.java View source code Vote up 6 votes
public javax.microedition.io.Connection openConnection(String name, int mode, boolean timeouts) throws IOException {
	if (!isAllowNetworkConnection()) {
		throw new IOException("No network");
	}
	URL url;
	try {
		url = new URL(name);
	} catch (MalformedURLException ex) {
		throw new IOException(ex.toString());
	}
	cn = url.openConnection();
	cn.setDoOutput(true);
	// J2ME do not follow redirects. Test this url
	// http://www.microemu.org/test/r/
	if (cn instanceof HttpURLConnection) {
		((HttpURLConnection) cn).setInstanceFollowRedirects(false);
	}
	return this;
}
 
Example 38
Project: cm4mm-updater   File: ChangelogTask.java View source code Vote up 6 votes
@Override
  public void onPreExecute() {
  	try {
	changelogUrl = new URL(new Preferences(mCtx).getChangelogURL());
} catch (MalformedURLException e) {
	Log.e(TAG, "Exception on parsing URL", e);
	mException = e.toString();
}
Resources res = mCtx.getResources();
d = ProgressDialog.show(mCtx, res.getString(R.string.changelog_progress_title), res.getString(R.string.changelog_progress_body), true);
  }
 
Example 39
Project: dcache   File: DelegationShell.java View source code Vote up 6 votes
private void setEndpoint(URI uri) throws CommandException
{
    uri = checkSyntax(uri);
    String newPrompt = "[" + uri + "] $ ";
    uri = canonicalise(uri);

    checkProxyAge();

    try {
        _client = buildClient(uri.toURL());
        _prompt = newPrompt;
    } catch (MalformedURLException e) {
        throw new CommandException("Bad URI: " + e.toString());
    }
}
 
Example 40
Project: pljava   File: SPIConnection.java View source code Vote up 6 votes
static Object basicCoersion(Class cls, Object value)
throws SQLException
{
	if(value == null || cls.isInstance(value))
		return value;

	if(cls == String.class)
	{
		if(value instanceof Number
		|| value instanceof Boolean
		|| value instanceof Timestamp
		|| value instanceof Date
		|| value instanceof Time)
			return value.toString();
	}
	else if(cls == URL.class && value instanceof String)
	{
		try
		{
			return new URL((String)value);
		}
		catch(MalformedURLException e)
		{
			throw new SQLException(e.toString());
		}
	}
	throw new SQLException("Cannot derive a value of class " +
			cls.getName() + " from an object of class " + value.getClass().getName());
}
 
Example 41
Project: r2r   File: LoadingFunctionManager.java View source code Vote up 6 votes
public Function getFunctionByUri(String URI) {
	if(basicFunctions.containsFunctionByUri(URI))
		return basicFunctions.getFunctionByUri(URI);
	
	// Try to load function if not present in this manager
	if(!functions.containsKey(URI)) {
		if(ffLoader==null)
			throw new IllegalArgumentException("No function found with URI/ID: " + URI);
		else {
			try {
				FunctionFactory ff = ffLoader.getFunctionFactory(URI);
				if(ff!=null) {
					synchronized (functions) {
						functions.put(URI, ff);
					}
				}
				else 
					return null;// Could not load Function
			} catch(MalformedURLException e) {
				if(log.isDebugEnabled())
					log.debug("TransformationFunction <" + URI + "> could not be loaded: " + e.toString());
				if(Config.rethrowActivated())
					throw new R2RException("TransformationFunction <" + URI + "> could not be loaded: " + e.toString(), e);
				return null;
			}
		}
	}
	FunctionFactory factory = functions.get(URI);
	if (factory instanceof MultiFunctionFactory) {
		return ((MultiFunctionFactory) factory).getInstance(URI);
	}
	return functions.get(URI).getInstance();
}
 
Example 42
Project: ocr-tools   File: JackrabbitHotfolder.java View source code Vote up 6 votes
public void configureConnection(String serverUrl, String username, String password) {
	URL url;
	try {
		url = new URL(serverUrl);
	} catch (MalformedURLException e) {
		throw new IllegalStateException("no valid host given: "
				+ e.toString());
	}

	HostConfiguration hostConfig = new HostConfiguration();
	hostConfig.setHost(url.getHost(), url.getDefaultPort(),
			url.getProtocol());

	HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
	HttpConnectionManagerParams params = new HttpConnectionManagerParams();
	int maxHostConnections = 10;

	params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
	params.setStaleCheckingEnabled(true);
	params.setSoTimeout(10000);
	connectionManager.setParams(params);
	client = new HttpClient(connectionManager);
	if (username != null || password != null) {
		Credentials creds = new UsernamePasswordCredentials(username,
				password);
		client.getParams().setAuthenticationPreemptive(true);
		client.getState().setCredentials(AuthScope.ANY, creds);
	}
	client.setHostConfiguration(hostConfig);
}
 
Example 43
Project: SMUpdater   File: ChangelogTask.java View source code Vote up 6 votes
@Override
  public void onPreExecute() {
  	try {
	changelogUrl = new URL(new Preferences(mCtx).getChangelogURL());
} catch (MalformedURLException e) {
	Log.e(TAG, "Exception on parsing URL", e);
	mException = e.toString();
}
Resources res = mCtx.getResources();
d = ProgressDialog.show(mCtx, res.getString(R.string.changelog_progress_title), res.getString(R.string.changelog_progress_body), true);
  }
 
Example 44
Project: irond   File: RemoteSunXacml.java View source code Vote up 6 votes
public RemoteSunXacml(String param, boolean rawLog) throws ServerInitialException {

		try {
			mUrl = new URL(param);
		} catch (MalformedURLException e) {
			throw new ServerInitialException(e.toString());
		}

		mRawLog = rawLog;
		mCounter = new AtomicLong();
	}
 
Example 45
Project: gatein-portal   File: ServletContextImpl.java View source code Vote up 6 votes
public URL getResource(String path) throws MalformedURLException {
    if (path.length() == 0 || path.charAt(0) != '/') {
        throw new MalformedURLException(path + "does not start with /");
    }
    try {
        URI relative = new URI(path.substring(1));
        URI uri = base.toURI().resolve(relative);
        if (new File(uri).exists()) {
            return uri.toURL();
        } else {
            return null;
        }
    } catch (Exception e) {
        MalformedURLException ex = new MalformedURLException("Cannot build URL");
        ex.initCause(e);
        throw ex;
    }
}
 
Example 46
Project: Locast-Core-Android   File: NetworkClient.java View source code Vote up 6 votes
private void setBaseUrl(String baseUrlString) throws MalformedURLException {
    final URL baseUrl = new URL(baseUrlString);
    try {
        mBaseUrl = baseUrl.toURI();

        mAuthScope = new AuthScope(mBaseUrl.getHost(), mBaseUrl.getPort());

    } catch (final URISyntaxException e) {
        final MalformedURLException me = new MalformedURLException(e.getLocalizedMessage());
        me.initCause(e);
        throw me;
    }
}
 
Example 47
Project: org.ops4j.pax.url   File: Parser.java View source code Vote up 6 votes
/**
 * Creates an MalformedURLException with a message and a cause.
 *
 * @param message exception message
 * @param cause   exception cause
 *
 * @throws MalformedURLException the created MalformedURLException
 */
private static void throwAsMalformedURLException( final String message, final Exception cause )
    throws MalformedURLException
{
    final MalformedURLException exception = new MalformedURLException( message );
    exception.initCause( cause );
    throw exception;
}
 
Example 48
Project: spring-android   File: UrlResource.java View source code Vote up 6 votes
/**
 * Create a new UrlResource based on a URI specification.
 * <p>The given parts will automatically get encoded if necessary.
 * @param protocol the URL protocol to use (e.g. "jar" or "file" - without colon);
 * also known as "scheme"
 * @param location the location (e.g. the file path within that protocol);
 * also known as "scheme-specific part"
 * @param fragment the fragment within that location (e.g. anchor on an HTML page,
 * as following after a "#" separator)
 * @throws MalformedURLException if the given URL specification is not valid
 * @see java.net.URI#URI(String, String, String)
 */
public UrlResource(String protocol, String location, String fragment) throws MalformedURLException  {
	try {
		this.uri = new URI(protocol, location, fragment);
		this.url = this.uri.toURL();
		this.cleanedUrl = getCleanedUrl(this.url, this.uri.toString());
	}
	catch (URISyntaxException ex) {
		MalformedURLException exToThrow = new MalformedURLException(ex.getMessage());
		exToThrow.initCause(ex);
		throw exToThrow;
	}
}
 
Example 49
Project: org.ops4j.pax.swissbox   File: BndUtils.java View source code Vote up 6 votes
/**
 * Creates an MalformedURLException with a message and a cause.
 *
 * @param message exception message
 * @param cause   exception cause
 *
 * @throws MalformedURLException the created MalformedURLException
 */
private static void throwAsMalformedURLException( final String message, final Exception cause )
    throws MalformedURLException
{
    final MalformedURLException exception = new MalformedURLException( message );
    exception.initCause( cause );
    throw exception;
}
 
Example 50
Project: jaxws   File: JAXWSUtils.java View source code Vote up 6 votes
public static URL getEncodedURL(String urlStr) throws MalformedURLException {
    URL url = new URL(urlStr);
    String scheme = String.valueOf(url.getProtocol()).toLowerCase();
    if (scheme.equals("http") || scheme.equals("https")) {
        try {
            return new URL(url.toURI().toASCIIString());
        } catch (URISyntaxException e) {
            MalformedURLException malformedURLException = new MalformedURLException(e.getMessage());
            malformedURLException.initCause(e);
            throw malformedURLException;
        }
     }
     return url;
}
 
Example 51
Project: openjdk8-jdk   File: UrlUtil.java View source code Vote up 6 votes
/**
 * Decode a URI string (according to RFC 2396).
 *
 * Three-character sequences '%xy', where 'xy' is the two-digit
 * hexadecimal representation of the lower 8-bits of a character,
 * are decoded into the character itself.
 *
 * The string is subsequently converted using the specified encoding
 */
public static final String decode(String s, String enc)
        throws MalformedURLException, UnsupportedEncodingException {
    try {
        return URLDecoder.decode(s, enc);
    } catch (IllegalArgumentException iae) {
        MalformedURLException mue = new MalformedURLException("Invalid URI encoding: " + s);
        mue.initCause(iae);
        throw mue;
    }
}
 
Example 52
Project: skalli   File: URLUtils.java View source code Vote up 6 votes
/**
 * Converts a given string into a corresponding URL.
 * <p>
 * Encodes path and/or query parts of the given string according to
 * [email protected] URI#URI(String, String, String, int, String, String, String)}.
 * For example, blanks in the path are converted to <tt>%20</tt>.
 *
 * @param s  the string to convert to an URL.
 * @return  an URL, or <code>null</code> if the string is <code>null</code>, empty or whitespace.
 *
 * @throws MalformedURLException  if the given string is not a valid URL and cannot be
 * "sanitized" to yield a valid URL even after proper encoding of its parts.
 */
public static URL stringToURL(String s) throws MalformedURLException {
    if (StringUtils.isBlank(s)) {
        return null;
    }
    URI uri = null;
    try {
        uri = new URI(s);
    } catch (URISyntaxException e) {
        URL url = new URL(s);
        try {
            uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                            url.getPath(), url.getQuery(), url.getRef());
        } catch (URISyntaxException e1) {
            MalformedURLException e2 = new MalformedURLException(e1.getMessage());
            e2.initCause(e1);
            throw e2;
        }
    }
    return new URL(uri.toASCIIString());
}
 
Example 53
Project: jdk7u-jdk   File: UrlUtil.java View source code Vote up 6 votes
/**
 * Decode a URI string (according to RFC 2396).
 *
 * Three-character sequences '%xy', where 'xy' is the two-digit
 * hexadecimal representation of the lower 8-bits of a character,
 * are decoded into the character itself.
 *
 * The string is subsequently converted using the specified encoding
 */
public static final String decode(String s, String enc)
        throws MalformedURLException, UnsupportedEncodingException {
    try {
        return URLDecoder.decode(s, enc);
    } catch (IllegalArgumentException iae) {
        MalformedURLException mue = new MalformedURLException("Invalid URI encoding: " + s);
        mue.initCause(iae);
        throw mue;
    }
}
 
Example 54
Project: proarc   File: AlephXServer.java View source code Vote up 6 votes
static URI setQuery(URI u, String newQuery, boolean add) throws MalformedURLException {
    String query = u.getQuery();
    query = (query == null || !add) ? newQuery : query + '&' + newQuery;
    try {
        return  new URI(u.getScheme(), u.getUserInfo(), u.getHost(),
                u.getPort(), u.getPath(), query, u.getFragment());
    } catch (URISyntaxException ex) {
        MalformedURLException mex = new MalformedURLException(ex.getMessage());
        mex.initCause(ex);
        throw mex;
    }
}
 
Example 55
Project: xchain   File: RelativeUrlUtil.java View source code Vote up 6 votes
/**
 * Attempt to resolve the given spec URI against the given context URI.
 * 
 * @param context The context URI to resolve against.
 * @param spec The spec URI to resolve with.
 * 
 * @return The given spec URI resolved against the given context URI.
 * 
 * @see URI#relativize(URI)
 */
public static String resolve( String context, String spec )
  throws MalformedURLException
{
  try {
    return new URI(context).resolve(spec).toString();
  }
  catch( URISyntaxException use ) {
    MalformedURLException mue = new MalformedURLException("Could not create url for context '"+context+"' and spec '"+spec+"'.");
    mue.initCause(use);
    throw mue;
  }
}
 
Example 56
Project: mind-compiler   File: InputResourcesHelper.java View source code Vote up 6 votes
/**
 * Get the time-stamp corresponding to the given [email protected] URL}.
 * 
 * @param resource a [email protected] URL}
 * @return the time-stamp of the file designated by the given [email protected] URL}.
 * @throws MalformedURLException is the given [email protected] URL} is invalid.
 * @see InputResourceLocator#findResource(InputResource, java.util.Map)
 */
public static long getTimestamp(final URL resource)
    throws MalformedURLException {
  if ("file".equals(resource.getProtocol())) {
    try {
      return new File(resource.toURI()).lastModified();
    } catch (final URISyntaxException e) {
      final MalformedURLException mue = new MalformedURLException(
          "Invalid URL");
      mue.initCause(e);
      throw mue;
    }
  } else if ("jar".equals(resource.getProtocol())) {
    final String path = resource.getPath();
    final int i = path.indexOf('!');
    if (i == -1)
      throw new MalformedURLException("Invalid path of 'jar' URL: '" + path
          + "'");

    final URL jarFile = new URL(path.substring(0, i));
    return getTimestamp(jarFile);
  }
  return 0;
}
 
Example 57
Project: Locast-Android   File: NetworkClient.java View source code Vote up 6 votes
private void setBaseUrl(String baseUrlString) throws MalformedURLException {
	final URL baseUrl = new URL(baseUrlString);
	try {
		mBaseUrl = baseUrl.toURI();

		mAuthScope = new AuthScope(mBaseUrl.getHost(), mBaseUrl.getPort());

	} catch (final URISyntaxException e) {
		final MalformedURLException me = new MalformedURLException(e.getLocalizedMessage());
		me.initCause(e);
		throw me;
	}
}
 
Example 58
Project: richfaces   File: AbstractBaseResource.java View source code Vote up 6 votes
@Override
public URL getURL() {
    try {
        return new URL(URL_PROTOCOL, null, -1, getResourceName(), new MyURLStreamHandler());
    } catch (MalformedURLException e) {
        throw new FacesException(e.getLocalizedMessage(), e);
    }
}
 
Example 59
Project: shrinkwrap   File: UrlAsset.java View source code Vote up 6 votes
/**
 * Create a new resource with a <code>URL</code> source.
 *
 * @param url
 *            A valid URL
 * @throws IllegalArgumentException
 *             <Code>URL</code> can not be null
 */
public UrlAsset(final URL url) {
    // Precondition check
    if (url == null) {
        throw new IllegalArgumentException("URL must be specified");
    }
    // create a defensible copy
    try {
        this.url = new URL(url.toString());
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("URL is malformed " + e.getLocalizedMessage());
    }
}
 
Example 60
Project: substeps-eclipse-plugin   File: ImportTestRunSessionFromURLAction.java View source code Vote up 6 votes
@Override
public String isValid(final String newText) {
    if (newText.length() == 0)
        return null;
    try {
        @SuppressWarnings("unused")
        final URL url = new URL(newText);
        return null;
    } catch (final MalformedURLException e) {
        return SubstepsFeatureMessages.SubstepsFeatureTestRunnerViewPart_ImportTestRunSessionFromURLAction_invalid_url
                + e.getLocalizedMessage();
    }
}
 
Example 61
Project: acs-android-sdk   File: ACSClient.java View source code Vote up 6 votes
/**
   * Show dialog for authentication
   * @param context
   * @param action
   * @param parameters
   * @param listener
   * @throws ACSClientError 
   */
  private void dialog(Context context, String action, Bundle parameters, final DialogListener listener, boolean useSecure) throws ACSClientError {

  	StringBuffer endpoint = null;
if (useSecure) {
	endpoint = new StringBuffer(CCConstants.HTTPS_HEAD);
} else {
	endpoint = new StringBuffer(CCConstants.HTTP_HEAD);
}

if(this.authHost == null || this.authHost.length() == 0) {
	listener.onACSClientError(new ACSClientError("Authorization Server isn't set."));
	return;
}
  	endpoint.append(this.authHost);
  	parameters.putString("oauth_consumer_key", this.oauthKey);
      parameters.putString("client_id", this.oauthKey);
      parameters.putString("redirect_uri", REDIRECT_URI);

      if(ACTION_LOGIN.equals(action)) {
   	endpoint.append("/oauth/authorize");
       parameters.putString("response_type", "token");
} else if(ACTION_SIGNUP.equals(action)) {
	endpoint.append("/users/sign_up");
} else {
	throw new ACSClientError("Action not supported: " + action);
}

      if (isSessionValid()) {
          parameters.putString(ACCESS_TOKEN, getAccessToken());
      }
      endpoint.append("?");
      endpoint.append(Util.encodeUrl(parameters));
      
try {
	URI reqUri = new URL(endpoint.toString()).toURI();
} catch (MalformedURLException e1) {
	throw new ACSClientError("Incorrect Auth Host: " + e1.getLocalizedMessage());
} catch (URISyntaxException e2) {
	throw new ACSClientError("Incorrect Auth Host: " + e2.getLocalizedMessage());
}
      
      if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
          Util.showAlert(context, "Error", "Application requires permission to access the Internet");
      } else {
          new ACSClientDialog(context, endpoint.toString(), listener, this.dlgCustomizer).show();
      }
  }
 
Example 62
Project: turmeric-eclipse   File: WSDLUtil.java View source code Vote up 6 votes
/**
 * Validate url.
 *
 * @param url the url
 * @return the string
 */
public static String validateURL(final String url) {
	if (StringUtils.isBlank(url))
		return "url is blank.";
	try {
		new URL(StringEscapeUtils.escapeHtml(url));
	} catch (final MalformedURLException e) {
		return e.getLocalizedMessage();
	}
	return "";
}
 
Example 63
Project: geofence   File: WorkspacesManagerServiceImpl.java View source code Vote up 6 votes
public PagingLoadResult<WorkspaceModel> getWorkspaces(int offset, int limit, String remoteURL,
    GSInstanceModel gsInstance) throws ApplicationException
{

    List<WorkspaceModel> workspacesListDTO = new ArrayList<WorkspaceModel>();
    workspacesListDTO.add(new WorkspaceModel("*"));

    if ((remoteURL != null) && !remoteURL.equals("*") && !remoteURL.contains("?"))
    {
        try
        {
            GeoServerRESTReader gsreader = new GeoServerRESTReader(remoteURL, gsInstance.getUsername(), gsInstance.getPassword());

            RESTWorkspaceList workspaces = gsreader.getWorkspaces();
            if ((workspaces != null) && !workspaces.isEmpty())
            {
                Iterator<RESTShortWorkspace> wkIT = workspaces.iterator();
                while (wkIT.hasNext())
                {
                    RESTShortWorkspace workspace = wkIT.next();

                    workspacesListDTO.add(new WorkspaceModel(workspace.getName()));
                }
            }
        }
        catch (MalformedURLException e)
        {
            logger.error(e.getLocalizedMessage(), e);
            throw new ApplicationException(e.getLocalizedMessage(), e);
        }
    }

    return new RpcPageLoadResult<WorkspaceModel>(workspacesListDTO, 0, workspacesListDTO.size());
}
 
Example 64
Project: crux   File: AbstractURLResourceHandler.java View source code Vote up 6 votes
/**
 * 
 */
public URL getChildResource(URL url, String path)
{
	checkProtocol(url);
	
	try
	{
		String urlPath = url.toString();
		if (!urlPath.endsWith("/"))
		{
			urlPath += "/";
		}

		return new URL(urlPath+path);
	}
	catch (MalformedURLException e)
	{
		throw new URLResourceException(e.getLocalizedMessage(), e); 
	}
}
 
Example 65
Project: eclipse.jdt.ui   File: TestRunnerViewPart.java View source code Vote up 6 votes
@Override
public String isValid(String newText) {
	if (newText.length() == 0)
		return null;
	try {
		@SuppressWarnings("unused")
		URL url= new URL(newText);
		return null;
	} catch (MalformedURLException e) {
		return JUnitMessages.TestRunnerViewPart_ImportTestRunSessionFromURLAction_invalid_url + e.getLocalizedMessage();
	}
}
 
Example 66
Project: aipo   File: JetspeedWebPageService.java View source code Vote up 5 votes
/**
 * Maps a full URL path to a resource to a base path
 *   given: http://localhost:8080/jetspeed/search/index.html
 *   returns: http://localhost:8080/jetspeed/
 *
 * @param url the full URL of the resource.
 * @return the base host application string
 */
public String getTargetBase(String url) throws ServletException
{
    try
    {
        URL u = new URL(url);
        StringBuffer base = new StringBuffer();
        String protocol = u.getProtocol();
        base.append(protocol);
        base.append( "://");
        int port = u.getPort();
        base.append(u.getHost());  
        if ( (port > 0) &&
             ((protocol.equals("http") && port != 80) ||
              (protocol.equals("https") && port != 443)
             )
           )
        {
            base.append(":");
            base.append(port);
        }

        // we need to separate the filename from the resource, since
        // URL.getPath() and .getFile() return the same string
        String path = u.getFile();

        if (null != path)
        {

            int dot = path.lastIndexOf('.');
            int slash = path.lastIndexOf('/');
            if (dot > slash && slash != -1)
            { // its a file
                path = path.substring(0, slash);
            }
            // 

            base.append(path);

            if ('/' != base.charAt(base.length()-1))
                base.append('/');
        } else
            base.append("/");

        return base.toString();
    } catch (MalformedURLException e)
    {
        throw new ServletException(e.toString());
    }
}
 
Example 67
Project: geotoolkit   File: NetcdfImageReader.java View source code Vote up 5 votes
/**
 * Adds the aggregated files to the given list. This method invokes itself recursively
 * if an aggregation is a outer aggregation containing inner elements.
 *
 * @param  dataset  The dataset from which to get the aggregation.
 * @param  variable The name of the variable for which to get aggregated elements.
 * @param  addTo    The list in which to add the URI, or [email protected] null} if not yet created.
 * @return The [email protected] addTo} list, or a new list if [email protected] addTo}¬†was null and new elements
 *         were found.
 * @throws IOException If an error occurred while building the list of files.
 */
private List<URI> getAggregatedFiles(NetcdfDataset dataset, final String variable,
        List<URI> addTo) throws IOException
{
    final Aggregation aggregation = dataset.getAggregation();
    if (aggregation != null) {
        final List<Aggregation.Dataset> components = aggregation.getDatasets();
        if (components != null) {
            if (addTo == null) {
                addTo = new ArrayList<>(components.size());
            }
            for (final Aggregation.Dataset component : components) {
                if (abortRequested()) {
                    throw new IIOException(errors().getString(Errors.Keys.CanceledOperation));
                }
                if (component != null) {
                    /*
                     * We will process the aggregated file only if it contains the variable
                     * we are looking for.
                     */
                    final NetcdfFile componentFile = component.acquireFile(this);
                    if (componentFile.findVariable(variable) != null) {
                        final String location = component.getLocation();
                        if (location == null) {
                            /*
                             * If the component does not contain a link to a file, it may be an
                             * outer aggregation which contain inner aggregations.  Explore the
                             * content recursively.
                             */
                            if (componentFile instanceof NetcdfDataset) {
                                addTo = getAggregatedFiles((NetcdfDataset) componentFile, variable, addTo);
                            }
                        } else {
                            /*
                             * Get the URI, wrapping exception in a MalformedURLException since
                             * in order to get a subclass of IOException. We give the location
                             * as the message a let the more detailled explanation in the cause.
                             * We do that because MalformedURLException does not have an getInput()
                             * method (at the opposite of URISyntaxException).
                             */
                            final URI url;
                            try {
                                url = new URI(location);
                            } catch (URISyntaxException c) {
                                MalformedURLException e = new MalformedURLException(location);
                                e.initCause(c);
                                throw e;
                            }
                            addTo.add(url);
                        }
                    }
                    componentFile.close();
                }
            }
        }
    }
    return addTo;
}
 
Example 68
Project: pcgen-deprecated   File: LstFileLoader.java View source code Vote up 5 votes
/**
 * This method reads the given URL and stores its contents in the provided
 * data buffer, returning a URL to the specified file for use in log/error
 * messages by its caller.
 *
 * @param uri        String path of the URL to read -- MUST be a URL path,
 *                   not a file!
 * @return URL pointing to the actual file read, for use in debug/log
 *         messages
 * @throws PersistenceLayerException 
 */
public static StringBuilder readFromURI(URI uri) throws PersistenceLayerException
{
	if (uri == null)
	{
		// We have a problem!
		throw new PersistenceLayerException(
			"LstFileLoader.readFromURI() received a null uri parameter!");
	}
	
	URL url;
	try {
		url = uri.toURL();
	} catch (MalformedURLException e) {
		throw new PersistenceLayerException(
				"LstFileLoader.readFromURI() could not convert parameter to a URL: "
						+ e.getLocalizedMessage());
	}
	InputStream inputStream = null;

	StringBuilder dataBuffer = null;
	try
	{
		//only load local urls, unless loading of URLs is allowed
		if (!CoreUtility.isNetURL(url) || SettingsHandler.isLoadURLs())
		{
			// try to make a buffer of sufficient size in one go to save on GC
			int size = 2048;
			if ("file".equals(url.getProtocol())) 
			{
				long fileSize = new File(url.getPath()).length();
				if (fileSize > 0)
				{
					// this is an overestimate if the LST has wide 
					// characters, but it's accurate for ASCII
					size = (int) fileSize; 
				}
			}
			dataBuffer = new StringBuilder(size);

			// Get the URL and open the stream
			inputStream = url.openStream();

			// Read from the stream
			final InputStreamReader ir =
					new InputStreamReader(inputStream, "UTF-8"); //$NON-NLS-1$

			// Buffer the stream content
			final char[] b = new char[512];
			int n;

			n = ir.read(b, 0, 1);
			/*
			 * Take out the optional BOM: This is a pre-Java 1.6 workaround
			 * for Sun B-U-G 4508058, see:
			 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
			 */
			if (n == 1 && b[0] != '\uFEFF')
			{
				dataBuffer.append(b, 0, 1);
			}
			while ((n = ir.read(b)) > 0)
			{
				dataBuffer.append(b, 0, n);
			}
		}
		else
		{
			// Just to protect people from using web
			// sources without their knowledge,
			// we added a preference.
			ShowMessageDelegate
				.showMessageDialog(
					"Preferences are currently set to NOT allow\nloading of "
						+ "sources from web links. \n" + url
						+ " is a web link", Constants.APPLICATION_NAME,
					MessageType.ERROR);
			// aURL = null; //currently unnecessary reassignment 
		}
	}
	catch (IOException ioe)
	{
		// Don't throw an exception here because a simple
		// file not found will prevent ANY other files from
		// being loaded/processed -- NOT what we want
		Logging.errorPrint("ERROR:" + url + "\n" + "Exception type:"
			+ ioe.getClass().getName() + "\n" + "Message:"
			+ ioe.getMessage());
	}
	finally
	{
		if (inputStream != null)
		{
			try
			{
				inputStream.close();
			}
			catch (IOException e2)
			{
				Logging.errorPrint(
					"Can't close inputStream in LstSystemLoader.initFile",
					e2);
			}
		}
	}
	return dataBuffer == null ? new StringBuilder() : dataBuffer;
}
 
Example 69
Project: pcgen   File: LstFileLoader.java View source code Vote up 5 votes
/**
 * This method reads the given URL and stores its contents in the provided
 * data buffer, returning a URL to the specified file for use in log/error
 * messages by its caller.
 *
 * @param uri        String path of the URL to read -- MUST be a URL path,
 *                   not a file!
 * @return URL pointing to the actual file read, for use in debug/log
 *         messages
 * @throws PersistenceLayerException 
 */
public static StringBuilder readFromURI(URI uri) throws PersistenceLayerException
{
	if (uri == null)
	{
		// We have a problem!
		throw new PersistenceLayerException(
			"LstFileLoader.readFromURI() received a null uri parameter!");
	}
	
	URL url;
	try {
		url = uri.toURL();
	} catch (MalformedURLException e) {
		throw new PersistenceLayerException(
				"LstFileLoader.readFromURI() could not convert parameter to a URL: "
						+ e.getLocalizedMessage());
	}
	InputStream inputStream = null;

	StringBuilder dataBuffer = null;
	try
	{
		//only load local urls, unless loading of URLs is allowed
		if (!CoreUtility.isNetURL(url) || SettingsHandler.isLoadURLs())
		{
			// try to make a buffer of sufficient size in one go to save on GC
			int size = 2048;
			if ("file".equals(url.getProtocol())) 
			{
				long fileSize = new File(url.getPath()).length();
				if (fileSize > 0)
				{
					// this is an overestimate if the LST has wide 
					// characters, but it's accurate for ASCII
					size = (int) fileSize; 
				}
			}
			dataBuffer = new StringBuilder(size);

			// Get the URL and open the stream
			inputStream = url.openStream();

			// Read from the stream
			final InputStreamReader ir =
					new InputStreamReader(inputStream, "UTF-8"); //$NON-NLS-1$

			// Buffer the stream content
			final char[] b = new char[512];
			int n;

			n = ir.read(b, 0, 1);
			/*
			 * Take out the optional BOM: This is a pre-Java 1.6 workaround
			 * for Sun B-U-G 4508058, see:
			 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
			 */
			if (n == 1 && b[0] != '\uFEFF')
			{
				dataBuffer.append(b, 0, 1);
			}
			while ((n = ir.read(b)) > 0)
			{
				dataBuffer.append(b, 0, n);
			}
		}
		else
		{
			// Just to protect people from using web
			// sources without their knowledge,
			// we added a preference.
			ShowMessageDelegate
				.showMessageDialog(
					"Preferences are currently set to NOT allow\nloading of "
						+ "sources from web links. \n" + url
						+ " is a web link", Constants.APPLICATION_NAME,
					MessageType.ERROR);
			// aURL = null; //currently unnecessary reassignment 
		}
	}
	catch (IOException ioe)
	{
		// Don't throw an exception here because a simple
		// file not found will prevent ANY other files from
		// being loaded/processed -- NOT what we want
		Logging.errorPrint("ERROR:" + url + "\n" + "Exception type:"
			+ ioe.getClass().getName() + "\n" + "Message:"
			+ ioe.getMessage());
	}
	finally
	{
		if (inputStream != null)
		{
			try
			{
				inputStream.close();
			}
			catch (IOException e2)
			{
				Logging.errorPrint(
					"Can't close inputStream in LstSystemLoader.initFile",
					e2);
			}
		}
	}
	return dataBuffer == null ? new StringBuilder() : dataBuffer;
}