Example #1
1
  /** @see java.net.URLStreamHandler#openConnection(URL) */
  protected URLConnection openConnection(URL u) throws IOException {

    try {

      URL otherURL = new URL(u.getFile());
      String host = otherURL.getHost();
      String protocol = otherURL.getProtocol();
      int port = otherURL.getPort();
      String file = otherURL.getFile();
      String query = otherURL.getQuery();
      // System.out.println("Trying to load: " + u.toExternalForm());
      String internalFile = null;
      if (file.indexOf("!/") != -1) {
        internalFile = file.substring(file.indexOf("!/") + 2);
        file = file.substring(0, file.indexOf("!/"));
      }
      URL subURL = new URL(protocol, host, port, file);
      File newFile;
      if (cacheList.containsKey(subURL.toExternalForm())) {
        newFile = cacheList.get(subURL.toExternalForm());
      } else {
        InputStream is = (InputStream) subURL.getContent();
        String update = subURL.toExternalForm().replace(":", "_");
        update = update.replace("/", "-");
        File f = File.createTempFile("pack", update);
        f.deleteOnExit();
        FileOutputStream fostream = new FileOutputStream(f);
        copyStream(new BufferedInputStream(is), fostream);

        // Unpack
        newFile = File.createTempFile("unpack", update);
        newFile.deleteOnExit();
        fostream = new FileOutputStream(newFile);
        BufferedOutputStream bos = new BufferedOutputStream(fostream, 50 * 1024);
        JarOutputStream jostream = new JarOutputStream(bos);
        Unpacker unpacker = Pack200.newUnpacker();
        long start = System.currentTimeMillis();

        unpacker.unpack(f, jostream);
        printMessage(
            "Unpack of " + update + " took " + (System.currentTimeMillis() - start) + "ms");
        jostream.close();
        fostream.close();
        cacheList.put(subURL.toExternalForm(), newFile);
      }
      if (internalFile != null) {

        URL directoryURL = new URL("jar:" + newFile.toURL().toExternalForm() + "!/" + internalFile);
        printMessage("Using DirectoryURL:" + directoryURL);
        return directoryURL.openConnection();
      } else return newFile.toURL().openConnection();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    printMessage("Returning null for: " + u.toExternalForm());
    return null;
  }
Example #2
0
 private String readUrl(String address) {
   String content = null;
   try {
     URL url = new URL(address);
     assertNotNull(url.getContent());
     content = IOUtils.toString((InputStream) url.getContent());
   } catch (IOException e) {
     e.printStackTrace(System.err);
     Assert.fail("Couldn't read URL: " + e.getMessage());
   }
   return content;
 }
Example #3
0
 /**
  * Gets the DTD for the specified doctype file name.
  *
  * @param doctype the doctype file name (e.g., "osp10.dtd")
  * @return the DTD as a string
  */
 public static String getDTD(String doctype) {
   if (dtdName != doctype) {
     // set to defaults in case doctype is not found
     dtdName = defaultName;
     try {
       String dtdPath = "/org/opensourcephysics/resources/controls/doctypes/"; // $NON-NLS-1$
       java.net.URL url = XML.class.getResource(dtdPath + doctype);
       if (url == null) {
         return dtd;
       }
       Object content = url.getContent();
       if (content instanceof InputStream) {
         BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) content));
         StringBuffer buffer = new StringBuffer(0);
         String line;
         while ((line = reader.readLine()) != null) {
           buffer.append(line + NEW_LINE);
         }
         dtd = buffer.toString();
         dtdName = doctype;
       }
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
   return dtd;
 }
  public byte[] fetchURL(String urlStr) {
    Log.d("PCL", "fetchURL('" + urlStr + "')");
    Object o = null;
    try {
      try {
        URL url = new URL(urlStr);
        o = url.getContent();
        // probably also need a "can't find the surver" exception
        // as well.  Maybe requeue the request to cache.
        // for now, just fix the no asset issue
      } catch (MalformedURLException e) {
        try {
          o = context.getApplicationContext().getAssets().open(urlStr);
        } catch (java.io.FileNotFoundException noFile) {
          return null;
        }
      }

      if (o instanceof InputStream) {
        return SurveyUtil.readAll((InputStream) o);
      } else if (o instanceof byte[]) {
        return (byte[]) o;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Example #5
0
  public static URL getURL(double latitude, double longitude, String output)
      throws MalformedURLException, IOException {
    StringBuilder stringBuilder = new StringBuilder(URL_PREFIX);
    stringBuilder.append("?");
    stringBuilder.append("output=" + output + "&");
    stringBuilder.append("location=" + latitude + "," + longitude + "&");
    stringBuilder.append("key=" + PRIVATE_KEY);

    URL url = new URL(stringBuilder.toString());

    System.out.println(String.format("getProtocol %s", url.getProtocol()));
    System.out.println(String.format("getHost %s", url.getHost()));
    System.out.println(String.format("getPath %s", url.getPath()));
    System.out.println(String.format("getPort %s", url.getPort()));
    System.out.println(String.format("getDefaultPort %s", url.getDefaultPort()));
    System.out.println(String.format("getQuery %s", url.getQuery()));
    System.out.println(String.format("getAuthority %s", url.getAuthority()));
    System.out.println(String.format("getRef %s", url.getRef()));
    System.out.println(String.format("getUserInfo %s", url.getUserInfo()));
    System.out.println(String.format("getFile %s", url.getFile()));
    System.out.println(String.format("getContent %s", url.getContent()));
    System.out.println(String.format("toExternalForm %s", url.toExternalForm()));
    System.out.println("---------------");

    return url;
  }
  public Vfs.Dir createDir(final URL url) {
    // Create non VFS Url
    final File deployment = PackagingUtil.identifyDeployment(url);
    if (null == deployment)
      throw new RuntimeException("Unable identify deployment file for: " + url);

    final File file = deployment.getAbsoluteFile();

    try {
      if (jbossAS) {
        try {
          if (url.getContent() instanceof VirtualFile) {
            return new JBossVfsDir(url);
          }
        } catch (IOException e) {
          throw new RuntimeException("error reading from VFS", e);
        }
      }

      final URL targetURL = file.toURI().toURL();

      // delegate unpacked archives to SystemDir handler
      if (deployment.isDirectory()) return new SystemDir(targetURL);

      // if it's a file delegate to ZipDir handler
      return new ZipDir(targetURL);
    } catch (MalformedURLException e) {
      throw new RuntimeException("Invalid URL", e);
    }
  }
 public static void main(String[] args) {
   Example4 ef = new Example4();
   try {
     final String molS = "C1C2=CC=CC=C2C3=C4CC5=CC=CC=C5C4=C6CC7=CC=CC=C7C6=C13";
     Molecule mol = MolImporter.importMol(molS);
     PolarizabilityPlugin plugin = new PolarizabilityPlugin();
     plugin.setMolecule(mol);
     plugin.run();
     ArrayList values = new ArrayList();
     java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
     nf.setMaximumFractionDigits(3);
     for (int i = 0; i < mol.getAtomCount(); i++) {
       values.add(Float.valueOf(nf.format(((Double) plugin.getResult(i)).floatValue())));
     }
     mol.hydrogenize(true);
     for (int i = 0; i < mol.getExplicitHcount(); i++) {
       values.add(new Double(0));
     }
     ef.setPlugin(plugin);
     JFrame frame = ef.createSpaceFrame(mol, values);
     frame.setTitle("Polarizability");
     java.net.URL u = ef.getClass().getResource("/chemaxon/marvin/space/gui/mspace16.gif");
     frame.setIconImage(
         Toolkit.getDefaultToolkit().createImage((java.awt.image.ImageProducer) u.getContent()));
     frame.setVisible(true);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #8
0
 /**
  * Reads the contents of a webpage to a string
  *
  * @param url the url to read
  * @return the contents of the webpage
  * @throws IOException if an error occurred during reading of the webpage
  */
 public static String readURLToString(URL url) throws IOException {
   HttpURLConnection http = (HttpURLConnection) url.openConnection();
   http.setConnectTimeout(10000);
   http.setReadTimeout(10000);
   http.connect();
   return http.getErrorStream() == null
       ? Utils.convertStreamToString((InputStream) url.getContent())
       : null;
 }
 public AudioClip getAudioClip(URL url) {
   // We don't currently support audio clips in the Beans.instantiate
   // applet context, unless by some luck there exists a URL content
   // class that can generate an AudioClip from the audio URL.
   try {
     return (AudioClip) url.getContent();
   } catch (Exception ex) {
     return null;
   }
 }
Example #10
0
 @Override
 public Image getImage(URL url) {
   Toolkit tk = Toolkit.getDefaultToolkit();
   try {
     ImageProducer prod = (ImageProducer) url.getContent();
     return tk.createImage(prod);
   } catch (IOException e) {
     return null;
   }
 }
 public ConfigFileTagProvider(URL url) {
   try {
     Object content = url.getContent();
     if (content instanceof InputStream) {
       InputStreamReader reader = new InputStreamReader((InputStream) content);
       new ConfigParser(this).parse(new InputSource(reader));
     }
   } catch (Exception e) {
     throw new HtmlCleanerException("Error parsing tag configuration file!", e);
   }
 }
  public Drawable getMapTileFromUrl(
      double minx, double miny, double maxx, double maxy, double size) {
    // Lade den druch die Parameter beschriebenen Kartenteil vom WMS
    // if (minx >= bb_minx && miny >= bb_miny && maxx <= bb_maxx && maxy <= bb_maxy)
    try {
      URL url =
          new URL(
              this.baseUrl
                  + "width="
                  + String.valueOf(size)
                  + "&height="
                  + String.valueOf(size)
                  + "&bbox="
                  + String.valueOf(minx)
                  + ","
                  + String.valueOf(miny)
                  + ","
                  + String.valueOf(maxx)
                  + ","
                  + String.valueOf(maxy));
      // URL url = new URL("http://hiu.kit.edu/img/kit_logo_de_farbe_positiv.jpg");

      Log.d("theUrl", url.toString());

      // Lazy way: Erlaube Netzwerkoperationen im Main-Thread (temporär!)
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);

      InputStream content = (InputStream) url.getContent();
      Drawable img = Drawable.createFromStream(content, "src");

      // Speichere Kartenstück in der HashMap, die ID wird durch die Koordinaten und die Größe
      // gegeben.
      imgCache.put(
          String.valueOf(minx)
              + ","
              + String.valueOf(miny)
              + ","
              + String.valueOf(maxx)
              + ","
              + String.valueOf(maxy)
              + ','
              + String.valueOf(size),
          img);
      return img;
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
 public static Drawable loadImageFromUrl(String url) {
   URL mURL;
   InputStream i = null;
   try {
     mURL = new URL(url);
     i = (InputStream) mURL.getContent();
   } catch (MalformedURLException e1) {
     e1.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   Drawable drawable = Drawable.createFromStream(i, "src");
   return drawable;
 }
Example #14
0
 void setIcon() {
   try {
     Image image;
     MediaTracker tracker = new MediaTracker(this);
     URL url = getClass().getResource("/images/mufficon.jpg");
     Object obj;
     if (url != null && ((obj = url.getContent()) instanceof ImageProducer)) {
       image = Toolkit.getDefaultToolkit().createImage((ImageProducer) obj);
       tracker.addImage(image, 1);
       tracker.waitForAll();
       setIconImage(image);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #15
0
  /**
   * Returns whether or not the pathname exists. If the pathname is a URL, then existence is
   * determined based on whether or not we can successfully read content from the URL.
   *
   * @see java.io.File#exists()
   */
  public boolean exists() {
    if (isURL) {
      try {
        url.getContent();
        return true;
      } catch (IOException e) {
        LOGGER.trace("Failed to retrieve content from URL", e);
        return false;
      }
    }
    if (file.exists()) return true;
    if (getMappedFile(file.getPath()) != null) return true;

    String mappedId = getMappedId(file.getPath());
    return mappedId != null && new File(mappedId).exists();
  }
Example #16
0
 public static Bitmap loadImageFromUrlToBitmap(String url) {
   if (url == null) {
     return null;
   }
   URL m;
   Bitmap bmp = null;
   InputStream i = null;
   try {
     m = new URL(url);
     i = (InputStream) m.getContent();
     bmp = BitmapFactory.decodeStream(i);
   } catch (MalformedURLException e1) {
     e1.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return bmp;
 }
 /**
  * This is where the bulk of our work is done. This function is called in a background thread and
  * should generate a new set of data to be published by the loader.
  */
 @Override
 public Bitmap loadInBackground() {
   InputStream inCoverURL = null;
   InputStream inCoverImage = null;
   Bitmap result = null;
   try {
     URL url = new URL(Constants.URL_GET_SEASON_IMAGES);
     URLConnection urlConnection = url.openConnection();
     urlConnection.addRequestProperty("Content-Type", "application/json");
     urlConnection.addRequestProperty("trakt-api-version", "2");
     urlConnection.addRequestProperty("trakt-api-key", Constants.CLIENT_ID);
     HttpURLConnection httpconnection = (HttpURLConnection) urlConnection;
     if (httpconnection.getResponseCode() == 200) {
       inCoverURL = new BufferedInputStream(urlConnection.getInputStream());
       String coverURL = readCoverURLStream(inCoverURL);
       url = new URL(coverURL);
       inCoverImage = (InputStream) url.getContent();
       result = readCoverImageStream(inCoverImage);
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (inCoverURL != null) {
       try {
         inCoverURL.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
     if (inCoverImage != null) {
       try {
         inCoverImage.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return result;
 }
Example #18
0
  public void init() {
    MediaTracker mt = new MediaTracker(this);

    URL url = getClass().getResource("tiger.gif");

    try {
      image = createImage((ImageProducer) url.getContent());
      mt.addImage(image, 0);
      mt.waitForID(0);
    } catch (Exception e) {
      e.printStackTrace();
    }
    imw = image.getWidth(this);
    imh = image.getWidth(this);
    pixels = new int[imw * imh];

    try {
      PixelGrabber pg = new PixelGrabber(image, 0, 0, imw, imh, pixels, 0, imw);
      pg.grabPixels();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    addMouseMotionListener(
        new MouseMotionAdapter() {
          public void mouseMoved(MouseEvent e) {
            int mx = e.getX(), my = e.getY();

            if (mx > 0 && mx < imw && my > 0 && my < imh) {
              int pixel = ((int[]) pixels)[my * imw + mx];

              int red = defaultRGB.getRed(pixel),
                  green = defaultRGB.getGreen(pixel),
                  blue = defaultRGB.getBlue(pixel),
                  alpha = defaultRGB.getAlpha(pixel);

              showStatus("red=" + red + " green=" + green + " blue=" + blue + " alpha=" + alpha);
            }
          }
        });
  }
 public Object fetch(String address) throws MalformedURLException, IOException {
   try {
     URL url = new URL(address);
     URI uri =
         new URI(
             url.getProtocol(),
             url.getUserInfo(),
             url.getHost(),
             url.getPort(),
             url.getPath(),
             url.getQuery(),
             url.getRef());
     url = uri.toURL();
     Log.i("Url:", url + "");
     Object content = url.getContent();
     return content;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
Example #20
0
  /**
   * A very handy utility method that reads the contents of a URL and returns them as a String.
   *
   * @param url
   * @return
   */
  public static String readContents(String url) {
    StringBuilder response = null;
    try {
      URL website = new URL(url);
      URLConnection connection = website.openConnection();
      String a = website.getContent().toString();
      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      response = new StringBuilder();
      String inputLine;

      while ((inputLine = in.readLine()) != null) response.append(inputLine);

      in.close();
    } catch (Exception e) {
      String a = e.getMessage();
      Log.i("the exception", a);
    }

    return response.toString();
  }
 public synchronized Image getImage(URL url) {
   Object o = imageCache.get(url);
   if (o != null) {
     return (Image) o;
   }
   try {
     o = url.getContent();
     if (o == null) {
       return null;
     }
     if (o instanceof Image) {
       imageCache.put(url, o);
       return (Image) o;
     }
     // Otherwise it must be an ImageProducer.
     Image img = target.createImage((java.awt.image.ImageProducer) o);
     imageCache.put(url, img);
     return img;
   } catch (Exception ex) {
     return null;
   }
 }
Example #22
0
  public String getOpenStreamHTML(String urlToRead) {
    String result = "";
    try {
      URL url = new URL(urlToRead);

      System.out.println("url=[" + url + "]");
      System.out.println("protocol=[" + url.getProtocol() + "]");
      System.out.println("host=[" + url.getHost() + "]");
      System.out.println("content=[" + url.getContent() + "]");

      InputStream is = url.openStream();
      int ch;
      while ((ch = is.read()) != -1) {
        System.out.print((char) ch);
        result += (char) ch;
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
  public static Drawable loadImageFromUrl(String url) {
    /** 加载网络图片 */
    URL m;
    InputStream i = null;
    try {
      m = new URL(url);
      i = (InputStream) m.getContent();
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    Drawable d = Drawable.createFromStream(i, "src");
    return d;

    //    	/**
    //    	 * 加载内存卡图片
    //    	 */
    //    	    Options options=new Options();
    //    	    options.inSampleSize=2;
    //    	    Bitmap bitmap=BitmapFactory.decodeFile(url, options);
    //    	    Drawable drawable=new BitmapDrawable(bitmap);
    //            return drawable;
  }
Example #24
0
  public void init() {
    MediaTracker mt = new MediaTracker(this); // 建立一个媒体跟踪器对象

    try {
      url = new URL("file:c:/1.jpg");
    } catch (MalformedURLException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } //

    // 实现完全加载图像
    try {
      im = createImage((ImageProducer) url.getContent()); //
      mt.addImage(im, 0);
      mt.waitForID(0);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // ----------------------
    ImageFilter filter = new CropImageFilter(110, 5, 100, 100); // 获取图片指定位置和大小

    FilteredImageSource fis = new FilteredImageSource(im.getSource(), filter);
    cropped = createImage(fis);
  }
 public Object fetch(String address) throws MalformedURLException, IOException {
   URL url = new URL(address);
   Object content = url.getContent();
   return content;
 }
  // This uses the key to get the entire record from the web page
  // For now the fields that compose the record will be hardcoded
  // but these fields need to be checked with the advertisement
  // in future releases. It then uses the parameter passed to it
  // to decide which fields to return
  // Also put's the field values in a Hashtable that can be later accessed
  private synchronized String getRecordFields(String key, String param) {

    fieldsTable = null;

    String city = new String(key);
    displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " + "city = " + city);

    // Add the URL extension corresponding to the city.
    StringBuffer sbuf = new StringBuffer();
    for (int i = 0; i < city.length(); i++) {
      char ch = city.charAt(i);
      if (ch != ' ' && ch != '\t' && ch != '\n') sbuf.append(ch);
    }
    String formURLString = siteURLString + new String(sbuf) + ".html";

    URL infoURL = null;
    try {
      infoURL = new URL(formURLString);
    } catch (MalformedURLException e) {
      displayMessage(
          "ERROR",
          "WCNForecastWeatherQueryFn::getRecordFields " + "Malformed URL " + formURLString);
      return null;
    }
    // displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    //	   "Got URL for site: " + formURLString);
    Object content = null;
    try {
      content = infoURL.getContent();
    } catch (IOException e) {
      displayMessage(
          "ERROR",
          "WCNForecastWeatherQueryFn::getRecordFields "
              + "Can't load content from "
              + formURLString);
      return null;
    }
    InputStreamReader input = new InputStreamReader((InputStream) content);
    BufferedReader reader = new BufferedReader(input);
    sbuf.setLength(0);
    boolean stillReading = true;
    char[] cbuf = new char[100000];
    int ccount = 0;
    long startTime = System.currentTimeMillis();
    while (stillReading) {
      try {
        ccount = reader.read(cbuf);
      } catch (IOException e) {
        displayMessage(
            "ERROR",
            "WCNForecastWeatherQueryFn::getRecordFields "
                + "IO error getting content from "
                + formURLString);
        return null;
      }
      if (ccount > 0) sbuf.append(cbuf, 0, ccount);
      if (ccount < 0) stillReading = false;
    }
    // displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    //	   "Time to read content: " + ((System.currentTimeMillis() - startTime) / 1000.0) +
    //            " seconds");
    String page = sbuf.toString();
    StringBuffer day = new StringBuffer();
    StringBuffer condition = new StringBuffer();

    int pos = page.indexOf("<!-- forecast include");
    int delimit;
    pos = page.indexOf("<TR>", pos);
    pos = page.indexOf("<TR>", pos + 1);
    pos = page.indexOf("<TR>", pos + 1);
    for (int n = 0; n < 10; n++) {
      pos = page.indexOf("<TR>", pos + 1);
      int daypos = page.indexOf("<BR>", pos) + 4;
      delimit = page.indexOf("</B>", daypos);
      day.append("(" + page.substring(daypos, delimit) + (n == 9 ? ")" : ") "));
      pos = page.indexOf("<FONT", daypos);
      int condpos = page.indexOf(">", pos) + 1;
      delimit = page.indexOf("</FONT>", condpos);
      condition.append("(" + page.substring(condpos, delimit) + (n == 9 ? ")" : ") "));
    }

    // Get the parser corresponding to the initial URL
    /*
       Parser infoParser = null;
       try {
         infoParser = new Parser(infoURL,true,display);
       } catch (Exception ex) {
         infoParser = null;
       }

       if (infoParser == null)     {
         displayMessage("ERROR",  "WCNForecastWeatherQueryFn::getRecordFields " +
    	     "Cannot initialize parser for page " + formURLString );
         return null ;
       }


       if (FILE_WRITE) {
         displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    	     "Site URL: " + formURLString +
    	     " Calling writeContent()." + FILE_WRITE_EXT_NUM);
         writeContent(infoParser.getContent());
       }


       displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    	   "ready to return record fields: " + param);

       displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    	   "city is: " + key);



       String ct = null;
       StringBuffer day = new StringBuffer();
       StringBuffer condition = new StringBuffer();
       String tag = null;

       while ((tag = infoParser.nextTag("NONE")) != null) {
         ct = infoParser.getContentBetween ();
         if ((ct == null) || (ct.length() == 0)) continue;
         ct = ct.replace('\n', ' ');
         ct = ct.replace('\r', ' ');
         if (ct.toLowerCase().indexOf("sunrise:") != -1) {
           tag = infoParser.nextTag("NONE");
    while (tag != null && !tag.equalsIgnoreCase("table"))
      tag = infoParser.nextTag("NONE");
    while (tag != null && !tag.equalsIgnoreCase("span"))
      tag = infoParser.nextTag("NONE");
           for ( int n = 0; n < 5; n++ ) {
             if (tag != null) {
               infoParser.removeContentBetween();
               tag = infoParser.nextTag("NONE");
               while (tag != null && !tag.equalsIgnoreCase("/span"))
                 tag = infoParser.nextTag("NONE");
               if (tag != null) {
                 day.append(infoParser.getContentBetween() + (n == 4 ? "" : " "));
                 tag = infoParser.nextTag("IMG");
                 while (tag != null && !tag.equalsIgnoreCase("img"))
                   tag = infoParser.nextTag("IMG");
                 if (tag != null)
                   condition.append(infoParser.getParameterValue("ALT") + (n == 4 ? "" : " "));
               }
             }
             tag = infoParser.nextTag("NONE");
             while (tag != null && !tag.equalsIgnoreCase("img"))
               tag = infoParser.nextTag("NONE");
             while (tag != null && !tag.equalsIgnoreCase("span"))
               tag = infoParser.nextTag("NONE");
             System.out.println("Content after condition = " + infoParser.getContentBetween());
           }
         }
         infoParser.removeContentBetween();
       }
       */

    // If we couldn't get at least a temperature from the page, it must
    // have been an invalid URL, ie.e, a city not in CNN database or
    // incorrectly spelled or designated.
    if (day == null) {
      displayMessage(
          "ERROR",
          "WCNForecastWeatherQueryFn::getRecordFields "
              + "URL "
              + formURLString
              + " is not a valid URL. "
              + "The \"CityCountry\" or \"CityState\" key may be wrong.");
      return null;
    }

    String weather =
        WEATHER_PERF_STRING
            + " "
            + ":"
            + DAY_STRING
            + " ("
            + day.toString()
            + ") "
            + ":"
            + CONDITION_STRING
            + " ("
            + condition.toString()
            + ")";

    if (param.equalsIgnoreCase(ALL_FIELDS)) {

      fieldsTable = new Hashtable();

      if (key != null) {
        fieldsTable.put(CITY_STRING, key);
      }
      if (day != null) {
        fieldsTable.put(DAY_STRING, day);
      }
      if (condition != null) {
        fieldsTable.put(CONDITION_STRING, condition);
      }
      if (formURLString != null) {
        fieldsTable.put(WEATHER_URL_STRING, formURLString);
      }

      if (key == null) {
        key = " ";
      }

      if (formURLString == null) {
        formURLString = " ";
      }

      String reply =
          "(reply :"
              + CITY_STRING
              + " ("
              + key
              + ") "
              + ":"
              + WEATHER_STRING
              + " ("
              + weather
              + ") "
              + ":"
              + WEATHER_URL_STRING
              + " ("
              + formURLString
              + "))";
      displayMessage(
          "DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " + "Weather is: " + reply);
      return reply;
    } else if (param.equalsIgnoreCase(CITY_STRING)) {
      fieldsTable = new Hashtable();
      fieldsTable.put(CITY_STRING, key);
      return key;
    } else if (param.equalsIgnoreCase(WEATHER_STRING)) {
      fieldsTable = new Hashtable();
      fieldsTable.put(WEATHER_STRING, weather);
      return weather;
    } else if (param.equalsIgnoreCase(WEATHER_URL_STRING)) {
      fieldsTable = new Hashtable();
      fieldsTable.put(WEATHER_URL_STRING, formURLString);
      return formURLString;
    } else {
      return null;
    }
  }
Example #27
0
 private static URL findResourceURL(
     IJavaProject javaProject, Set<IJavaProject> visited, boolean isFirstProject, String name) {
   if (visited.contains(javaProject)) return null;
   visited.add(javaProject);
   try {
     IPath outPath =
         javaProject
             .getProject()
             .getLocation()
             .removeLastSegments(1)
             .append(javaProject.getOutputLocation());
     outPath = outPath.addTrailingSeparator();
     {
       URL url = toURL(outPath.append(name));
       if (url != null) {
         return url;
       }
     }
     for (IPackageFragmentRoot fragment : javaProject.getPackageFragmentRoots()) {
       if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
         URL url = toURL(fragment.getResource().getLocation().append(name));
         if (url != null) {
           return url;
         }
       }
     }
     // urls.add(out);
     IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
     for (IClasspathEntry entry : entries) {
       switch (entry.getEntryKind()) {
         case IClasspathEntry.CPE_LIBRARY:
           {
             // TODO
             IClasspathEntry resolveEntry = JavaCore.getResolvedClasspathEntry(entry);
             File file = resolveEntry.getPath().toFile();
             IPath path = resolveEntry.getPath();
             if (!file.exists()) {
               String projectName = path.segment(0);
               IProject project =
                   javaProject.getProject().getWorkspace().getRoot().getProject(projectName);
               path = project.getLocation().append(path.removeFirstSegments(1));
             }
             String spec = "jar:file:" + path.toString() + "!/" + name;
             try {
               URL url2 = new URL(spec);
               url2.getContent();
               return url2;
             } catch (Exception e) {
             }
           }
           break;
         case IClasspathEntry.CPE_CONTAINER:
           break;
         case IClasspathEntry.CPE_VARIABLE:
           {
             {
               // TODO
               URL url = toURL(outPath.append(name));
               if (url != null) {
                 return url;
               }
             }
           }
           break;
         case IClasspathEntry.CPE_PROJECT:
           {
             if (isFirstProject || entry.isExported()) {
               URL url = findResourceURL(getJavaProject(entry), visited, false, name);
               if (url != null) {
                 return url;
               }
             }
             break;
           }
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #28
0
 void setIcon() throws Exception {
   URL url = this.getClass().getResource("/microscope.gif");
   if (url == null) return;
   Image img = createImage((ImageProducer) url.getContent());
   if (img != null) setIconImage(img);
 }
Example #29
0
  public static String getAuthorAuthorityWithWebservice(String author) throws IOException {
    if (loadedAuthorities.containsKey(author)) {
      return loadedAuthorities.get(author);
    }
    String authority = null;

    URL urlToCall =
        new URL(
            "http://viaf.org/viaf/search?query=local.names+%3D+%22"
                + URLEncoder.encode(author, "UTF-8")
                + "%22"
                +
                /*+AND+local.title%3D" + URLEncoder.encode(baseTitle, "UTF-8") +*/
                "+AND+local.sources%3D%22LC%22"
                + "&maximumRecords=25"
                + "&startRecord=1&sortKeys=holdingscount&httpAccept=text/xml");
    String responseXML = null;
    try {
      responseXML = VIAF.convertStreamToString((InputStream) urlToCall.getContent());
    } catch (Exception e) {
      logger.error("Unable to connect to VIAF", e);
    }

    // If we are getting the name in the 100/110 we can be a bit more sloppy to deal with
    // abbreviations, etc.
    String authorityMatching100 = null;
    double authorityMatch100Similarity = 0.45;
    // Need very good similarity to use related author
    String authorityMatching400 = null;
    double authorityMatch400Similarity = 0.7;
    if (responseXML != null) {
      // Parse the data as XML
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      try {
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader(responseXML)));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression recordExpression =
            xpath.compile("searchRetrieveResponse/records/record/recordData/VIAFCluster");
        XPathExpression mainHeadingExpression = xpath.compile("mainHeadings/mainHeadingEl");
        XPathExpression marc21Expression = xpath.compile("datafield[@dtype='MARC21']");
        XPathExpression sourcesExpression = xpath.compile("sources/s");
        XPathExpression subfieldExpression = xpath.compile("subfield[@code='a']");
        XPathExpression marc400FieldsExpression =
            xpath.compile("x400s/x400/datafield[@tag='400']/subfield[@code='a']");

        // Get the returned records
        NodeList records = (NodeList) recordExpression.evaluate(doc, XPathConstants.NODESET);
        for (int h = 0; h < records.getLength(); h++) {
          Node curRecord = records.item(h);
          // Get main headings for the response
          NodeList mainHeadings =
              (NodeList) mainHeadingExpression.evaluate(curRecord, XPathConstants.NODESET);
          for (int i = 0; i < mainHeadings.getLength(); i++) {
            // Look through all nodes to get 100 or 110 fields.
            Node curMainHeading = mainHeadings.item(i);
            NodeList marc21DataFields =
                (NodeList) marc21Expression.evaluate(curMainHeading, XPathConstants.NODESET);
            for (int j = 0; j < marc21DataFields.getLength(); j++) {
              Element curField = (Element) marc21DataFields.item(j);
              if (curField.hasAttribute("tag")) {
                String tag = curField.getAttribute("tag");
                if (tag.equals("100") || tag.equals("110")) {
                  // Keep processing
                  boolean isValidSource = true;
                  /*NodeList sources = (NodeList)sourcesExpression.evaluate(curMainHeading, XPathConstants.NODESET);
                  for (int k = 0; k < sources.getLength(); k++){
                  	String curSource = ((Element)sources.item(k)).getTextContent();
                  	if (curSource.equals("LC")){
                  		//This is an authority we can use (at least so far)
                  		isValidSource = true;
                  		break;
                  	}
                  }*/

                  if (isValidSource) {
                    String tempAuthority =
                        (String) subfieldExpression.evaluate(curField, XPathConstants.STRING);
                    if (tempAuthority.endsWith(",")) {
                      tempAuthority = tempAuthority.substring(0, tempAuthority.length() - 1);
                    }
                    // We can use it if at least one word we passed in is in this authority
                    double matchSimilarity = StringSimilarity.similarity(author, tempAuthority);
                    if (matchSimilarity > authorityMatch100Similarity) {
                      authorityMatching100 = tempAuthority;
                      authorityMatch100Similarity = matchSimilarity;
                      if (authorityMatch100Similarity >= 0.99) {
                        break;
                      }
                    }

                    // Or we can use it if the term we passed in is located in the 400 fields
                    // Get a list of 400 fields
                    NodeList marc400Fields =
                        (NodeList)
                            marc400FieldsExpression.evaluate(curRecord, XPathConstants.NODESET);
                    for (int k = 0; k < marc400Fields.getLength(); k++) {
                      Node curMarc400 = marc400Fields.item(k);
                      String relatedName = curMarc400.getTextContent();
                      if (relatedName.endsWith(",")) {
                        relatedName = relatedName.substring(0, relatedName.length() - 1);
                      }
                      double matchSimilarity400 = StringSimilarity.similarity(author, relatedName);
                      if (matchSimilarity400 > authorityMatch400Similarity) {
                        authorityMatching400 = tempAuthority;
                        authorityMatch400Similarity = matchSimilarity400;
                      }
                    }
                  }
                }
              }
            }
            // Yeah, we have a valid authority, be done
            if (authorityMatch100Similarity >= 0.99) {
              break;
            }
          }
          // Yeah, we have a valid authority, be done
          if (authorityMatch100Similarity >= 0.99) {
            break;
          }
        }
      } catch (Exception e) {
        logger.error("Error parsing XML for VIAF record", e);
      }
    }

    if (authorityMatching100 != null && authorityMatching400 != null) {
      if (authorityMatch100Similarity >= authorityMatch400Similarity) {
        authority = authorityMatching100;
      } else {
        authority = authorityMatching400;
      }
    } else if (authorityMatching100 != null) {
      authority = authorityMatching100;
    } else if (authorityMatching400 != null) {
      authority = authorityMatching400;
    }

    /*if (authority != null){
    	if (authorityMatch100Similarity <= 0.9999999)
    	logger.debug("For author " + author + " preferred name is " + authority + " authorityMatch100Similarity = " + authorityMatch100Similarity + " authorityMatch400Similarity = " + authorityMatch400Similarity);
    }else{
    	logger.debug("No authority found for author " + author);
    }*/
    loadedAuthorities.put(author, authority);
    return authority;
  }
Example #30
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.coupon);

    Bundle b = getIntent().getExtras();
    couponId = b.getInt("id");

    imgCoupon = (ImageView) findViewById(R.id.imgCoupon);
    txtBrandName = (TextView) findViewById(R.id.txtBrandName);
    txtTitle = (TextView) findViewById(R.id.txtTitle);
    txtDescription = (TextView) findViewById(R.id.txtDescription);
    seekBarCheckIn = (SeekBar) findViewById(R.id.seekBarCheckIn);
    seekBarCheckIn.setOnSeekBarChangeListener(this);
    btnEndDate = (RelativeLayout) findViewById(R.id.btnEndDate);
    btnEndDate.setOnClickListener(this);
    btnFav = (RelativeLayout) findViewById(R.id.btnFav);
    btnFav.setOnClickListener(this);
    btnLocation = (RelativeLayout) findViewById(R.id.btnLocation);
    btnLocation.setOnClickListener(this);
    btnUsage = (RelativeLayout) findViewById(R.id.btnUsage);
    btnUsage.setOnClickListener(this);
    btnInfo = (RelativeLayout) findViewById(R.id.btnInfo);
    btnInfo.setOnClickListener(this);
    btnTerms = (RelativeLayout) findViewById(R.id.btnTerms);
    btnTerms.setOnClickListener(this);

    txtEndDate = (TextView) findViewById(R.id.txtEndDate);
    txtEndDate2 = (TextView) findViewById(R.id.txtEndDate2);
    txtFav = (TextView) findViewById(R.id.txtFav);
    imgFavOn = (ImageView) findViewById(R.id.imgFavOn);
    imgFavOff = (ImageView) findViewById(R.id.imgFavOff);
    txtLocation = (TextView) findViewById(R.id.txtLocation);
    txtLocation2 = (TextView) findViewById(R.id.txtLocation2);
    txtUsage = (TextView) findViewById(R.id.txtUsage);
    linearLayoutCheckIn = (LinearLayout) findViewById(R.id.linearLayoutCheckIn);
    txtCouponCodeTitle = (TextView) findViewById(R.id.txtCouponCodeTitle);
    txtCouponCode = (TextView) findViewById(R.id.txtCouponCode);

    dialogDate = new Dialog(this);
    dialogDate.setContentView(R.layout.dialog_coupon_date);
    dialogDate.setTitle("Dates");
    dialogDate.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
    dialogLocation = new Dialog(this);
    dialogLocation.setContentView(R.layout.dialog_coupon_location);
    dialogLocation.setTitle("Location");
    dialogLocation.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
    dialogUsage = new Dialog(this);
    dialogUsage.setContentView(R.layout.dialog_coupon_usage);
    dialogUsage.setTitle("Usage");
    dialogUsage.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
    dialogInfo = new Dialog(this);
    dialogInfo.setContentView(R.layout.dialog_coupon_info);
    dialogInfo.setTitle("Information");
    dialogInfo.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
    dialogTerms = new Dialog(this);
    dialogTerms.setContentView(R.layout.dialog_coupon_terms);
    dialogTerms.setTitle("Terms and Conditions");
    dialogTerms.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
    dialogCheckIn = new Dialog(this);
    dialogCheckIn.setContentView(R.layout.dialog_coupon_checkin);
    dialogCheckIn.setTitle("Check In");
    dialogCheckIn.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;

    if (couponId > 0) {
      cb =
          RestClient.getCoupon(
              couponId,
              SessionUserBean.getId(),
              SessionUserBean.getLat(),
              SessionUserBean.getLng());

      URL url;
      try {
        url = new URL(cb.getImage());
        brandName = cb.getBrandName();
        branchAddress = cb.getBranchAddress();
        couponLat = "" + cb.getLat();
        couponLng = "" + cb.getLng();
        InputStream content = (InputStream) url.getContent();
        Drawable drawable = Drawable.createFromStream(content, "src");
        imgCoupon.setImageDrawable(drawable);
        txtBrandName.setText(cb.getBrandName());
        txtTitle.setText(cb.getName() + " in " + cb.getBranchName());
        txtDescription.setText(cb.getDescription());
        if (cb.getCheckinDateTime() != null) {
          txtEndDate2.setText("Checked In");
          txtEndDate.setText(Util.formatDate(cb.getCheckinDateTime()));
          seekBarCheckIn.setVisibility(View.INVISIBLE);
          linearLayoutCheckIn.setVisibility(View.GONE);
          txtCouponCodeTitle.setVisibility(View.VISIBLE);
          txtCouponCode.setVisibility(View.VISIBLE);
          txtCouponCode.setText(cb.getCouponCode());

        } else {
          txtEndDate.setText(Util.formatDate(cb.getEndDateTime()));
        }
        txtFav.setText(cb.getFavCouponCount() + " times favorited");
        if (cb.isFavorited()) {
          imgFavOn.setVisibility(View.VISIBLE);
          imgFavOff.setVisibility(View.INVISIBLE);
        } else {
          imgFavOn.setVisibility(View.INVISIBLE);
          imgFavOff.setVisibility(View.VISIBLE);
        }

        txtLocation.setText(Util.formatDoubleValue(cb.getDistance() * 1000, 0) + " meters");
        txtLocation2.setText(cb.getBranchDistrict());
        txtUsage.setText("" + cb.getUserCouponCount());
        TextView txtLocationDialogAddress = (TextView) dialogLocation.findViewById(R.id.txtAddress);
        txtLocationDialogAddress.setText(cb.getBranchAddress());
        TextView txtLocationDialogDistance =
            (TextView) dialogLocation.findViewById(R.id.txtDistance);
        txtLocationDialogDistance.setText(
            Util.formatDoubleValue(cb.getDistance() * 1000, 0) + " meters");
        TextView txtLocationDialogLatLng = (TextView) dialogLocation.findViewById(R.id.txtLatLng);
        txtLocationDialogLatLng.setText("Latitude:" + cb.getLat() + " Longitude:" + cb.getLng());
        txtDialogUsage = (TextView) dialogUsage.findViewById(R.id.txtDialogUsage);
        txtDialogUsage.setText("" + cb.getUserCouponCount());
        txtDialogInfo = (TextView) dialogInfo.findViewById(R.id.txtDialogInfo);
        txtDialogInfo.setText(cb.getDetail());

      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }