Java Code Examples for java.net.MalformedURLException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project airlift, under directory /jmx-http-rpc/src/main/java/io/airlift/jmx/http/rpc/.

Source file: HttpJmxConnector.java

  34 
vote

public HttpJmxConnector(JMXServiceURL jmxServiceUrl,Map<String,?> environment) throws MalformedURLException {
  String[] credentials=(String[])environment.get(JMXConnector.CREDENTIALS);
  if (credentials != null) {
    this.credentials=new HttpMBeanServerCredentials(credentials[0],credentials[1]);
  }
 else {
    this.credentials=null;
  }
  String protocol=jmxServiceUrl.getProtocol();
  if (!"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) {
    throw new MalformedURLException(jmxServiceUrl.toString());
  }
  String urlPath=jmxServiceUrl.getURLPath();
  if (!urlPath.endsWith("/")) {
    urlPath+="/";
  }
  urlPath+="v1/jmx/mbeanServer/";
  int port=jmxServiceUrl.getPort();
  if (port == 0) {
    if ("http".equalsIgnoreCase(protocol)) {
      port=80;
    }
 else {
      port=433;
    }
  }
  try {
    this.baseUri=new URI(protocol,null,jmxServiceUrl.getHost(),port,urlPath,null,null);
  }
 catch (  URISyntaxException e) {
    throw new MalformedURLException(jmxServiceUrl.toString());
  }
  this.jmxServiceUrl=jmxServiceUrl;
}
 

Example 2

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  31 
vote

/** 
 * Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root. <p> This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file system, in a database, or in a <code>.war</code> file. <p> The servlet container must implement the URL handlers and <code>URLConnection</code> objects that are necessary to access the resource. <p> This method returns <code>null</code> if no resource is mapped to the pathname. <p> Some containers may allow writing to the URL returned by this method using the methods of the URL class. <p> The resource content is returned directly, so be aware that requesting a <code>.jsp</code> page returns the JSP source code. Use a <code>RequestDispatcher</code> instead to include results of an execution. <p> This method has a different purpose than <code>java.lang.Class.getResource</code>, which looks up resources based on a class loader. This method does not use class loaders.
 * @param path a <code>String</code> specifying the path to the resource
 * @return the resource located at the named path, or <code>null</code> if there is no resource at that path
 * @exception MalformedURLException if the pathname is not given in the correct form
 */
public URL getResource(String path) throws MalformedURLException {
  if (path == null || path.length() == 0 || path.charAt(0) != '/')   throw new MalformedURLException("Path " + path + " is not in acceptable form.");
  File resFile=new File(getRealPath(path));
  if (resFile.exists())   return new URL("file","localhost",resFile.getPath());
  return null;
}
 

Example 3

From project aether-core, under directory /aether-connector-asynchttpclient/src/test/java/org/eclipse/aether/connector/async/.

Source file: ProxyGetTest.java

  31 
vote

@Override public String url(){
  URL orig;
  try {
    orig=new URL(super.url());
    return new URL(orig.getProtocol(),"proxiedhost",orig.getPort(),"").toString();
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
    throw new IllegalStateException(e.getMessage(),e);
  }
}
 

Example 4

From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.

Source file: OcrInitAsyncTask.java

  31 
vote

/** 
 * Download a file from the site specified by DOWNLOAD_BASE, and gunzip to the given destination.
 * @param sourceFilenameBase Name of file to download, minus the required ".gz" extension
 * @param destinationFile Name of file to save the unzipped data to, including path
 * @return True if download and unzip are successful
 * @throws IOException
 */
private boolean downloadFile(String sourceFilenameBase,File destinationFile) throws IOException {
  try {
    return downloadGzippedFileHttp(new URL(CaptureActivity.DOWNLOAD_BASE + sourceFilenameBase + ".gz"),destinationFile);
  }
 catch (  MalformedURLException e) {
    throw new IllegalArgumentException("Bad URL string.");
  }
}
 

Example 5

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/config/.

Source file: JsonConfigLoader.java

  30 
vote

/** 
 * Load the configuration from a URL.  This understands any URL that the JVM has a protocol handler for, and also "classpath:" URLs. 
 * @return the configuration or null
 * @param urlString the URL for the config file
 * @throws URISyntaxException 
 * @throws MalformedURLException 
 */
public C loadConfigurationFromUrl(String urlString) throws ConfigurationException {
  InputStream is=null;
  try {
    URI uri=new URI(urlString);
    if (uri.getScheme().equals("classpath")) {
      String path=uri.getSchemeSpecificPart();
      LOG.debug("Loading configuration from classpath resource '" + path + "'");
      is=JsonConfigLoader.class.getClassLoader().getResourceAsStream(path);
      if (is == null) {
        throw new IllegalArgumentException("Cannot locate resource '" + path + "' on the classpath");
      }
    }
 else {
      LOG.debug("Loading configuration from url '" + urlString + "'");
      is=uri.toURL().openStream();
    }
    return readConfiguration(is);
  }
 catch (  URISyntaxException ex) {
    throw new IllegalArgumentException("Invalid urlString '" + urlString + "'",ex);
  }
catch (  MalformedURLException ex) {
    throw new IllegalArgumentException("Invalid urlString '" + urlString + "'",ex);
  }
catch (  IOException ex) {
    throw new ConfigurationException("Cannot open URL input stream",ex);
  }
 finally {
    closeQuietly(is);
  }
}
 

Example 6

From project advanced, under directory /management/src/main/java/org/neo4j/management/impl/.

Source file: HotspotManagementSupport.java

  30 
vote

private JMXServiceURL getUrlFrom(String url){
  if (url == null)   return null;
  JMXServiceURL jmxUrl;
  try {
    jmxUrl=new JMXServiceURL(url);
  }
 catch (  MalformedURLException e1) {
    return null;
  }
  String host=null;
  try {
    host=InetAddress.getLocalHost().getHostAddress();
  }
 catch (  UnknownHostException ok) {
  }
  if (host == null) {
    host=jmxUrl.getHost();
  }
  try {
    return new JMXServiceURL(jmxUrl.getProtocol(),host,jmxUrl.getPort(),jmxUrl.getURLPath());
  }
 catch (  MalformedURLException e) {
    return null;
  }
}
 

Example 7

From project android-rackspacecloud, under directory /main/java/net/elasticgrid/rackspace/cloudservers/.

Source file: XMLCloudServers.java

  30 
vote

protected <T>T makeRequestInt(HttpRequestBase request,Class<T> respType) throws CloudServersException {
  try {
    return makeRequest(request,respType);
  }
 catch (  RackspaceException e) {
    throw new CloudServersException(e);
  }
catch (  JiBXException e) {
    throw new CloudServersException("Problem parsing returned message.",e);
  }
catch (  MalformedURLException e) {
    throw new CloudServersException(e.getMessage(),e);
  }
catch (  IOException e) {
    throw new CloudServersException(e.getMessage(),e);
  }
catch (  HttpException e) {
    throw new CloudServersException(e.getMessage(),e);
  }
}
 

Example 8

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/facebook/extpack/com/facebook/android/.

Source file: AsyncFacebookRunner.java

  30 
vote

/** 
 * Invalidate the current user session by removing the access token in memory, clearing the browser cookies, and calling auth.expireSession through the API. The application will be notified when logout is complete via the callback interface. Note that this method is asynchronous and the callback will be invoked in a background thread; operations that affect the UI will need to be posted to the UI thread or an appropriate handler.
 * @param context The Android context in which the logout should be called: it should be the same context in which the login occurred in order to clear any stored cookies
 * @param listener Callback interface to notify the application when the request has completed.
 * @param state An arbitrary object used to identify the request when it returns to the callback. This has no effect on the request itself.
 */
public void logout(final Context context,final RequestListener listener,final Object state){
  new Thread(){
    @Override public void run(){
      try {
        String response=fb.logout(context);
        if (response.length() == 0 || response.equals("false")) {
          listener.onFacebookError(new FacebookError("auth.expireSession failed"),state);
          return;
        }
        listener.onComplete(response,state);
      }
 catch (      FileNotFoundException e) {
        listener.onFileNotFoundException(e,state);
      }
catch (      MalformedURLException e) {
        listener.onMalformedURLException(e,state);
      }
catch (      IOException e) {
        listener.onIOException(e,state);
      }
    }
  }
.start();
}
 

Example 9

From project android_7, under directory /src/org/immopoly/android/api/.

Source file: IS24ApiService.java

  30 
vote

/** 
 * Runs an IS2 search with the given lat,lon,r Returns at most 'max' Flats or null if there are less than 'min' flats.   
 * @param lat Latitude
 * @param lon Longitude
 * @param r Radius
 * @param min minimum nuber of flats
 * @param max maximum nuber of flats
 * @return Flats or null
 * @throws JSONException.MalformedURLException , NullPointerException 
 */
private Flats loadFlats(double lat,double lon,float r,int min,int max) throws JSONException, MalformedURLException {
  Log.d(Const.LOG_TAG,"IS24 search: Lat: " + lat + " Lon: "+ lon+ " R: "+ r+ " min: "+ min+ " max: "+ max);
  JSONObject json=loadPage(lat,lon,r,1);
  JSONObject resultList=json.getJSONObject("resultlist.resultlist");
  JSONObject pagingInfo=resultList.getJSONObject("paging");
  int numPages=pagingInfo.getInt("numberOfPages");
  int results=pagingInfo.getInt("numberOfHits");
  int pageSize=pagingInfo.getInt("pageSize");
  Log.d(Const.LOG_TAG,"IS24 search got first page, numPages: " + numPages + " results: "+ results+ " pageSize: "+ pageSize);
  if (results < min || numPages * pageSize < min || results <= 0)   return null;
  Flats flats=new Flats(max);
  flats.parse(json);
  int pages=max / pageSize;
  if (pages >= 0 && max % pageSize > 0)   pages++;
  if (pages > numPages)   pages=numPages;
  for (int i=2; i <= pages; i++) {
    json=loadPage(lat,lon,r,i);
    flats.parse(json);
    Log.d(Const.LOG_TAG,"IS24 search got page " + i + "/"+ pages+ " #flats: "+ flats.size());
  }
  if (flats.size() > max) {
    Flats lessFlats=new Flats(max);
    lessFlats.addAll(flats.subList(0,max));
    flats=lessFlats;
  }
  return flats;
}
 

Example 10

From project activejdbc, under directory /activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/.

Source file: ActiveJdbcInstrumentationPlugin.java

  29 
vote

private void instrument(String instrumentationDirectory) throws MalformedURLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  if (!new File(instrumentationDirectory).exists()) {
    getLog().info("Instrumentation: directory " + instrumentationDirectory + " does not exist, skipping");
    return;
  }
  ClassLoader realmLoader=getClass().getClassLoader();
  URL outDir=new File(instrumentationDirectory).toURL();
  Method addUrlMethod=realmLoader.getClass().getSuperclass().getDeclaredMethod("addURL",URL.class);
  addUrlMethod.setAccessible(true);
  addUrlMethod.invoke(realmLoader,outDir);
  Instrumentation instrumentation=new Instrumentation();
  instrumentation.setOutputDirectory(instrumentationDirectory);
  instrumentation.instrument();
}
 

Example 11

From project activemq-apollo, under directory /apollo-boot/src/main/java/org/apache/activemq/apollo/boot/.

Source file: Apollo.java

  29 
vote

static private void add(ArrayList<URL> urls,File file){
  try {
    urls.add(file.toURI().toURL());
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
}
 

Example 12

From project addis, under directory /application/src/test/java/org/drugis/addis/presentation/wizard/.

Source file: AddStudyWizardPresentationTest.java

  29 
vote

@Test public void testClearStudies() throws MalformedURLException, IOException {
  importStudy();
  d_wizardImported.resetStudy();
  assertEquals(Source.MANUAL,d_wizardImported.getSourceModel().getValue());
  assertEquals("",d_wizardImported.getTitleModel().getValue());
  assertEquals(null,d_wizardImported.getIndicationNoteModel().getValue());
  assertEquals(1,d_wizardImported.getEndpointSelectModel().getSlots().size());
  assertEquals(2,d_wizardImported.getArms().size());
}
 

Example 13

From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/http/.

Source file: KeywordUtils.java

  29 
vote

public static String getSearchEngineQueryString(HttpServletRequest request,String referrer){
  String queryString=null;
  String hostName=null;
  if (referrer != null) {
    URL refererURL;
    try {
      refererURL=new URL(referrer);
    }
 catch (    MalformedURLException e) {
      return null;
    }
    hostName=refererURL.getHost();
    queryString=refererURL.getQuery();
    if (Strings.isEmpty(queryString)) {
      return null;
    }
    Set<String> keys=seParams.keySet();
    for (    String se : keys) {
      if (hostName.toLowerCase().contains(se)) {
        queryString=getQueryStringParameter(queryString,seParams.get(se));
      }
    }
    return queryString;
  }
  return null;
}
 

Example 14

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/util/.

Source file: URL.java

  29 
vote

/** 
 * Create a URL object from the specified components.  Specifying a port number of -1 indicates that the URL should use the default port for that protocol.  Based on logic from JDK 1.3.1's <code>java.net.URL</code>.
 * @param protocol Name of the protocol to use
 * @param host Name of the host addressed by this protocol
 * @param port Port number, or -1 for the default port for this protocol
 * @param file Filename on the specified host
 * @exception MalformedURLException is never thrown, but present forcompatible APIs
 */
public URL(String protocol,String host,int port,String file) throws MalformedURLException {
  this.protocol=protocol;
  this.host=host;
  this.port=port;
  int hash=file.indexOf('#');
  this.file=hash < 0 ? file : file.substring(0,hash);
  this.ref=hash < 0 ? null : file.substring(hash + 1);
  int question=file.lastIndexOf('?');
  if (question >= 0) {
    query=file.substring(question + 1);
    path=file.substring(0,question);
  }
 else   path=file;
  if ((host != null) && (host.length() > 0))   authority=(port == -1) ? host : host + ":" + port;
}
 

Example 15

From project agraph-java-client, under directory /src/com/franz/agraph/http/.

Source file: AGHTTPClient.java

  29 
vote

/** 
 * Set the username and password for authentication with the remote server.
 * @param username the username
 * @param password the password
 */
public void setUsernameAndPassword(String username,String password){
  if (username != null && password != null) {
    logger.debug("Setting username '{}' and password for server at {}.",username,serverURL);
    try {
      URL server=new URL(serverURL);
      authScope=new AuthScope(server.getHost(),AuthScope.ANY_PORT);
      httpClient.getState().setCredentials(authScope,new UsernamePasswordCredentials(username,password));
      httpClient.getParams().setAuthenticationPreemptive(true);
    }
 catch (    MalformedURLException e) {
      logger.warn("Unable to set username and password for malformed URL " + serverURL,e);
    }
  }
 else {
    authScope=null;
    httpClient.getState().clearCredentials();
    httpClient.getParams().setAuthenticationPreemptive(false);
  }
}
 

Example 16

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/net/.

Source file: HttpClient.java

  29 
vote

/** 
 * Get a byte array version of the target URL.
 * @param url The URL to fetch.
 * @return The results of the URL, if possible, or null.
 * @throws IOException If the file could not be fetched.
 */
public static byte[] getBytes(final String url) throws IOException {
  try {
    final URL ur=new URL(url);
    URLConnection conn;
    conn=ur.openConnection();
    return StreamUtils.toByteArray(conn.getInputStream());
  }
 catch (  final MalformedURLException e) {
    return null;
  }
}
 

Example 17

From project akubra, under directory /akubra-www/src/main/java/org/akubraproject/www/.

Source file: WWWConnection.java

  29 
vote

/** 
 * Gets a WWWBlob instance for an id. Instances are cached so that instance equality is guaranteed for the same connection.
 * @param blobId the blob identifier
 * @param create whether to create new blob instances
 * @return the WWWBlob instance
 * @throws IOException if the connection is closed or on a failure to create a WWWBlob instance
 * @throws IllegalArgumentException if the blobId is null or not an absolute URL
 */
WWWBlob getWWWBlob(URI blobId,boolean create) throws IOException {
  if (blobs == null)   throw new IllegalStateException("Connection closed.");
  if (blobId == null)   throw new UnsupportedOperationException("Must supply a valid URL as the blob-id. " + "This store has no id generation capability.");
  WWWBlob blob=blobs.get(blobId);
  if ((blob == null) && create) {
    try {
      URL url=new URL(null,blobId.toString(),handlers.get(blobId.getScheme()));
      blob=new WWWBlob(url,this,streamManager);
    }
 catch (    MalformedURLException e) {
      throw new UnsupportedIdException(blobId," must be a valid URL",e);
    }
    blobs.put(blobId,blob);
  }
  return blob;
}
 

Example 18

From project AlarmApp-Android, under directory /src/org/alarmapp/web/http/.

Source file: HttpUtil.java

  29 
vote

public static String request(String url,HashMap<String,String> data,HashMap<String,String> headers) throws WebException {
  Ensure.notNull(url);
  try {
    URL uri=new URL(url);
    if (isNullOrEmpty(data))     return get(uri,headers);
 else     return post(uri,data,headers);
  }
 catch (  MalformedURLException e) {
    throw new WebException(URL_ERROR + url,e);
  }
}
 

Example 19

From project ALP, under directory /workspace/alp-selenium/src/main/java/com/lohika/alp/selenium/.

Source file: AlpWebDriverFactory.java

  29 
vote

/** 
 * Create WebDriver object wrapped with ALP logging that allow implements autologging
 * @param SeleniumUrl - represent target Selenium standalone server for WebDriver that will be created 
 * @param capabilities - DesiredCapabilities for WebDriver that will be created  
 * @return created WebDriver instance 
 * @throws MalformedURLException the malformed url exception
 */
public static WebDriver getDriver(String SeleniumUrl,DesiredCapabilities capabilities) throws MalformedURLException {
  Logger alpSeleniumLogger=Logger.getLogger("com.lohika.alp.selenium");
  if (alpSeleniumLogger.getLevel() == null)   alpSeleniumLogger.setLevel(Level.DEBUG);
  URL remoteAddress=new URL(SeleniumUrl);
  CommandExecutor commandExecutor=new HttpCommandExecutor(remoteAddress);
  WebDriver driver;
  String name=capabilities.getBrowserName();
  WebDriverConfigurator webDriverConfigurator=new WebDriverConfigurator(name);
  capabilities=webDriverConfigurator.configure(capabilities);
  driver=new RemoteWebDriverTakeScreenshotFix(commandExecutor,capabilities);
  LogElementsSeleniumFactory logObjectsFactory=new LogElementsSeleniumFactoryJAXB();
  LogElementsSeleniumFactory elementsFactory=new LogElementsSeleniumFactoryJAXB();
  WebDriverEventListener listener=new LoggingWebDriverListener(elementsFactory);
  driver=new EventFiringWebDriver(driver);
  ((EventFiringWebDriver)driver).register(listener);
  driver=new LoggingWebDriver(driver,name,logObjectsFactory);
  Logger seleniumLogger=Logger.getLogger("selenium-logging");
  if (seleniumLogger != null)   try {
    String levelStr=seleniumLogger.getLevel().toString();
    log.debug("java.util.logging.Level for selenium: " + levelStr);
    java.util.logging.Level level=java.util.logging.Level.parse(levelStr);
    RemoteWebDriverTakeScreenshotFix.setLogLevel(level);
  }
 catch (  IllegalArgumentException e) {
    log.warn("Unable turn off native selenium logging");
  }
catch (  NullPointerException e) {
    log.warn("Unable to get log level for native selenium logging");
  }
  return driver;
}
 

Example 20

From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/utility/.

Source file: ImageLoaderView.java

  29 
vote

public void setImageDrawable(final String imageUrl){
  mDrawable=null;
  mSpinner.setVisibility(View.VISIBLE);
  mImage.setVisibility(View.GONE);
  new Thread(){
    public void run(){
      try {
        mDrawable=getDrawableFromUrl(imageUrl);
        imageLoadedHandler.sendEmptyMessage(COMPLETE);
      }
 catch (      MalformedURLException e) {
        imageLoadedHandler.sendEmptyMessage(FAILED);
      }
catch (      IOException e) {
        imageLoadedHandler.sendEmptyMessage(FAILED);
      }
    }
  }
.start();
}
 

Example 21

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.

Source file: CacheInvalidator.java

  29 
vote

private URL getAbsoluteURL(String uri){
  URL absURL=null;
  try {
    absURL=new URL(uri);
  }
 catch (  MalformedURLException mue) {
  }
  return absURL;
}
 

Example 22

From project anadix, under directory /examples/anadix-sample/src/main/java/org/anadix/sample/.

Source file: App.java

  29 
vote

public static void main(String[] args){
  String[] filenames=new String[]{"google.com.html","idnes.cz.html","seznam.cz.html","redhat.com.html"};
  Anadix.setDefaultFormatter(XHTMLReportFormatter.class);
  try {
    Analyzer a=Anadix.newAnalyzer(new Section508());
    for (    String filename : filenames) {
      Report r=a.analyze(SourceFactory.newClassPathSource("/" + filename));
      Anadix.formatReport(r);
      System.out.println(r.report());
    }
    Report r=a.analyze(SourceFactory.newURLSource(new URL("http://section508.gov")));
    Anadix.formatReport(r);
    System.out.println(r.report());
  }
 catch (  InstantiationException e) {
    e.printStackTrace();
  }
catch (  MalformedURLException e) {
    e.printStackTrace();
  }
catch (  SourceException e) {
    e.printStackTrace();
  }
}
 

Example 23

From project android-client, under directory /xwiki-android-core/src/org/xwiki/android/rest/transformation/.

Source file: DocumentBuilder_XML.java

  29 
vote

@Override public DocumentBuilder withAttachment(Attachment attachment){
  org.xwiki.android.xmodel.entity.Attachment a=new org.xwiki.android.xmodel.entity.Attachment();
  a.setId(attachment.id);
  a.setName(attachment.name);
  a.setSize(attachment.size);
  a.setVersion(attachment.version);
  a.setPageId(attachment.pageId);
  a.setPageVersion(attachment.version);
  a.setMimeType(attachment.mimeType);
  a.setAuthor(attachment.author);
  a.setDate(XUtils.toDate(attachment.date));
  URL absUrl=null;
  URL relUrl=null;
  try {
    absUrl=new URL(attachment.xwikiAbsoluteUrl);
    relUrl=new URL(attachment.xwikiRelativeUrl);
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
  a.setXwikiAbsoluteUrl(absUrl);
  a.setXwikiRelativeUrl(relUrl);
  a.setEdited(false);
  a.setNew(false);
  d.setAttachment(a);
  return this;
}
 

Example 24

From project android-joedayz, under directory /Proyectos/AndroidTwitter/src/com/mycompany/android/.

Source file: TwitterApp.java

  29 
vote

private String getVerifier(String callbackUrl){
  String verifier="";
  try {
    callbackUrl=callbackUrl.replace("twitterapp","http");
    URL url=new URL(callbackUrl);
    String query=url.getQuery();
    String array[]=query.split("&");
    for (    String parameter : array) {
      String v[]=parameter.split("=");
      if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
        verifier=URLDecoder.decode(v[1]);
        break;
      }
    }
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
  return verifier;
}
 

Example 25

From project android-mapviewballoons, under directory /android-mapviewballoons-example/src/mapviewballoons/example/custom/.

Source file: CustomBalloonOverlayView.java

  29 
vote

@Override protected Bitmap doInBackground(String... arg0){
  Bitmap b=null;
  try {
    b=BitmapFactory.decodeStream((InputStream)new URL(arg0[0]).getContent());
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return b;
}
 

Example 26

From project android-tether, under directory /facebook/src/com/facebook/android/.

Source file: AsyncFacebookRunner.java

  29 
vote

/** 
 * Invalidate the current user session by removing the access token in memory, clearing the browser cookies, and calling auth.expireSession through the API. The application will be notified when logout is complete via the callback interface. Note that this method is asynchronous and the callback will be invoked in a background thread; operations that affect the UI will need to be posted to the UI thread or an appropriate handler.
 * @param context The Android context in which the logout should be called: it should be the same context in which the login occurred in order to clear any stored cookies
 * @param listener Callback interface to notify the application when the request has completed.
 * @param state An arbitrary object used to identify the request when it returns to the callback. This has no effect on the request itself.
 */
public void logout(final Context context,final RequestListener listener,final Object state){
  new Thread(){
    @Override public void run(){
      try {
        String response=fb.logout(context);
        if (response.length() == 0 || response.equals("false")) {
          listener.onFacebookError(new FacebookError("auth.expireSession failed"),state);
          return;
        }
        listener.onComplete(response,state);
      }
 catch (      FileNotFoundException e) {
        listener.onFileNotFoundException(e,state);
      }
catch (      MalformedURLException e) {
        listener.onMalformedURLException(e,state);
      }
catch (      IOException e) {
        listener.onIOException(e,state);
      }
    }
  }
.start();
}
 

Example 27

From project android-xbmcremote, under directory /src/org/xbmc/android/remote/presentation/controller/.

Source file: MediaIntentController.java

  29 
vote

private static boolean isValidURL(String path){
  if (path == null || path.equals(""))   return false;
  try {
    new URL(path);
  }
 catch (  MalformedURLException e) {
    return false;
  }
  return true;
}
 

Example 28

From project androidpn, under directory /androidpn-server-src/starter/src/main/java/org/androidpn/server/starter/.

Source file: ServerClassLoader.java

  29 
vote

/** 
 * Constructs the classloader.
 * @param parent the parent class loader (or null for none)
 * @param confDir the directory to load configration files from
 * @param libDir the directory to load jar files from
 * @throws java.net.MalformedURLException if the libDir path is not valid
 */
public ServerClassLoader(ClassLoader parent,File confDir,File libDir) throws MalformedURLException {
  super(new URL[]{confDir.toURI().toURL(),libDir.toURI().toURL()},parent);
  File[] jars=libDir.listFiles(new FilenameFilter(){
    public boolean accept(    File dir,    String name){
      boolean accept=false;
      String smallName=name.toLowerCase();
      if (smallName.endsWith(".jar")) {
        accept=true;
      }
 else       if (smallName.endsWith(".zip")) {
        accept=true;
      }
      return accept;
    }
  }
);
  if (jars == null) {
    return;
  }
  for (int i=0; i < jars.length; i++) {
    if (jars[i].isFile()) {
      addURL(jars[i].toURI().toURL());
    }
  }
}
 

Example 29

From project androidquery, under directory /auth/com/androidquery/auth/.

Source file: FacebookHandle.java

  29 
vote

private static Bundle parseUrl(String url){
  try {
    URL u=new URL(url);
    Bundle b=decodeUrl(u.getQuery());
    b.putAll(decodeUrl(u.getRef()));
    return b;
  }
 catch (  MalformedURLException e) {
    return new Bundle();
  }
}
 

Example 30

From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/examples/.

Source file: MockResultSet.java

  29 
vote

public URL getURL(int columnIndex) throws SQLException {
  try {
    return new URL("http://www.google.com/");
  }
 catch (  MalformedURLException ex) {
    throw new SQLException();
  }
}
 

Example 31

From project android_8, under directory /src/com/google/gson/.

Source file: DefaultTypeAdapters.java

  29 
vote

@Override public URL deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context) throws JsonParseException {
  try {
    return new URL(json.getAsString());
  }
 catch (  MalformedURLException e) {
    throw new JsonSyntaxException(e);
  }
}
 

Example 32

From project android_external_oauth, under directory /core/src/main/java/net/oauth/.

Source file: ConsumerProperties.java

  29 
vote

/** 
 * Get the consumer with the given name. 
 */
public OAuthConsumer getConsumer(String name) throws MalformedURLException {
  OAuthConsumer consumer;
synchronized (pool) {
    consumer=pool.get(name);
  }
  if (consumer == null) {
    consumer=newConsumer(name);
  }
synchronized (pool) {
    OAuthConsumer first=pool.get(name);
    if (first == null) {
      pool.put(name,consumer);
    }
 else {
      consumer=first;
    }
  }
  return consumer;
}
 

Example 33

From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/.

Source file: EditTagActivity.java

  29 
vote

/** 
 * Populates the editor from extras in a given  {@link Intent}
 * @param intent the {@link Intent} to parse.
 * @return whether or not the {@link Intent} could be handled.
 */
private boolean buildFromSendIntent(final Intent intent){
  String type=intent.getType();
  if ("text/plain".equals(type)) {
    String text=getIntent().getStringExtra(Intent.EXTRA_TEXT);
    try {
      URL parsed=new URL(text);
      mRecord=new UriRecordEditInfo(text);
      refresh();
      return true;
    }
 catch (    MalformedURLException ex) {
      mRecord=new TextRecordEditInfo(text);
      refresh();
      return true;
    }
  }
 else   if ("text/x-vcard".equals(type)) {
    Uri stream=(Uri)getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
    if (stream != null) {
      RecordEditInfo editInfo=VCardRecord.editInfoForUri(stream);
      if (editInfo != null) {
        mRecord=editInfo;
        refresh();
        return true;
      }
    }
  }
  return false;
}
 

Example 34

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: PostReporter.java

  29 
vote

/** 
 * Configures the POST Reporter. The given configuration <b>must</b> contain the  {@link PostReporter#ANDROLOG_REPORTER_POST_URL} property and it mustbe a valid  {@link URL}.
 * @see de.akquinet.android.androlog.reporter.Reporter#configure(java.util.Properties)
 */
@Override public void configure(Properties configuration){
  String u=configuration.getProperty(ANDROLOG_REPORTER_POST_URL);
  if (u == null) {
    Log.e(this,"The Property " + ANDROLOG_REPORTER_POST_URL + " is mandatory");
    return;
  }
  try {
    url=new URL(u);
  }
 catch (  MalformedURLException e) {
    Log.e(this,"The Property " + ANDROLOG_REPORTER_POST_URL + " is not a valid url",e);
  }
}
 

Example 35

From project ANE-Facebook, under directory /android/src/com/freshplanet/natExt/.

Source file: FBRequestThread.java

  29 
vote

@Override public void run(){
  String data=null;
  try {
    if (paramsString != null) {
      params=new Bundle();
      params.putString("fields",paramsString);
    }
    if (params != null) {
      data=FBExtensionContext.facebook.request(graphPath,params,this.httpMethod);
    }
 else {
      data=FBExtensionContext.facebook.request(graphPath);
    }
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
    context.dispatchStatusEventAsync(callbackName,e.getMessage());
  }
catch (  IOException e) {
    e.printStackTrace();
    context.dispatchStatusEventAsync(callbackName,e.getMessage());
  }
catch (  Exception e) {
    e.printStackTrace();
    context.dispatchStatusEventAsync(callbackName,e.getMessage());
  }
  if (data != null && callbackName != null) {
    context.dispatchStatusEventAsync(callbackName,data);
  }
}
 

Example 36

From project ant4eclipse, under directory /org.ant4eclipse.ant.platform/src/org/ant4eclipse/ant/platform/internal/team/.

Source file: SvnAdapter.java

  29 
vote

/** 
 * {@inheritDoc}
 */
@Override protected void checkout(File destination,TeamProjectDescription projectDescription) throws Ant4EclipseException {
  Assure.isDirectory("destination",destination);
  Assure.notNull("projectDescription",projectDescription);
  Assure.assertTrue(projectDescription instanceof SvnTeamProjectDescription,"ProjectDescription must be a SvnTeamProjectDescription");
  SvnTeamProjectDescription svnTeamProjectDescription=(SvnTeamProjectDescription)projectDescription;
  SvnTask task=createSvnTask(svnTeamProjectDescription);
  Checkout checkout=new Checkout();
  checkout.setProject(getAntProject());
  checkout.setTask(task);
  File destPath=new File(destination,svnTeamProjectDescription.getProjectName());
  A4ELogging.debug("Setting dest path for project '%s' to '%s'",svnTeamProjectDescription.getProjectName(),destPath);
  checkout.setDestpath(destPath);
  checkout.setRevision(svnTeamProjectDescription.getRevision());
  try {
    checkout.setUrl(new SVNUrl(svnTeamProjectDescription.getUrl()));
  }
 catch (  MalformedURLException e) {
    throw new Ant4EclipseException(PlatformExceptionCode.COULD_NOT_BUILD_SVNURL_FOR_PROJECT,svnTeamProjectDescription.getUrl(),svnTeamProjectDescription.getProjectName(),e.toString());
  }
  task.addCheckout(checkout);
  try {
    task.execute();
  }
 catch (  Exception ex) {
    throw new Ant4EclipseException(ex,PlatformExceptionCode.ERROR_WHILE_EXECUTING_SVN_COMMAND,"checkout",ex.toString());
  }
}
 

Example 37

From project AntiCheat, under directory /src/main/java/net/h31ix/anticheat/update/.

Source file: Updater.java

  29 
vote

/** 
 * Initialize the updater
 * @param plugin The plugin that is checking for an update.
 * @param slug The dev.bukkit.org slug of the project (http://dev.bukkit.org/server-mods/SLUG_IS_HERE)
 * @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
 * @param type Specify the type of update this will be. See  {@link UpdateType}
 * @param announce True if the program should announce the progress of new updates in console
 */
public Updater(Plugin plugin,String slug,File file,UpdateType type,boolean announce){
  this.plugin=plugin;
  this.type=type;
  this.announce=announce;
  try {
    url=new URL(DBOUrl + slug + "/files.rss");
  }
 catch (  MalformedURLException ex) {
    plugin.getLogger().warning("The author of this plugin has misconfigured their Auto Update system");
    plugin.getLogger().warning("The project slug added ('" + slug + "') is invalid, and does not exist on dev.bukkit.org");
    result=Updater.UpdateResult.FAIL_BADSLUG;
  }
  if (url != null) {
    readFeed();
    if (versionCheck(versionTitle)) {
      String fileLink=getFile(versionLink);
      if (fileLink != null && type != UpdateType.NO_DOWNLOAD) {
        String name=file.getName();
        if (fileLink.endsWith(".zip")) {
          String[] split=fileLink.split("/");
          name=split[split.length - 1];
        }
        saveFile(new File("plugins/" + updateFolder),name,fileLink);
      }
 else {
        result=UpdateResult.UPDATE_AVAILABLE;
      }
    }
  }
}
 

Example 38

From project any23, under directory /api/src/main/java/org/apache/any23/plugin/.

Source file: Any23PluginManager.java

  29 
vote

public boolean addClassDir(File classDir){
  final String urlPath="file://" + classDir.getAbsolutePath() + "/";
  try {
    if (addURL(urlPath)) {
      dirs.add(classDir);
      return true;
    }
    return false;
  }
 catch (  MalformedURLException murle) {
    throw new RuntimeException("Invalid dir URL.",murle);
  }
}
 

Example 39

From project apb, under directory /modules/apb-base/src/apb/compiler/.

Source file: InMemJavaC.java

  29 
vote

/** 
 * Creates the Compiler
 * @param environment
 */
public InMemJavaC(@NotNull Environment environment){
  env=environment;
  compiler=ToolProvider.getSystemJavaCompiler();
  try {
    memoryClassLoader=new MemoryClassLoader(FileUtils.toUrl(environment.getExtClassPath()),getClass().getClassLoader());
  }
 catch (  MalformedURLException e) {
    throw new BuildException(e);
  }
  fileManager=new MemoryJavaFileManager(compiler,memoryClassLoader);
  classesByFile=new HashMap<File,Class>();
}
 

Example 40

From project apg, under directory /src/org/thialfihar/android/apg/.

Source file: HkpKeyServer.java

  29 
vote

private String query(String request) throws QueryException, HttpError {
  InetAddress ips[];
  try {
    ips=InetAddress.getAllByName(mHost);
  }
 catch (  UnknownHostException e) {
    throw new QueryException(e.toString());
  }
  for (int i=0; i < ips.length; ++i) {
    try {
      String url="http://" + ips[i].getHostAddress() + ":"+ mPort+ request;
      URL realUrl=new URL(url);
      HttpURLConnection conn=(HttpURLConnection)realUrl.openConnection();
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(25000);
      conn.connect();
      int response=conn.getResponseCode();
      if (response >= 200 && response < 300) {
        return readAll(conn.getInputStream(),conn.getContentEncoding());
      }
 else {
        String data=readAll(conn.getErrorStream(),conn.getContentEncoding());
        throw new HttpError(response,data);
      }
    }
 catch (    MalformedURLException e) {
    }
catch (    IOException e) {
    }
  }
  throw new QueryException("querying server(s) for '" + mHost + "' failed");
}
 

Example 41

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/client/.

Source file: AndroidNativeDriverBuilder.java

  29 
vote

private static URL defaultServerUrl(){
  try {
    return new URL(DEFAULT_SERVER_URL);
  }
 catch (  MalformedURLException exception) {
    throw Throwables.propagate(exception);
  }
}
 

Example 42

From project Application-Builder, under directory /src/main/java/org/silverpeas/applicationbuilder/.

Source file: EARDirectory.java

  29 
vote

/** 
 * Adds an entry to the archive. The entry added is fetched from the file system
 * @param entry the file to add
 * @since 1.0
 * @roseuid 3AAF55F2017D
 */
public void add(ApplicationBuilderItem entry) throws AppBuilderException {
  try {
    add(entry,entry.getPath().toURI().toURL().openStream());
  }
 catch (  MalformedURLException mue) {
    throw new AppBuilderException(getName() + " : could not add \"" + entry.getName()+ "\"",mue);
  }
catch (  IOException ioe) {
    throw new AppBuilderException(getName() + " : could not add \"" + entry.getName()+ "\"",ioe);
  }
}
 

Example 43

From project apps-for-android, under directory /CLiCkin2DaBeaT/src/com/google/clickin2dabeat/.

Source file: Unzipper.java

  29 
vote

public static String download(String fileUrl){
  URLConnection cn;
  try {
    fileUrl=(new URL(new URL(fileUrl),fileUrl)).toString();
    URL url=new URL(fileUrl);
    cn=url.openConnection();
    cn.connect();
    InputStream stream=cn.getInputStream();
    File outputDir=new File("/sdcard/c2b/");
    outputDir.mkdirs();
    String filename=fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    filename=filename.substring(0,filename.indexOf("c2b.zip") + 7);
    File outputFile=new File("/sdcard/c2b/",filename);
    outputFile.createNewFile();
    FileOutputStream out=new FileOutputStream(outputFile);
    byte buf[]=new byte[16384];
    do {
      int numread=stream.read(buf);
      if (numread <= 0) {
        break;
      }
 else {
        out.write(buf,0,numread);
      }
    }
 while (true);
    stream.close();
    out.close();
    return "/sdcard/c2b/" + filename;
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
    return "";
  }
catch (  IOException e) {
    e.printStackTrace();
    return "";
  }
}
 

Example 44

From project aranea, under directory /server/src/main/java/no/dusken/aranea/filter/.

Source file: PluginAwareUrlRewriteFilter.java

  29 
vote

@Override protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
  ServletContext context=filterConfig.getServletContext();
  InputStream inputStream=context.getResourceAsStream(DEFAULT_WEB_CONF_PATH);
  URL confUrl=null;
  try {
    confUrl=context.getResource(DEFAULT_WEB_CONF_PATH);
  }
 catch (  MalformedURLException e) {
    log.debug("Malformed url",e);
  }
  String confUrlStr=null;
  if (confUrl != null) {
    confUrlStr=confUrl.toString();
  }
  if (inputStream == null) {
    log.error("unable to find urlrewrite conf file at " + DEFAULT_WEB_CONF_PATH);
  }
 else {
    Conf conf=new PluginAwareConf(context,inputStream,DEFAULT_WEB_CONF_PATH,confUrlStr);
    checkConf(conf);
  }
}
 

Example 45

From project archaius, under directory /archaius-core/src/main/java/com/netflix/config/.

Source file: WebApplicationProperties.java

  29 
vote

protected static void initApplicationProperties() throws ConfigurationException, MalformedURLException {
  File appPropFile=new File(appConfFolder + "/" + baseConfigFileName+ ".properties");
  File appEnvPropOverrideFile=new File(appConfFolder + "/" + baseConfigFileName+ getEnvironment()+ ".properties");
  PropertiesConfiguration appConf=new PropertiesConfiguration(appPropFile);
  PropertiesConfiguration overrideConf=new PropertiesConfiguration(appEnvPropOverrideFile);
  Properties overrideprops=ConfigurationUtils.getProperties(overrideConf);
  for (  Object prop : overrideprops.keySet()) {
    appConf.setProperty("" + prop,overrideprops.getProperty("" + prop));
  }
  String path=appPropFile.toURI().toURL().toString();
  System.setProperty(URLConfigurationSource.CONFIG_URL,path);
  ConfigurationManager.loadPropertiesFromConfiguration(appConf);
}
 

Example 46

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/extract/.

Source file: RealCDXExtractorOutput.java

  29 
vote

private String resolve(String context,String spec){
  try {
    URL cUrl=new URL(context);
    URL resolved=new URL(cUrl,spec);
    return resolved.toURI().toASCIIString();
  }
 catch (  URISyntaxException e) {
  }
catch (  MalformedURLException e) {
  }
catch (  NullPointerException e) {
  }
  return spec;
}
 

Example 47

From project arquillian-container-openshift, under directory /openshift-express/src/main/java/org/jboss/arquillian/container/openshift/express/.

Source file: OpenShiftExpressConfiguration.java

  29 
vote

/** 
 * @return the rootContextUrl
 */
public String getRootContextUrl(){
  try {
    return constructRootContext().toURI().toString();
  }
 catch (  MalformedURLException e) {
    throw new IllegalArgumentException("Application name, namespace and Libra Domain does not represent a valid URL",e);
  }
catch (  URISyntaxException e) {
    throw new RuntimeException("Application name, namespace and Libra Domain does not represent a valid URL",e);
  }
}
 

Example 48

From project arquillian-container-tomcat, under directory /tomcat-common/src/main/java/org/jboss/arquillian/container/tomcat/.

Source file: CommonTomcatConfiguration.java

  29 
vote

@Override public void validate() throws ConfigurationException {
  Validate.notNullOrEmpty(bindAddress,"Bind address must not be null or empty");
  Validate.isInRange(jmxPort,0,MAX_PORT,"JMX port must be in interval ]" + MIN_PORT + ","+ MAX_PORT+ "[, but was "+ jmxPort);
  try {
    this.setJmxUri(createJmxUri());
    this.setManagerUrl(createManagerUrl());
  }
 catch (  URISyntaxException ex) {
    throw new ConfigurationException("JMX URI is not valid, please provide ",ex);
  }
catch (  MalformedURLException e) {
    throw new ConfigurationException("JMX URI is not valid",e);
  }
}
 

Example 49

From project arquillian-container-weld, under directory /weld-ee-embedded-1.1/src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockServletContext.java

  29 
vote

/** 
 * Get the URL for a particular resource that is relative to the web app root directory.
 * @param name The name of the resource to get
 * @return The resource, or null if resource not found
 * @throws MalformedURLException If the URL is invalid
 */
public URL getResource(String name) throws MalformedURLException {
  if (webappRoot == null) {
    return null;
  }
  if (name.startsWith("/")) {
    name=name.substring(1);
  }
  File f=new File(webappRoot,name);
  if (!f.exists()) {
    return null;
  }
 else {
    return f.toURI().toURL();
  }
}
 

Example 50

From project arquillian-extension-drone, under directory /drone-webdriver/src/main/java/org/jboss/arquillian/drone/webdriver/factory/.

Source file: Validate.java

  29 
vote

static void isValidUrl(String url,String message) throws IllegalArgumentException {
  isEmpty(url,message);
  try {
    new URL(url);
  }
 catch (  MalformedURLException e) {
    throw new IllegalArgumentException(message,e);
  }
}
 

Example 51

From project arquillian-extension-seam2, under directory /src/main/java/org/jboss/arquillian/seam2/configuration/.

Source file: ConfigurationTypeConverter.java

  29 
vote

/** 
 * A helper converting method. Converts string to a class of given type
 * @param value String value to be converted
 * @param to Type of desired value
 * @param < T > Type of returned value
 * @return Value converted to a appropriate type
 */
public <T>T convert(String value,Class<T> to){
  if (String.class.equals(to)) {
    return to.cast(value);
  }
 else   if (Integer.class.equals(to)) {
    return to.cast(Integer.valueOf(value));
  }
 else   if (Double.class.equals(to)) {
    return to.cast(Double.valueOf(value));
  }
 else   if (Long.class.equals(to)) {
    return to.cast(Long.valueOf(value));
  }
 else   if (Boolean.class.equals(to)) {
    return to.cast(Boolean.valueOf(value));
  }
 else   if (URL.class.equals(to)) {
    try {
      return to.cast(new URI(value).toURL());
    }
 catch (    MalformedURLException e) {
      throw new IllegalArgumentException("Unable to convert value " + value + " to URL",e);
    }
catch (    URISyntaxException e) {
      throw new IllegalArgumentException("Unable to convert value " + value + " to URL",e);
    }
  }
 else   if (URI.class.equals(to)) {
    try {
      return to.cast(new URI(value));
    }
 catch (    URISyntaxException e) {
      throw new IllegalArgumentException("Unable to convert value " + value + " to URL",e);
    }
  }
  throw new IllegalArgumentException("Unable to convert value " + value + "to a class: "+ to.getName());
}
 

Example 52

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/client/proxy/.

Source file: DefaultURLMapping.java

  29 
vote

private URL newProxyUrlWithPort(URL url,int port){
  try {
    return new URL(url.getProtocol(),"localhost",port,url.getFile());
  }
 catch (  MalformedURLException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 53

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-drone/src/main/java/org/jboss/arquillian/ajocado/drone/configuration/.

Source file: ArquillianGrapheneConfiguration.java

  29 
vote

/** 
 * @return the contextRoot
 */
public URL getContextRoot(){
  try {
    if (contextRoot != null && !contextRoot.toString().endsWith("/")) {
      contextRoot=new URL(contextRoot.toString() + "/");
    }
  }
 catch (  MalformedURLException e) {
    throw new IllegalArgumentException("Unable to convert contextRoot from configuration to URL",e);
  }
  return contextRoot;
}
 

Example 54

From project arquillian-weld-embedded-1.1, under directory /src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockServletContext.java

  29 
vote

/** 
 * Get the URL for a particular resource that is relative to the web app root directory.
 * @param name The name of the resource to get
 * @return The resource, or null if resource not found
 * @throws MalformedURLException If the URL is invalid
 */
public URL getResource(String name) throws MalformedURLException {
  if (webappRoot == null) {
    return null;
  }
  if (name.startsWith("/")) {
    name=name.substring(1);
  }
  File f=new File(webappRoot,name);
  if (!f.exists()) {
    return null;
  }
 else {
    return f.toURI().toURL();
  }
}
 

Example 55

From project arquillian_deprecated, under directory /containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/.

Source file: EmbeddedContextConfig.java

  29 
vote

/** 
 * Process the META-INF/context.xml descriptor in the web application root. This descriptor is not processed when a webapp is added programmatically through a StandardContext
 */
protected void applicationContextConfig(){
  ServletContext servletContext=context.getServletContext();
  InputStream stream=servletContext.getResourceAsStream("/" + Constants.ApplicationContextXml);
  if (stream == null) {
    return;
  }
synchronized (contextDigester) {
    URL url=null;
    try {
      url=servletContext.getResource("/" + Constants.ApplicationContextXml);
    }
 catch (    MalformedURLException e) {
      throw new AssertionError("/" + Constants.ApplicationContextXml + " should not be considered a malformed URL");
    }
    InputSource is=new InputSource(url.toExternalForm());
    is.setByteStream(stream);
    contextDigester.push(context);
    try {
      contextDigester.parse(is);
    }
 catch (    Exception e) {
      ok=false;
      log.error("Parse error in context.xml for " + context.getName(),e);
    }
 finally {
      contextDigester.reset();
      try {
        if (stream != null) {
          stream.close();
        }
      }
 catch (      IOException e) {
        log.error("Error closing context.xml for " + context.getName(),e);
      }
    }
  }
  log.debug("Done processing " + Constants.ApplicationContextXml + " descriptor");
}
 

Example 56

From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  29 
vote

URL getSealURL(){
  String seal=mf.getMainAttributes().getValue(Name.SEALED);
  if (seal != null) {
    try {
      return new URL(seal);
    }
 catch (    MalformedURLException e) {
    }
  }
  return null;
}
 

Example 57

From project asterisk-java, under directory /src/main/java/org/asteriskjava/fastagi/.

Source file: AbstractMappingStrategy.java

  29 
vote

/** 
 * Returns the ClassLoader to use for loading AgiScript classes and load other resources like the mapping properties file.<p> By default this method returns a class loader that searches for classes in the "agi" subdirectory (if it exists) and uses the context class loader of the current thread as the parent class loader.<p> You can override this method if you prefer using a different class loader.
 * @return the ClassLoader to use for loading AgiScript classes and loadother resources like the mapping properties file.
 * @since 1.0.0
 */
protected synchronized ClassLoader getClassLoader(){
  if (defaultClassLoader == null) {
    final ClassLoader parentClassLoader=Thread.currentThread().getContextClassLoader();
    final List<URL> dirUrls=new ArrayList<URL>();
    for (    String scriptPathEntry : DEFAULT_SCRIPT_PATH) {
      final File scriptDir=new File(scriptPathEntry);
      if (!scriptDir.isDirectory()) {
        continue;
      }
      try {
        dirUrls.add(scriptDir.toURI().toURL());
      }
 catch (      MalformedURLException e) {
      }
    }
    if (dirUrls.size() == 0) {
      return parentClassLoader;
    }
    defaultClassLoader=new URLClassLoader(dirUrls.toArray(new URL[dirUrls.size()]),parentClassLoader);
  }
  return defaultClassLoader;
}
 

Example 58

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-sync/src/main/java/fm/audiobox/sync/stream/.

Source file: SocketClient.java

  29 
vote

/** 
 * Connects to Socket server and returns  {@code true} it everithing went ok
 * @return boolean
 */
public void connect() throws ServiceException {
  log.info("Trying to connect to server");
  if (this.isConnected()) {
    this.disconnect();
    this.wasConnected=false;
  }
  if (this.audiobox.getUser() != null) {
    String urlStr=this.getServerUrl();
    URL url=null;
    try {
      url=new URL(urlStr);
      log.info("Server will be " + url.toURI().toString());
    }
 catch (    MalformedURLException e) {
      log.error("Invalid url found");
      throw new ServiceException("No valid URL for server found");
    }
catch (    URISyntaxException e) {
      log.error("Invalid url found");
      throw new ServiceException("No valid URL for server found");
    }
    this.socket=new SocketIO(url);
    this.socket.addHeader(IConnector.X_AUTH_TOKEN_HEADER,this.audiobox.getUser().getAuthToken());
    this.socket.connect(this);
  }
 else {
    this.wasConnected=true;
  }
}
 

Example 59

From project autopatch-maven-plugin, under directory /src/main/java/com/tacitknowledge/autopatch/maven/.

Source file: AbstractAutoPatchMojo.java

  29 
vote

/** 
 * Adds the classpath elements to a new class loader and sets it as the  current thread context's class loader.
 * @throws MalformedURLException if a classpath element contains a malformed url.
 */
protected void addClasspathElementsClassLoader() throws MalformedURLException {
  URL[] urls=new URL[classpathElements.size()];
  Iterator iter=classpathElements.iterator();
  int i=0;
  while (iter.hasNext()) {
    urls[i++]=new File((String)iter.next()).toURL();
  }
  URLClassLoader urlClassLoader=new URLClassLoader(urls,Thread.currentThread().getContextClassLoader());
  Thread.currentThread().setContextClassLoader(urlClassLoader);
}
 

Example 60

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/corecomponents/.

Source file: ProductInformationPanel.java

  29 
vote

private void jLabel1MouseClicked(java.awt.event.MouseEvent evt){
  try {
    url=new URL(NbBundle.getMessage(ProductInformationPanel.class,"URL_ON_IMG"));
    showUrl();
  }
 catch (  MalformedURLException ex) {
  }
  url=null;
}
 

Example 61

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/trace/.

Source file: TraceClientServlet.java

  29 
vote

@Override public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out=response.getWriter();
  String servers=request.getParameter("servers");
  if (servers != null) {
    String splitToken=System.getProperty("line.separator");
    lastInput=servers;
    if (splitToken == null) {
      splitToken="\n";
    }
    String[] parts=servers.split(splitToken);
    List<URL> urls=new LinkedList<URL>();
    for (    String p : parts) {
      String[] portHost=p.split(":");
      if (portHost.length != 2) {
        continue;
      }
      try {
        URL url=new URL("http://" + p);
        urls.add(url);
      }
 catch (      MalformedURLException e) {
        continue;
      }
    }
    List<Span> spans=collectAllSpans(urls);
    List<Span> merged=SpanAggregator.getFullSpans(spans).completeSpans;
    this.activeSpans.addAll(merged);
    List<Trace> traces=SpanAggregator.getTraces(merged).traces;
    List<TraceCollection> collections=SpanAggregator.getTraceCollections(traces);
    for (    TraceCollection col : collections) {
      this.activeCollections.put(col.getExecutionPathHash(),col);
    }
    response.sendRedirect("/overview/");
  }
 else {
    out.println("No text entered.");
  }
}
 

Example 62

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/.

Source file: RegionUtils.java

  29 
vote

/** 
 * Searches through all known regions to find one with any service at the specified endpoint. If no region is found with a service at that endpoint, an exception is thrown.
 * @param endpoint The endpoint for any service residing in the desired region.
 * @return The region containing any service running at the specifiedendpoint, otherwise an exception is thrown if no region is found with a service at the specified endpoint.
 */
public static Region getRegionByEndpoint(String endpoint){
  URL targetEndpointUrl=null;
  try {
    targetEndpointUrl=new URL(endpoint);
  }
 catch (  MalformedURLException e) {
    throw new RuntimeException("Unable to parse service endpoint: " + e.getMessage());
  }
  String targetHost=targetEndpointUrl.getHost();
  for (  Region region : getRegions()) {
    for (    String serviceEndpoint : region.getServiceEndpoints().values()) {
      try {
        URL serviceEndpointUrl=new URL(serviceEndpoint);
        if (serviceEndpointUrl.getHost().equals(targetHost))         return region;
      }
 catch (      MalformedURLException e) {
        Status status=new Status(Status.ERROR,AwsToolkitCore.PLUGIN_ID,"Unable to parse service endpoint: " + serviceEndpoint,e);
        StatusManager.getManager().handle(status,StatusManager.LOG);
      }
    }
  }
  throw new RuntimeException("No region found with any service for endpoint " + endpoint);
}
 

Example 63

From project azkaban, under directory /azkaban/src/java/azkaban/app/.

Source file: AzkabanApplication.java

  29 
vote

private ClassLoader getBaseClassloader() throws MalformedURLException {
  final ClassLoader retVal;
  String hadoopHome=System.getenv("HADOOP_HOME");
  String hadoopConfDir=System.getenv("HADOOP_CONF_DIR");
  if (hadoopConfDir != null) {
    logger.info("Using hadoop config found in " + hadoopConfDir);
    retVal=new URLClassLoader(new URL[]{new File(hadoopConfDir).toURI().toURL()},getClass().getClassLoader());
  }
 else   if (hadoopHome != null) {
    logger.info("Using hadoop config found in " + hadoopHome);
    retVal=new URLClassLoader(new URL[]{new File(hadoopHome,"conf").toURI().toURL()},getClass().getClassLoader());
  }
 else {
    logger.info("HADOOP_HOME not set, using default hadoop config.");
    retVal=getClass().getClassLoader();
  }
  return retVal;
}
 

Example 64

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/taskqueue/local/.

Source file: LocalTaskRunner.java

  29 
vote

@Override public void run(){
  urlFetchService=URLFetchServiceFactory.getURLFetchService();
  final HTTPRequest httpRequest=new HTTPRequest();
  try {
    httpRequest.setURL(new URL(Latkes.getServer() + Latkes.getContextPath() + task.getURL()));
    httpRequest.setRequestMethod(task.getRequestMethod());
    httpRequest.setPayload(task.getPayload());
  }
 catch (  final MalformedURLException e) {
    e.printStackTrace();
  }
  Integer retry=0;
  while (retry < retryLimit) {
    if (!doUrlFetch(httpRequest)) {
      retry++;
      try {
        Thread.sleep(new Integer("1000"));
      }
 catch (      final InterruptedException e) {
        e.printStackTrace();
      }
    }
 else {
      break;
    }
  }
}
 

Example 65

From project BazaarUtils, under directory /src/com/congenialmobile/utils/.

Source file: NetUtils.java

  29 
vote

/** 
 * Retrieve a file from the given url and save it into the given destination file.
 * @param sourceUrl
 * @param dest
 * @param stopperIndicator
 * @return true if successful
 */
public static boolean retrieveAndSave(final String sourceUrl,final File dest,final StopperIndicator stopperIndicator){
  try {
    final URL url=new URL(sourceUrl);
    return retrieveAndSave(url,dest,null);
  }
 catch (  MalformedURLException e) {
    Log.w(TAG,"retrieveAndSave :: MalformedURLException",e);
    return false;
  }
}
 

Example 66

From project beam-third-party, under directory /beam-meris-veg/src/main/java/org/esa/beam/processor/baer/.

Source file: BaerProcessor.java

  29 
vote

/** 
 * Retrieves the full path to the processor configuration file.
 * @return the config path
 * @throws org.esa.beam.framework.processor.ProcessorException
 */
private URL getConfigPath() throws ProcessorException {
  File configFile=new File(getAuxdataInstallDir(),BaerConstants.CONFIG_FILE);
  URL configPath=null;
  try {
    configPath=configFile.toURI().toURL();
  }
 catch (  MalformedURLException e) {
    throw new ProcessorException("Failed to create configuration URL for " + configFile.getPath(),e);
  }
  return configPath;
}
 

Example 67

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: LoaderImageView.java

  29 
vote

public void setImageDrawable(final String imageUrl,final int width,final int height,final boolean scale){
  mDrawable=null;
  mSpinner.setVisibility(View.VISIBLE);
  mImage.setVisibility(View.GONE);
  if (scale) {
    mImage.setAdjustViewBounds(true);
    mImage.setMaxHeight(height);
    mImage.setMaxWidth(width);
    mImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    mSpinner.setLayoutParams(new LayoutParams(width / 2,height / 2));
  }
  new Thread(){
    public void run(){
      try {
        mDrawable=getDrawableFromUrl(imageUrl);
        if (scale) {
          try {
            Bitmap bmImg=((BitmapDrawable)mDrawable).getBitmap();
            Bitmap resizedbitmap=resize(bmImg,width,height);
            mDrawable=new BitmapDrawable(resizedbitmap);
          }
 catch (          Exception e) {
            e.printStackTrace();
          }
        }
        imageLoadedHandler.sendEmptyMessage(COMPLETE);
      }
 catch (      MalformedURLException e) {
        imageLoadedHandler.sendEmptyMessage(FAILED);
        e.printStackTrace();
      }
catch (      IOException e) {
        imageLoadedHandler.sendEmptyMessage(FAILED);
        e.printStackTrace();
      }
    }
  }
.start();
}
 

Example 68

From project bel-editor, under directory /org.openbel.editor.ui/src/org/openbel/editor/ui/views/.

Source file: NamespaceView.java

  29 
vote

private void launchBrowserForSelection(){
  final NamespaceInfo ns=getSelectedNamespaceInfo(combo.getSelectionIndex());
  int si=table.getSelectionIndex();
  String entity=table.getItem(si).getText();
  String link=ns.getQueryValueURL();
  if (link == null) {
    return;
  }
  try {
    IWebBrowser netscape=PlatformUI.getWorkbench().getBrowserSupport().createBrowser("entity-details");
    link=link.replace("[VALUE]",URLEncoder.encode(entity,Strings.UTF_8));
    netscape.openURL(new URL(link));
  }
 catch (  PartInitException e) {
    logError("Cound not load browser.");
    logError(e);
  }
catch (  MalformedURLException e) {
    logError("Entity url of '" + link + "' is invalid.");
    logError(e);
  }
catch (  UnsupportedEncodingException e) {
    logError("Entity url of '" + link + "' is invalid.");
    logError(e);
  }
}
 

Example 69

From project BetterShop_1, under directory /src/me/jascotty2/lib/net/.

Source file: FTP.java

  29 
vote

protected URL makeURL(String targetfile) throws MalformedURLException {
  if (user == null) {
    return new URL("ftp://" + host + "/"+ targetfile+ ";type=i");
  }
 else {
    return new URL("ftp://" + user + ":"+ password.replace("@","%40").replace("#","%23").replace(" ","%20")+ "@"+ host+ "/"+ targetfile+ ";type=i");
  }
}
 

Example 70

From project big-data-plugin, under directory /shims/api/src/org/pentaho/hbase/shim/spi/.

Source file: HBaseConnection.java

  29 
vote

/** 
 * Utility method to covert a string to a URL object.
 * @param pathOrURL file or http URL as a string
 * @return a URL
 * @throws MalformedURLException if there is a problem with the URL.
 */
public static URL stringToURL(String pathOrURL) throws MalformedURLException {
  URL result=null;
  if (isEmpty(pathOrURL)) {
    if (pathOrURL.toLowerCase().startsWith("http://") || pathOrURL.toLowerCase().startsWith("file://")) {
      result=new URL(pathOrURL);
    }
 else {
      String c="file://" + pathOrURL;
      result=new URL(c);
    }
  }
  return result;
}
 

Example 71

From project Bio-PEPA, under directory /uk.ac.ed.inf.biopepa.ui/lib/opencsv-2.1/examples/.

Source file: MockResultSet.java

  29 
vote

public URL getURL(int columnIndex) throws SQLException {
  try {
    return new URL("http://www.google.com/");
  }
 catch (  MalformedURLException ex) {
    throw new SQLException();
  }
}
 

Example 72

From project bioclipse.speclipse, under directory /plugins/net.bioclipse.nmrshiftdb.test/src/net/bioclipse/nmrshiftdb/business/test/.

Source file: AbstractNmrshiftdbManagerPluginTest.java

  29 
vote

@Test public void testSearchBySpectrum() throws URISyntaxException, MalformedURLException, IOException, BioclipseException, CoreException {
  URI uri=getClass().getResource("/testFiles/testspectrum.cml").toURI();
  URL url=FileLocator.toFileURL(uri.toURL());
  String path=url.getFile();
  JumboSpectrum cmlspectrum=net.bioclipse.spectrum.Activator.getDefault().getJavaSpectrumManager().loadSpectrum(path);
  List<ICDKMolecule> result=nmrshiftdbmmanager.searchBySpectrum(cmlspectrum,true,"http://www.ebi.ac.uk/nmrshiftdb/axis");
  Assert.assertTrue(result.size() > 0);
  Assert.assertEquals("100.00 %",result.get(0).getAtomContainer().getProperty("similarity"));
}
 

Example 73

From project Bit4Tat, under directory /Bit4Tat/src/com/Bit4Tat/.

Source file: PaymentProcessorForMtGox.java

  29 
vote

HttpsURLConnection setupConnection(String urlString){
  SSLContext ctx=null;
  try {
    ctx=SSLContext.getInstance("TLS");
  }
 catch (  NoSuchAlgorithmException e1) {
    e1.printStackTrace();
  }
  try {
    ctx.init(new KeyManager[0],new TrustManager[]{new DefaultTrustManager()},new SecureRandom());
  }
 catch (  KeyManagementException e) {
    e.printStackTrace();
  }
  SSLContext.setDefault(ctx);
  URL url=null;
  try {
    url=new URL(urlString);
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
  HttpsURLConnection conn=null;
  try {
    conn=(HttpsURLConnection)url.openConnection();
  }
 catch (  IOException e1) {
    e1.printStackTrace();
  }
  conn.setDoOutput(true);
  conn.setDoInput(true);
  conn.setHostnameVerifier(new HostnameVerifier(){
    @Override public boolean verify(    String arg0,    SSLSession arg1){
      return true;
    }
  }
);
  return conn;
}
 

Example 74

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/browsers/.

Source file: FishEyeSVN.java

  29 
vote

@DataBoundConstructor public FishEyeSVN(URL url,String rootModule) throws MalformedURLException {
  this.url=normalizeToEndWithSlash(url);
  rootModule=rootModule.trim();
  if (rootModule.startsWith("/"))   rootModule=rootModule.substring(1);
  if (rootModule.endsWith("/"))   rootModule=rootModule.substring(0,rootModule.length() - 1);
  this.rootModule=rootModule;
}
 

Example 75

From project Blitz, under directory /src/com/laxser/blitz/scanning/vfs/.

Source file: SimpleFileObject.java

  29 
vote

SimpleFileObject(FileSystemManager fs,URL url) throws FileNotFoundException, MalformedURLException {
  this.fs=fs;
  File file=ResourceUtils.getFile(url);
  String urlString=url.toString();
  this.url=url;
  this.file=file;
  this.urlString=urlString;
  this.fileName=new FileNameImpl(this,file.getName());
}
 

Example 76

From project Blueprint, under directory /blueprint-core/src/test/java/org/codemined/blueprint/.

Source file: BlueprintTest.java

  29 
vote

@Test public void typeHinting() throws MalformedURLException {
  TestConfiguration cfg=createTestBlueprint();
  assertEquals(cfg.state(String.class),"TRUE");
  assertTrue(cfg.state(Boolean.class));
  assertEquals(cfg.state(TestConfiguration._State.class),TestConfiguration._State.TRUE);
  assertEquals(cfg.deployUrl().getClass(),URL.class);
  assertEquals(cfg.deployUrl(),new URL("http://www.codemined.org/blueprint"));
  cfg.deployUrl().getHost();
}