예제 #1
1
  public static String submitPostData(String pos, String data) throws IOException {
    Log.v("req", data);

    URL url = new URL(urlPre + pos);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    configConnection(connection);
    if (sCookie != null && sCookie.length() > 0) {
      connection.setRequestProperty("Cookie", sCookie);
    }
    connection.connect();

    // Send data
    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    output.write(data.getBytes());
    output.flush();
    output.close();

    // check Cookie
    String cookie = connection.getHeaderField("set-cookie");
    if (cookie != null && !cookie.equals(sCookie)) {
      sCookie = cookie;
    }

    // Respond
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    connection.disconnect();
    String res = sb.toString();
    Log.v("res", res);
    return res;
  }
 private void performHttpCall(String host, int port, String path, String expected)
     throws IOException {
   URLConnection conn = null;
   InputStream in = null;
   StringWriter writer = new StringWriter();
   try {
     URL url =
         new URL(
             "http://"
                 + TestSuiteEnvironment.formatPossibleIpv6Address(host)
                 + ":"
                 + port
                 + "/"
                 + path);
     // System.out.println("Reading response from " + url + ":");
     conn = url.openConnection();
     conn.setDoInput(true);
     in = new BufferedInputStream(conn.getInputStream());
     int i = in.read();
     while (i != -1) {
       writer.write((char) i);
       i = in.read();
     }
     assertTrue((writer.toString().indexOf(expected) > -1));
     // System.out.println("OK");
   } finally {
     safeClose(in);
     safeClose(writer);
   }
 }
예제 #3
1
  public void makeRequest() {
    java.net.URL url;
    try {
      if (validateConnection()) {
        url = new URL(URL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(methodConnection);
        connection.setRequestProperty("Content-Type", TYPE_JSON);
        connection.setConnectTimeout(TIMEOUT);
        if ((methodConnection.equals(POST) || methodConnection.equals(PUT)) && params != null)
          configBody(params);

        if (headerParams != null) processHeader();

        processReturn();
        postExecute(response != null ? response.toString() : null);
      } else {
        error(new MessageResponse("Sem conexão com a internet", false));
      }
    } catch (Exception e) {
      if (e instanceof ConnectTimeoutException || e instanceof ConnectException)
        messageResponse.setMsg("Problemas ao tentar conectar com o servidor.");
      else if (e instanceof NullPointerException)
        messageResponse.setMsg("Humm, algo de errado deve ter acontecido com o servidor.");
      else messageResponse.setMsg(e.getMessage());
      error(messageResponse);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
예제 #4
0
  public RSAPublicKey toRSAPublicKey()
      throws MalformedURLException, FileNotFoundException, InvalidCsrException,
          InvalidKeyException {
    AppFactory appFactory = new AppFactory();
    CSRToRSAPublicKey csrToRSAPublicKey = appFactory.csrToRSAPublicKey();

    URL privateKeyURL = null;
    try {
      privateKeyURL = new URL("file:///example/rsa-cert.csr");
    } catch (MalformedURLException e) {
      // invalid url.
      throw e;
    }

    FileReader fr = null;
    try {
      fr = new FileReader(privateKeyURL.getFile());
    } catch (FileNotFoundException e) {
      throw e;
    }

    RSAPublicKey rsaPublicKey = null;
    try {
      rsaPublicKey = csrToRSAPublicKey.translate(fr, Optional.of("test-key-id"), Use.SIGNATURE);
    } catch (InvalidCsrException e) {
      // csr file could not be used.
      throw e;
    } catch (InvalidKeyException e) {
      // key in the csr file could not be used.
      throw e;
    }

    return rsaPublicKey;
  }
예제 #5
0
  /**
   * Retrieve a list of name-script key-value pairs.
   *
   * @return
   */
  public final Map<String, String> loadScripts() {
    HashMap<String, String> scripts = new HashMap<String, String>();
    try {
      URL url = this.getClass().getClassLoader().getResource(this.directory);
      if (url == null) {
        throw new RuntimeException("The following directory was not found: " + this.directory);
      }

      URI uri = new URI(url.toString());

      File directory = new File(uri);
      FilenameFilter filter = new JavascriptFilter();

      for (String file : directory.list(filter)) {
        String script = this.readScript(directory, file);

        int dotIndex = file.lastIndexOf('.');
        scripts.put(file.substring(0, dotIndex), script.toString());
      }
    } catch (URISyntaxException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    return scripts;
  }
예제 #6
0
  private String getData(String url, String data) throws WasabiNetClientException {

    StringBuffer sb = new StringBuffer();

    try {
      URL dest = new URL(url);
      URLConnection conn = dest.openConnection();

      conn.setDoOutput(true);

      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF8");
      System.out.println(writer.getEncoding());
      writer.write(data);
      writer.flush();

      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

      char[] buf = new char[MAX_READ];
      int readed = 0;
      while ((readed = reader.read(buf)) > 0) {
        sb.append(buf, 0, readed);
      }

    } catch (MalformedURLException ex) {
      Logger.getLogger(WasabiNetClient.class.getName()).log(Level.SEVERE, null, ex);
      throw new WasabiNetClientException(
          "Error al conectar con la url <" + url + ">:" + ex.getMessage());
    } catch (IOException ex) {
      Logger.getLogger(WasabiNetClient.class.getName()).log(Level.SEVERE, null, ex);
      throw new WasabiNetClientException("Error de lectura/escritura:" + ex.getMessage());
    }

    return sb.toString();
  }
예제 #7
0
  public static void downloadIt() {
    URL website;
    try {
      website = new URL(MainConstants.SOURCES_URL);

      try {
        InputStream in = new BufferedInputStream(website.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
          out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();
        FileOutputStream fos = new FileOutputStream(MainConstants.INPUT_ZIP_FILE);
        fos.write(response);
        fos.close();
        System.out.println("Download finished.");
      } catch (IOException ce) {
        System.out.print("Connection problem : " + ce);
      }

    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }
예제 #8
0
  /**
   * Utility method used to fetch Class list based on a package name.
   *
   * @param packageName The package name containing the annotated classes
   * @return A list of classes within the given package
   * @throws ClassNotFoundException If something goes wrong
   */
  private List<Class> getClasses(String packageName) throws ClassNotFoundException {
    List<Class> classes = new ArrayList<Class>();
    File directory = null;
    try {
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      if (classLoader == null) {
        throw new ClassNotFoundException("No class loader");
      }
      String path = packageName.replace('.', '/');
      URL resource = classLoader.getResource(path);
      if (resource == null) {
        throw new ClassNotFoundException("No resource for " + path);
      }
      directory = new File(resource.getFile());
    } catch (NullPointerException x) {
      throw new ClassNotFoundException(
          packageName + " (" + directory + ") does not appear to be a valid package");
    }
    if (directory.exists()) {
      String[] files = directory.list();
      for (int i = 0; i < files.length; i++) {
        if (files[i].endsWith(".class")) {
          // removes the .class extension
          classes.add(
              Class.forName(packageName + '.' + files[i].substring(0, files[i].length() - 6)));
        }
      }
    } else {
      throw new ClassNotFoundException(packageName + " is not a valid package");
    }

    return classes;
  }
예제 #9
0
  void registerImage(URL imageURL) {
    if (loadedImages.containsKey(imageURL)) {
      return;
    }

    SoftReference ref;
    try {
      String fileName = imageURL.getFile();
      if (".svg".equals(fileName.substring(fileName.length() - 4).toLowerCase())) {
        SVGIcon icon = new SVGIcon();
        icon.setSvgURI(imageURL.toURI());

        BufferedImage img =
            new BufferedImage(
                icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        icon.paintIcon(null, g, 0, 0);
        g.dispose();
        ref = new SoftReference(img);
      } else {
        BufferedImage img = ImageIO.read(imageURL);
        ref = new SoftReference(img);
      }
      loadedImages.put(imageURL, ref);
    } catch (Exception e) {
      Logger.getLogger(SVGConst.SVG_LOGGER)
          .log(Level.WARNING, "Could not load image: " + imageURL, e);
    }
  }
 static {
   try {
     logger =
         Logger.getLogger(
             "au.com.leighton.portal.peoplefinder.model.peopledetail.Phogetpersondetail_client_ep");
     URL baseUrl = Phogetpersondetail_client_ep.class.getResource(".");
     if (baseUrl == null) {
       wsdlLocationURL =
           Phogetpersondetail_client_ep.class.getResource(
               "http://lclxsoa11gdev.lc.local:7001/soa-infra/services/default/PhoGetPersonDetail/phogetpersondetail_client_ep?WSDL");
       if (wsdlLocationURL == null) {
         baseUrl = new File(".").toURL();
         wsdlLocationURL =
             new URL(
                 baseUrl,
                 "http://lclxsoa11gdev.lc.local:7001/soa-infra/services/default/PhoGetPersonDetail/phogetpersondetail_client_ep?WSDL");
       }
     } else {
       if (!baseUrl.getPath().endsWith("/")) {
         baseUrl = new URL(baseUrl, baseUrl.getPath() + "/");
       }
       wsdlLocationURL =
           new URL(
               baseUrl,
               "http://lclxsoa11gdev.lc.local:7001/soa-infra/services/default/PhoGetPersonDetail/phogetpersondetail_client_ep?WSDL");
     }
   } catch (MalformedURLException e) {
     logger.log(
         Level.ALL,
         "Failed to create wsdlLocationURL using http://lclxsoa11gdev.lc.local:7001/soa-infra/services/default/PhoGetPersonDetail/phogetpersondetail_client_ep?WSDL",
         e);
   }
 }
예제 #11
0
  protected Set<Class> processJarUrl(URL url, String basepath, Class clazz) throws IOException {
    Set<Class> set = new HashSet<Class>();
    String path = url.getFile().substring(5, url.getFile().indexOf("!"));
    JarFile jar = new JarFile(path);

    for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) {
      JarEntry entry = (JarEntry) entries.nextElement();
      if (entry.getName().startsWith(basepath) && entry.getName().endsWith(".class")) {
        try {
          String name = entry.getName();
          // Ignore anonymous
          // TODO RM what about the other anonymous classes like $2, $3 ?
          if (name.contains("$1")) {
            continue;
          }
          URL classURL = classLoader.getResource(name);
          ClassReader reader = new ClassReader(classURL.openStream());
          ClassScanner visitor = getScanner(clazz);
          reader.accept(visitor, 0);
          if (visitor.isMatch()) {
            Class c = loadClass(visitor.getClassName());
            if (c != null) {
              set.add(c);
            }
          }
        } catch (Exception e) {
          if (logger.isDebugEnabled()) {
            Throwable t = ExceptionHelper.getRootException(e);
            logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString()));
          }
        }
      }
    }
    return set;
  }
예제 #12
0
 private static File loadResource(String resourceName) {
   final URL resource = HdfsOverFtpServer.class.getResource(resourceName);
   if (resource == null) {
     throw new RuntimeException("Resource not found: " + resourceName);
   }
   return new File(resource.getFile());
 }
예제 #13
0
 private void onRequestUpload() {
   if (tempAttachments.size() < 3) {
     FileChooser fileChooser = new FileChooser();
     fileChooser.setTitle("Open file to attach");
     /* if (Utilities.isUnix())
     fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));*/
     File result = fileChooser.showOpenDialog(stage);
     if (result != null) {
       try {
         URL url = result.toURI().toURL();
         try (InputStream inputStream = url.openStream()) {
           byte[] filesAsBytes = ByteStreams.toByteArray(inputStream);
           if (filesAsBytes.length <= Connection.getMaxMsgSize()) {
             tempAttachments.add(
                 new DisputeDirectMessage.Attachment(result.getName(), filesAsBytes));
             inputTextArea.setText(
                 inputTextArea.getText() + "\n[Attachment " + result.getName() + "]");
           } else {
             new Popup().error("The max. allowed file size is 100 kB.").show();
           }
         } catch (java.io.IOException e) {
           e.printStackTrace();
           log.error(e.getMessage());
         }
       } catch (MalformedURLException e2) {
         e2.printStackTrace();
         log.error(e2.getMessage());
       }
     }
   } else {
     new Popup().error("You cannot send more then 3 attachments in one message.").show();
   }
 }
 static {
   try {
     logger =
         Logger.getLogger("co.com.losalpes.marketplace.ws.avisoDespacho.Dispatchadvice_client_ep");
     URL baseUrl = Dispatchadvice_client_ep.class.getResource(".");
     if (baseUrl == null) {
       wsdlLocationURL =
           Dispatchadvice_client_ep.class.getResource(
               "http://portal.marketplace.losalpes.com.co:7001/soa-infra/services/default/ProcesoAvisoDespacho/dispatchadvice_client_ep?WSDL");
       if (wsdlLocationURL == null) {
         baseUrl = new File(".").toURL();
         wsdlLocationURL =
             new URL(
                 baseUrl,
                 "http://portal.marketplace.losalpes.com.co:7001/soa-infra/services/default/ProcesoAvisoDespacho/dispatchadvice_client_ep?WSDL");
       }
     } else {
       if (!baseUrl.getPath().endsWith("/")) {
         baseUrl = new URL(baseUrl, baseUrl.getPath() + "/");
       }
       wsdlLocationURL =
           new URL(
               baseUrl,
               "http://portal.marketplace.losalpes.com.co:7001/soa-infra/services/default/ProcesoAvisoDespacho/dispatchadvice_client_ep?WSDL");
     }
   } catch (MalformedURLException e) {
     logger.log(
         Level.ALL,
         "Failed to create wsdlLocationURL using http://portal.marketplace.losalpes.com.co:7001/soa-infra/services/default/ProcesoAvisoDespacho/dispatchadvice_client_ep?WSDL",
         e);
   }
 }
예제 #15
0
 private static String getContextPath(ServletContext context) {
   // cette m茅thode retourne le contextPath de la webapp
   // en utilisant ServletContext.getContextPath si servlet api 2.5
   // ou en se d茅brouillant sinon
   // (on n'a pas encore pour l'instant de request pour appeler HttpServletRequest.getContextPath)
   if (context.getMajorVersion() == 2 && context.getMinorVersion() >= 5
       || context.getMajorVersion() > 2) {
     // api servlet 2.5 (Java EE 5) minimum pour appeler ServletContext.getContextPath
     return context.getContextPath();
   }
   URL webXmlUrl;
   try {
     webXmlUrl = context.getResource("/WEB-INF/web.xml");
   } catch (final MalformedURLException e) {
     throw new IllegalStateException(e);
   }
   String contextPath = webXmlUrl.toExternalForm();
   contextPath = contextPath.substring(0, contextPath.indexOf("/WEB-INF/web.xml"));
   final int indexOfWar = contextPath.indexOf(".war");
   if (indexOfWar > 0) {
     contextPath = contextPath.substring(0, indexOfWar);
   }
   // tomcat peut renvoyer une url commen莽ant pas "jndi:/localhost"
   // (v5.5.28, webapp dans un r茅pertoire)
   if (contextPath.startsWith("jndi:/localhost")) {
     contextPath = contextPath.substring("jndi:/localhost".length());
   }
   final int lastIndexOfSlash = contextPath.lastIndexOf('/');
   if (lastIndexOfSlash != -1) {
     contextPath = contextPath.substring(lastIndexOfSlash);
   }
   return contextPath;
 }
예제 #16
0
 public static Reader communicate(final String urlStr, final CharSequence toSend) {
   OutputStream outputStream = null;
   try {
     final URL url = new URL(urlStr);
     final URLConnection urlConnection = url.openConnection();
     urlConnection.setDoOutput(true);
     urlConnection.setDoInput(true);
     outputStream = urlConnection.getOutputStream();
     final OutputStreamWriter writer =
         new OutputStreamWriter(outputStream, DEFAULT_CHARSET.name());
     writer.append(toSend);
     writer.close();
     return new InputStreamReader(urlConnection.getInputStream(), DEFAULT_CHARSET.name());
   } catch (IOException e) {
     LOG.warn("exception caught", e);
   } finally {
     if (outputStream != null) {
       try {
         outputStream.close();
       } catch (IOException e) {
         LOG.warn("exception caught", e);
       }
     }
   }
   return null;
 }
예제 #17
0
 /**
  * @param Codebase String
  * @param hashList Hashtable
  * @param US UpdateStub
  * @return Object
  */
 private static Object downloadFile(String Codebase, Hashtable hashList, UpdateStub US) {
   int size = US.getInt("remotesize", 0);
   String LocalFileName = getLocalFileURI(hashList, US);
   String RemoteFileName = getRemoteFileURI(Codebase, US);
   File file = getLocalFile(LocalFileName);
   URL url = getRemoteFileURL(RemoteFileName);
   BasicNetworkLayer basicLayer = new BasicNetworkLayer();
   BasicDownloadLayer downloadFile = new BasicDownloadLayer(basicLayer);
   try {
     System.out.print("downloading:" + url.toString());
     downloadFile.download(url, file, null);
     file.setLastModified(Long.parseLong(US.getRemoteTime()));
     System.out.println(" is finish!");
   } catch (Exception e) {
     System.out.println("downloading:" + url.toString() + " is error!");
     file.delete();
     e.printStackTrace();
     if (e.getMessage() == null) {
       return e.getCause();
     }
     return e;
     //      e.printStackTrace();
   }
   return null;
   //    for(int i=0;i<size;i++) {
   //      pnSecond.setValue(i+1);
   //      this.lbTitle3.setText(US.toString()+" "+ String.valueOf(i+1)+"/"+String.valueOf(size));
   //    }
 }
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
          String stringValue = value.toString();

          if (preference instanceof ListPreference) {
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);
            preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
          } else {
            preference.setSummary(stringValue);
          }

          // detect errors
          if (preference.getKey().equals("sos_uri")) {
            try {
              URL url = new URL(value.toString());
              if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https"))
                throw new Exception("SOS URL must be HTTP or HTTPS");
            } catch (Exception e) {
              AlertDialog.Builder dlgAlert = new AlertDialog.Builder(preference.getContext());
              dlgAlert.setMessage("Invalid SOS URL");
              dlgAlert.setTitle(e.getMessage());
              dlgAlert.setPositiveButton("OK", null);
              dlgAlert.setCancelable(true);
              dlgAlert.create().show();
            }
          }

          return true;
        }
예제 #19
0
    @Override
    protected Bitmap doInBackground(String... urls) {

      try {
        URL url = new URL(urls[0]);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // download then convert
        connection.connect();

        InputStream inputStream = connection.getInputStream();

        Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);

        return myBitmap;

      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      return null;
    }
  /** Load config. */
  private void loadConfig() {
    try {

      if (properties.isEmpty()) {
        URL url = new URL(this.getCodeBase(), Constants.FTP_CONFIG_FILE_NAME);
        URLConnection uc = url.openConnection();
        properties.load(uc.getInputStream());
      }

      List<FtpConfig> ftpConfigs =
          JSON.parseObject(
              properties.getProperty(Constants.FTP_CONFIGS),
              new TypeReference<List<FtpConfig>>() {});
      int cfgIndex = (int) (Math.random() * (ftpConfigs.size() - 1));
      this.ftpConfig = ftpConfigs.get(cfgIndex);
      this.separator = ftpConfig.getOs() == OS.WINDOWS ? "\\" : "/";

      if (messageSource.isEmpty()) {
        URL murl = new URL(this.getCodeBase(), Constants.MESSAGE_SOURCE_NAME);
        URLConnection muc = murl.openConnection();
        messageSource.load(muc.getInputStream());
      }
    } catch (IOException e) {
      JOptionPane.showMessageDialog(this, getMessage(MessageCode.FTP_CONFIG_ERROR));
    }
  }
예제 #21
0
 /**
  * 获取网络上的文件
  *
  * @param URLName 地址
  * @throws Exception
  */
 public static byte[] getURLFile(String urlFile) throws Exception {
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int HttpResult = 0; // 服务器返回的状态
   URL url = new URL(urlFile); // 创建URL
   URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码urlconn.connect();
   HttpURLConnection httpconn = (HttpURLConnection) urlconn;
   HttpResult = httpconn.getResponseCode();
   if (HttpResult != HttpURLConnection.HTTP_OK) { // 不等于HTTP_OK说明连接不成功
     System.out.print("连接失败!");
   } else {
     BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());
     BufferedOutputStream bos = new BufferedOutputStream(os);
     byte[] buffer = new byte[1024]; // 创建存放输入流的缓冲
     int num = -1; // 读入的字节数
     while (true) {
       num = bis.read(buffer); // 读入到缓冲区
       if (num == -1) {
         bos.flush();
         break; // 已经读完
       }
       bos.flush();
       bos.write(buffer, 0, num);
     }
     bos.close();
     bis.close();
   }
   return os.toByteArray();
 }
예제 #22
0
 @Test
 public void getUrlStream() throws Exception {
   URL url = this.jarFile.getUrl();
   url.openConnection();
   this.thrown.expect(IOException.class);
   url.openStream();
 }
예제 #23
0
    @Override
    public Void doInBackground(String... params) {
      HttpsURLConnection connection = null;

      try {
        URL url = new URL(SEARCH_URL + params[0]);
        Log.d("****URL:", url.toString());
        connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", "JustDoIt");
        connection.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
        connection.setUseCaches(false);

        JSONObject obj = new JSONObject(ReadResponse.readResponse(connection));

        buildTweets(obj);

        Log.d("***GetTweets:", obj.toString());

      } catch (MalformedURLException e) {
        Log.e("***GetTweets", "Invalid endpoint URL specified.", e);

      } catch (IOException e) {
        Log.e("***GetTweets", "IOException: ", e);
      } catch (JSONException e) {
        e.printStackTrace();
      } finally {
        if (connection != null) {
          connection.disconnect();
        }
        lock.release();
      }
      return null;
    }
예제 #24
0
 /** Populate recent bookmarks. */
 public void populateRecentBookmarks() {
   JMenu bookmarksMenu = this.recentBookmarksMenu;
   bookmarksMenu.removeAll();
   Collection<HistoryEntry<BookmarkInfo>> historyEntries =
       BookmarksHistory.getInstance().getRecentEntries(PREFERRED_MAX_MENU_SIZE);
   for (HistoryEntry<BookmarkInfo> hentry : historyEntries) {
     BookmarkInfo binfo = hentry.getItemInfo();
     String text = binfo.getTitle();
     URL url = binfo.getUrl();
     String urlText = url.toExternalForm();
     if ((text == null) || (text.length() == 0)) {
       text = urlText;
     }
     long elapsed = System.currentTimeMillis() - hentry.getTimetstamp();
     text = text + " (" + Timing.getElapsedText(elapsed) + " ago)";
     Action action = this.actionPool.createBookmarkNavigateAction(url);
     JMenuItem menuItem = ComponentSource.menuItem(text, action);
     StringBuffer toolTipText = new StringBuffer();
     toolTipText.append("<html>");
     toolTipText.append(urlText);
     String description = binfo.getDescription();
     if ((description != null) && (description.length() != 0)) {
       toolTipText.append("<br>");
       toolTipText.append(description);
     }
     menuItem.setToolTipText(toolTipText.toString());
     bookmarksMenu.add(menuItem);
   }
 }
예제 #25
0
 @Test
 public void getMissingEntryUrl() throws Exception {
   URL url = new URL(this.jarFile.getUrl(), "missing.dat");
   assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat");
   this.thrown.expect(FileNotFoundException.class);
   ((JarURLConnection) url.openConnection()).getJarEntry();
 }
예제 #26
0
파일: MainAct_1.java 프로젝트: lzhih/Sqlite
  private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
      URL url = new URL(myurl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000 /* milliseconds */);
      conn.setConnectTimeout(15000 /* milliseconds */);
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      // Starts the query
      conn.connect();
      int response = conn.getResponseCode();
      Log.d(DEBUG_TAG, "The response is: " + response);
      is = conn.getInputStream();

      // Convert the InputStream into a string
      String contentAsString = readIt(is, len);
      return contentAsString;

      // Makes sure that the InputStream is closed after the app is
      // finished using it.
    } finally {
      if (is != null) {
        is.close();
      }
    }
  }
  public void download(String address) {
    StringBuilder jsonHtml = new StringBuilder();
    try {
      // ���� url ����
      URL url = new URL(address);
      // ���ؼ� ��ü ��
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDefaultUseCaches(false);
      conn.setDoInput(true); // �������� �б� ��� ����
      conn.setDoOutput(false); // ������ ���� ��� ����
      conn.setRequestMethod("POST"); // ��� ����� POST

      // ����Ǿ��
      if (conn != null) {
        conn.setConnectTimeout(10000);
        conn.setUseCaches(false);
        // ����Ȯ�� �ڵ尡 ���ϵǾ��� ��
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
          BufferedReader br =
              new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
          for (; ; ) {
            String line = br.readLine();
            if (line == null) break;
            jsonHtml.append(line);
          }
          br.close();
        }
        conn.disconnect();
      }
    } catch (Exception e) {
      Log.w(TAG, e.getMessage());
    }
  }
  // 活动短信发送
  public static void noteSend(String str, String mobile) {
    String postUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
    String account = "cf_CatMiao";
    String password = "******";
    String content = new String("冰川网贷:" + str);
    try {
      URL url = new URL(postUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true); // 允许连接提交信息
      connection.setRequestMethod("POST"); // 网页提交方式“GET”、“POST”
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection.setRequestProperty("Connection", "Keep-Alive");
      StringBuffer sb = new StringBuffer();
      sb.append("account=" + account);
      sb.append("&password="******"&mobile=" + mobile);
      sb.append("&content=" + content);
      OutputStream os = connection.getOutputStream();
      os.write(sb.toString().getBytes());
      os.close();

      String line, result = "";
      BufferedReader in =
          new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
      while ((line = in.readLine()) != null) {
        result += line + "\n";
      }
      in.close();
      System.out.println("result=" + result);
    } catch (IOException e) {
      e.printStackTrace(System.out);
    }
  }
예제 #29
0
파일: Fake.java 프로젝트: tariqabdulla/fiji
  protected static String discoverImageJHome() {
    URL url = Fake.class.getResource("Fake.class");
    String ijHome;
    try {
      ijHome = URLDecoder.decode(url.toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("Could not discover the ImageJ root directory");
    }
    if (Util.getPlatform().startsWith("win")) ijHome = ijHome.replace('\\', '/');
    if (!ijHome.endsWith("/Fake.class")) throw new RuntimeException("unexpected URL: " + url);
    ijHome = ijHome.substring(0, ijHome.length() - 10);
    if (ijHome.endsWith("/fiji/build/")) ijHome = ijHome.substring(0, ijHome.length() - 11);
    int slash = ijHome.lastIndexOf('/', ijHome.length() - 2);
    if (ijHome.startsWith("jar:file:") && ijHome.endsWith(".jar!/")) {
      fijiBuildJar = ijHome.substring(9, ijHome.length() - 2);
      mtimeFijiBuild = new File(fijiBuildJar).lastModified();
      ijHome = ijHome.substring(9, slash + 1);
    } else if (ijHome.startsWith("file:/")) {
      ijHome = ijHome.substring(5, slash + 1);
      if (ijHome.endsWith("/src-plugins/fake/target/"))
        ijHome = Util.stripSuffix(ijHome, "src-plugins/fake/target/");
      else if (ijHome.endsWith("/src-plugins/")) ijHome = Util.stripSuffix(ijHome, "src-plugins/");
      else if (ijHome.endsWith("/build/jars/")) ijHome = Util.stripSuffix(ijHome, "build/jars/");
    }
    if (Util.getPlatform().startsWith("win") && ijHome.startsWith("/"))
      ijHome = ijHome.substring(1);
    if (ijHome.endsWith("precompiled/")) ijHome = ijHome.substring(0, ijHome.length() - 12);
    else if (ijHome.endsWith("jars/")) ijHome = ijHome.substring(0, ijHome.length() - 5);
    else if (ijHome.endsWith("plugins/")) ijHome = ijHome.substring(0, ijHome.length() - 8);

    return ijHome;
  }
  public static Set<String> getPackageNames(final String url) throws IOException {
    final TreeSet<String> names = new TreeSet<String>();
    final HTMLEditorKit.ParserCallback callback =
        new HTMLEditorKit.ParserCallback() {
          HTML.Tag myTag;

          @Override
          public void handleStartTag(HTML.Tag tag, MutableAttributeSet set, int i) {
            myTag = tag;
          }

          public void handleText(char[] data, int pos) {
            if (myTag != null && "a".equals(myTag.toString())) {
              names.add(String.valueOf(data));
            }
          }
        };

    try {
      final URL repositoryUrl = new URL(url);
      final InputStream is = repositoryUrl.openStream();
      final Reader reader = new InputStreamReader(is);
      try {
        new ParserDelegator().parse(reader, callback, true);
      } catch (IOException e) {
        LOG.warn(e);
      } finally {
        reader.close();
      }
    } catch (MalformedURLException e) {
      LOG.warn(e);
    }

    return names;
  }