Java Code Examples for java.net.URL

The following are top voted examples for showing how to use java.net.URL. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: android-dev-challenge   File: NetworkUtils.java   Source Code and License 9 votes vote down vote up
/**
 * This method returns the entire result from the HTTP response.
 *
 * @param url The URL to fetch the HTTP response from.
 * @return The contents of the HTTP response, null if no response
 * @throws IOException Related to network and stream reading
 */
public static String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        String response = null;
        if (hasInput) {
            response = scanner.next();
        }
        scanner.close();
        return response;
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 2
Project: jdk8u-jdk   File: Beans.java   Source Code and License 9 votes vote down vote up
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 3
Project: CloudNet   File: TemplateLoader.java   Source Code and License 8 votes vote down vote up
public TemplateLoader load()
{
    try
    {
        URLConnection urlConnection = new URL(url).openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        urlConnection.setUseCaches(false);
        urlConnection.connect();
        Files.copy(urlConnection.getInputStream(), Paths.get(dest));
        ((HttpURLConnection)urlConnection).disconnect();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return this;
}
 
Example 4
Project: chromium-net-for-android   File: CronetHttpURLConnectionTest.java   Source Code and License 7 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testAddAndSetRequestPropertyWithSameKey() throws Exception {
    URL url = new URL(NativeTestServer.getEchoAllHeadersURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.addRequestProperty("header-name", "value1");
    connection.setRequestProperty("Header-nAme", "value2");

    // Before connection is made, check request headers are set.
    assertEquals("value2", connection.getRequestProperty("header-namE"));
    Map<String, List<String>> requestHeadersMap =
            connection.getRequestProperties();
    assertEquals(1, requestHeadersMap.get("HeAder-name").size());
    assertEquals("value2", requestHeadersMap.get("HeAder-name").get(0));

    // Check the request headers echoed back by the server.
    assertEquals(200, connection.getResponseCode());
    assertEquals("OK", connection.getResponseMessage());
    String headers = TestUtil.getResponseAsString(connection);
    List<String> actualValues =
            getRequestHeaderValues(headers, "Header-nAme");
    assertEquals(1, actualValues.size());
    assertEquals("value2", actualValues.get(0));
    connection.disconnect();
}
 
Example 5
Project: Orion   File: OrionAPIImpl.java   Source Code and License 7 votes vote down vote up
@NotNull
@Override
public List<URL> getRegisteredMavenRepositories() {
    if(registeredMavenRepositories == null || registeredMavenRepositories.get() == null) {
        registeredMavenRepositories = new SoftReference<>(Collections.unmodifiableList(
                orionCore.modMavenRepositories.stream().map(u -> {
                    try {
                        return u.toURL();
                    } catch (MalformedURLException e) {
                        SneakyThrow.throwException(e);
                        return null;
                    }
                })
                .collect(Collectors.toList())
        ));
    }

    return Objects.requireNonNull(registeredMavenRepositories.get()); // Should not throw NPE
}
 
Example 6
Project: ChatExchange-old   File: StackExchangeAuth.java   Source Code and License 7 votes vote down vote up
/**
 * Retrieve the URL of the page that contains the login form
 */
private void fetchLoginUrl() {
    Log.d(TAG, "fetching login URL...");
    mRequestFactory.get(
            "https://stackexchange.com/users/signin",
            true,
            new RequestListener() {
                @Override
                public void onSucceeded(URL url, String data) {
                    mListener.authProgress(20);
                    mLoginUrl = data;
                    fetchNetworkFkey();
                }
            }
    );
}
 
Example 7
Project: yelpv3-java-client   File: BusinessParser.java   Source Code and License 7 votes vote down vote up
static Business businessFrom(JSONObject information) {
    try {
        return new Business(
            information.getDouble("rating"),
            information.has("price") ? PricingLevel.fromSymbol(information.getString("price")) : PricingLevel.NONE,
            information.getString("phone"),
            information.getString("id"),
            information.getBoolean("is_closed"),
            buildCategories(information.getJSONArray("categories")),
            information.getInt("review_count"),
            information.getString("name"),
            new URL(information.getString("url")),
            CoordinatesParser.from(information.getJSONObject("coordinates")),
            !information.getString("image_url").trim().isEmpty() ? new URL(information.getString("image_url")) : null,
            LocationParser.from(information.getJSONObject("location")),
            !information.isNull("distance") ? Distance.inMeters(information.getDouble("distance")) : null,
            buildTransactions(information.getJSONArray("transactions"))
        );
    } catch (JSONException | MalformedURLException exception) {
        throw ParsingFailure.producedBy(information, exception);
    }
}
 
Example 8
Project: r2-streamer-java   File: TestActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected EpubPublication doInBackground(String... urls) {
    String strUrl = urls[0];

    try {
        URL url = new URL(strUrl);
        URLConnection urlConnection = url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        Log.d("TestActivity", "EpubPublication => " + stringBuilder.toString());

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return objectMapper.readValue(stringBuilder.toString(), EpubPublication.class);
    } catch (IOException e) {
        Log.e(TAG, "SpineListTask error " + e);
    }
    return null;
}
 
Example 9
Project: Transwarp-Sample-Code   File: KerberosWebHDFSConnection2.java   Source Code and License 6 votes vote down vote up
/**
 * <b>LISTSTATUS</b>
 *
 * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=LISTSTATUS"
 *
 * @param path
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String listStatus(String path) throws MalformedURLException,
        IOException, AuthenticationException {
    ensureValidToken();
    System.out.println("Token = "+token.isSet());

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?op=LISTSTATUS",
                    URLUtil.encodePath(path))), token);
    conn.setRequestMethod("GET");
    conn.connect();
    String resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
Example 10
Project: gate-core   File: Plugin.java   Source Code and License 6 votes vote down vote up
protected void scanJar(URL jarUrl, Map<String, ResourceInfo> resInfos) throws IOException {
  JarInputStream jarInput = new JarInputStream(jarUrl.openStream(), false);
  JarEntry entry = null;
  while((entry = jarInput.getNextJarEntry()) != null) {
    String entryName = entry.getName();
    if(entryName != null && entryName.endsWith(".class")) {
      final String className = entryName.substring(0,
               entryName.length() - 6).replace('/', '.');
      if(!resInfos.containsKey(className)) {
        ClassReader classReader = new ClassReader(jarInput);
        ResourceInfo resInfo = new ResourceInfo(null, className, null);
        ResourceInfoVisitor visitor = new ResourceInfoVisitor(resInfo);

        classReader.accept(visitor, ClassReader.SKIP_CODE |
            ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
        if(visitor.isCreoleResource()) {
          resInfos.put(className, resInfo);
        }
      }
    }
  }

  jarInput.close();
}
 
Example 11
Project: ripme   File: FlickrRipper.java   Source Code and License 6 votes vote down vote up
private Document getLargestImagePageDocument(URL url) throws IOException {
    // Get current page
    Document doc = Http.url(url).get();
    // Look for larger image page
    String largestImagePage = this.url.toExternalForm();
    for (Element olSize : doc.select("ol.sizes-list > li > ol > li")) {
        Elements ola = olSize.select("a");
        if (ola.size() == 0) {
            largestImagePage = this.url.toExternalForm();
        }
        else {
            String candImage = ola.get(0).attr("href");
            if (candImage.startsWith("/")) {
                candImage = "http://www.flickr.com" + candImage;
            }
            largestImagePage = candImage;
        }
    }
    if (!largestImagePage.equals(this.url.toExternalForm())) {
        // Found larger image page, get it.
        doc = Http.url(largestImagePage).get();
    }
    return doc;
}
 
Example 12
Project: hadoop   File: DFSAdmin.java   Source Code and License 6 votes vote down vote up
/**
 * Download the most recent fsimage from the name node, and save it to a local
 * file in the given directory.
 * 
 * @param argv
 *          List of of command line parameters.
 * @param idx
 *          The index of the command that is being processed.
 * @return an exit code indicating success or failure.
 * @throws IOException
 */
public int fetchImage(final String[] argv, final int idx) throws IOException {
  Configuration conf = getConf();
  final URL infoServer = DFSUtil.getInfoServer(
      HAUtil.getAddressOfActive(getDFS()), conf,
      DFSUtil.getHttpClientScheme(conf)).toURL();
  SecurityUtil.doAsCurrentUser(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      TransferFsImage.downloadMostRecentImageToDirectory(infoServer,
          new File(argv[idx]));
      return null;
    }
  });
  return 0;
}
 
Example 13
Project: incubator-netbeans   File: JavadocRegistry.java   Source Code and License 6 votes vote down vote up
private String getDocEncoding(URL root) {
    assert root != null && root.toString().endsWith("/") : root;
    InputStream is = URLUtils.open(root, "index-all.html", "index-files/index-1.html");
    if (is != null) {
        try {
            try {
                ParserDelegator pd = new ParserDelegator();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                EncodingCallback ecb = new EncodingCallback(in);
                pd.parse(in, ecb, true);
                return ecb.getEncoding();
            } finally {
                is.close();
            }
        } catch (IOException x) {
            LOG.log(Level.FINE, "Getting encoding from " + root, x);
        }
    }
    return null;
}
 
Example 14
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@Test public void proxyWithConnectionClose() throws IOException {
  server.useHttps(sslClient.socketFactory, true);
  server.enqueue(
      new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders());
  server.enqueue(new MockResponse().setBody("this response comes via a proxy"));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .proxy(server.toProxyAddress())
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(new RecordingHostnameVerifier())
      .build());

  URL url = new URL("https://android.com/foo");
  connection = urlFactory.open(url);
  connection.setRequestProperty("Connection", "close");

  assertContent("this response comes via a proxy", connection);
}
 
Example 15
Project: leoapp-sources   File: UpdateViewTrackerTask.java   Source Code and License 6 votes vote down vote up
@Override
protected Void doInBackground(Integer... params) {
    for (Integer cur : params) {
        remote = cur;
        try {
            URLConnection connection =
                    new URL(Utils.BASE_URL_PHP + "updateViewTracker.php?remote=" + remote)
                            .openConnection();

            connection.getInputStream();
            Utils.getController().getPreferences()
                    .edit()
                    .putString("pref_key_cache_vieweditems", getNewCacheString())
                    .apply();
        } catch (IOException e) {
            Utils.logError(e);
        }
    }
    return null;
}
 
Example 16
Project: FJ-VDMJ   File: CharsetTest.java   Source Code and License 6 votes vote down vote up
private void process(String resource, String charset) throws Exception
{
	Console.out.println("Processing " + resource + "...");

	URL rurl = getClass().getResource("/charsets/" + resource);
	String file = rurl.getPath();

	long before = System.currentTimeMillis();
	ASTClassList parsed = parseClasses(file, charset);
	TCClassList classes = ClassMapper.getInstance(TCNode.MAPPINGS).init().convert(parsed);
	long after = System.currentTimeMillis();

	Console.out.println("Parsed " + classes.size() + " classes in " +
  			(double)(after-before)/1000 + " secs. ");

	before = System.currentTimeMillis();
	TypeChecker typeChecker = new ClassTypeChecker(classes);
	typeChecker.typeCheck();
	after = System.currentTimeMillis();

  		Console.out.println("Type checked in " + (double)(after-before)/1000 + " secs. ");
	Console.out.println("There were " + TypeChecker.getWarningCount() + " warnings");
	assertEquals("Type check errors", 0, TypeChecker.getErrorCount());
}
 
Example 17
Project: manifold   File: UrlClassLoaderWrapper.java   Source Code and License 6 votes vote down vote up
public List<URL> getURLs()
{
  if( _loader instanceof URLClassLoader )
  {
    URL[] urls = ((URLClassLoader)_loader).getURLs();
    return urls == null ? Collections.emptyList() : Arrays.asList( urls );
  }

  List<URL> allUrls = new ArrayList<>( getClasspathUrls() );
  if( JreUtil.isJava9Modular_runtime() )
  {
    allUrls.addAll( getModularUrls() );
  }

  return Collections.unmodifiableList( allUrls );
}
 
Example 18
Project: incubator-netbeans   File: AptSourceFileManager.java   Source Code and License 5 votes vote down vote up
@Override
public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException {
    final URL foUrl = fo.toUri().toURL();
    for (Set<Location> s :  listLocationsForModules(location)) {
        for (Location l : s) {
            ModuleLocation ml = ModuleLocation.cast(l);
            for (URL root : ml.getModuleRoots()) {
                if (FileObjects.isParentOf(root, foUrl)) {
                    return l;
                }
            }
        }
    }
    return null;
}
 
Example 19
Project: SimpleNetworkLibrary   File: ImageSingleRequest.java   Source Code and License 5 votes vote down vote up
private Bitmap getBitmapFromUrl(String url) {
    Bitmap bitmap = null;
    try {
        URLConnection conn = new URL(url).openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        bitmap = BitmapFactory.decodeStream((InputStream) conn.getContent());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bitmap;
}
 
Example 20
Project: NeuralNetworkAPI   File: Metrics.java   Source Code and License 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 21
Project: openjdk-jdk10   File: SecuritySupport.java   Source Code and License 5 votes vote down vote up
/**
 * Check the protocol used in the systemId against allowed protocols
 *
 * @param systemId the Id of the URI
 * @param allowedProtocols a list of allowed protocols separated by comma
 * @param accessAny keyword to indicate allowing any protocol
 * @return the name of the protocol if rejected, null otherwise
 */
public static String checkAccess(String systemId, String allowedProtocols, String accessAny) throws IOException {
    if (systemId == null || (allowedProtocols != null &&
            allowedProtocols.equalsIgnoreCase(accessAny))) {
        return null;
    }

    String protocol;
    if (systemId.indexOf(":")==-1) {
        protocol = "file";
    } else {
        URL url = new URL(systemId);
        protocol = url.getProtocol();
        if (protocol.equalsIgnoreCase("jar")) {
            String path = url.getPath();
            protocol = path.substring(0, path.indexOf(":"));
        } else if (protocol.equalsIgnoreCase("jrt")) {
            // if the systemId is "jrt" then allow access if "file" allowed
            protocol = "file";
        }
    }

    if (isProtocolAllowed(protocol, allowedProtocols)) {
        //access allowed
        return null;
    } else {
        return protocol;
    }
}
 
Example 22
Project: incubator-netbeans   File: JavadocRootsSupport.java   Source Code and License 5 votes vote down vote up
private void maybeUpdateDefaultJavadoc() {
    if (javadocRoots.length == 0) {
        URL[] defaults = getDefaultJavadocRoots();
        if (defaults != null) {
            javadocRoots = defaults;
            pcs.firePropertyChange(JavadocRootsProvider.PROP_JAVADOC_ROOTS, null, null);
        }
    }
}
 
Example 23
Project: docx4j-template   File: PathUtils.java   Source Code and License 5 votes vote down vote up
public static URL fileAsUrl(File file) {
    try {
        return file.toURI().toURL();
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 24
Project: android-perftracking   File: URLDetours.java   Source Code and License 5 votes vote down vote up
@DetourCall
public static URLConnection openConnection(URL url) throws IOException {
  URLConnection conn = url.openConnection();
  if (conn instanceof HttpsURLConnection) {
    return new HttpsURLConnectionWrapper((HttpsURLConnection) conn);
  }
  if (conn instanceof HttpURLConnection) {
    return new HttpURLConnectionWrapper((HttpURLConnection) conn);
  }
  return conn;
}
 
Example 25
Project: ripme   File: FivehundredpxRipper.java   Source Code and License 5 votes vote down vote up
private boolean urlExists(String url) {
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("HEAD");
        if (connection.getResponseCode() != 200) {
            throw new IOException("Couldn't find full-size image at " + url);
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}
 
Example 26
Project: elasticsearch_my   File: JarHellTests.java   Source Code and License 5 votes vote down vote up
/** make sure if a plugin is compiled against the same ES version, it works */
public void testGoodESVersionInJar() throws Exception {
    Path dir = createTempDir();
    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
    attributes.put(new Attributes.Name("X-Compile-Elasticsearch-Version"), Version.CURRENT.toString());
    URL[] jars = {makeJar(dir, "foo.jar", manifest, "Foo.class")};
    JarHell.checkJarHell(jars);
}
 
Example 27
Project: hadoop   File: StreamUtil.java   Source Code and License 5 votes vote down vote up
static URL qualifyHost(URL url) {
  try {
    InetAddress a = InetAddress.getByName(url.getHost());
    String qualHost = a.getCanonicalHostName();
    URL q = new URL(url.getProtocol(), qualHost, url.getPort(), url.getFile());
    return q;
  } catch (IOException io) {
    return url;
  }
}
 
Example 28
Project: hadoop-oss   File: HttpServer2.java   Source Code and License 5 votes vote down vote up
/**
 * Get the pathname to the webapps files.
 * @param appName eg "secondary" or "datanode"
 * @return the pathname as a URL
 * @throws FileNotFoundException if 'webapps' directory cannot be found on CLASSPATH.
 */
protected String getWebAppsPath(String appName) throws FileNotFoundException {
  URL url = getClass().getClassLoader().getResource("webapps/" + appName);
  if (url == null)
    throw new FileNotFoundException("webapps/" + appName
        + " not found in CLASSPATH");
  String urlString = url.toString();
  return urlString.substring(0, urlString.lastIndexOf('/'));
}
 
Example 29
Project: chromium-for-android-56-debug-video   File: ContextualSearchManager.java   Source Code and License 5 votes vote down vote up
@Override
@Nullable public URL getBasePageUrl() {
    ContentViewCore baseContentViewCore = getBaseContentView();
    if (baseContentViewCore == null) return null;

    try {
        return new URL(baseContentViewCore.getWebContents().getUrl());
    } catch (MalformedURLException e) {
        return null;
    }
}
 
Example 30
Project: Star-Ride--RiverRaid   File: EfectosSonido.java   Source Code and License 5 votes vote down vote up
public EfectosSonido(){
    URL url = getClass().getResource("laser.WAV");
    clipShoot = Applet.newAudioClip(url);
    url = getClass().getResource("explosion.wav");
    clipExplosion = Applet.newAudioClip(url);
    url = getClass().getResource("Beep.WAV");
    clipClick = Applet.newAudioClip(url);
}
 
Example 31
Project: EsperantoRadio   File: Diverse.java   Source Code and License 5 votes vote down vote up
/**
 * Tjek for om vi er på et netværk der kræver login eller lignende.
 * Se 'Handling Network Sign-On' i http://developer.android.com/reference/java/net/HttpHttpURLConnection.html
 */
private static void tjekOmdirigering(URL u, HttpURLConnection urlConnection) throws IOException {
  URL u2 = urlConnection.getURL();
  if (!u.getHost().equals(u2.getHost())) {
    // Vi blev omdirigeret
    Log.d("tjekOmdirigering " + u);
    Log.d("tjekOmdirigering " + u2);
    //Log.rapporterFejl(omdirigeringsfejl);
    throw new UnknownHostException("Der blev omdirigeret fra " + u.getHost() + " til " + u2.getHost());
  }
}
 
Example 32
Project: geomapapp   File: ScalingTiledImageLayer.java   Source Code and License 5 votes vote down vote up
protected void retrieveRemoteImage(final TextureTile tile, String mimeType, int timeout) throws Exception
{
    // TODO: apply retriever-factory pattern for remote retrieval case.
    final URL resourceURL = tile.getResourceURL(mimeType);
    if (resourceURL == null)
        return;

    Retriever retriever;

    String protocol = resourceURL.getProtocol();

    if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol))
    {
        retriever = new HTTPRetriever(resourceURL, new CompositionRetrievalPostProcessor(tile));
        retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers
    }
    else
    {
        String message = Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", resourceURL);
        throw new RuntimeException(message);
    }

    Logging.logger().log(java.util.logging.Level.FINE, "Retrieving " + resourceURL.toString());
    retriever.setConnectTimeout(10000);
    retriever.setReadTimeout(timeout);
    retriever.call();
}
 
Example 33
Project: recruitervision   File: CvFilesWindowController.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize(URL location, ResourceBundle resources) {
    configuringFileChooser(fileChooser);
    initTable();
    initRightClick();
    initDragDrop();
    initDefaultChk();
}
 
Example 34
Project: java-natives   File: NativeLibrary.java   Source Code and License 5 votes vote down vote up
private File extractNativeLibraries(final File nativesDirectory, final String libraryPath) {
  final URL libraryUrl = Thread.currentThread().getContextClassLoader().getResource(libraryPath);
  if (libraryUrl == null) {
    throw new IllegalArgumentException(
        String.format("Unable to find native binary %s for library %s", libraryPath, key));
  }
  final String libraryName;
  libraryName = FilenameUtils.getName(libraryPath);
  final File libraryFile = new File(nativesDirectory, libraryName);
  libraryFile.getParentFile().mkdirs();
  try {
    final URLConnection urlConnection = libraryUrl.openConnection();
    try (final InputStream inputStream = urlConnection.getInputStream()) {
      try (final OutputStream outputStream =
          new BufferedOutputStream(new FileOutputStream(libraryFile))) {
        IOUtils.copy(inputStream, outputStream);
      }
    }
  } catch (final Exception exception) {
    throw new RuntimeException(exception);
  }
  if (deleteOnExit) {
    libraryFile.deleteOnExit();
  }
  // TODO make accessible for linux and mac
  return libraryFile;
}
 
Example 35
Project: openNaEF   File: VlanListCollector2.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String serverName = "example.com";
    String userName = "hoge";
    String password = "fuga";
    String url = "https://" + serverName + "/sdk";

    ManagedObjectReference siRef;
    VimServiceLocator locator;
    VimPortType service;
    ServiceContent siContent;

    System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory");

    siRef = new ManagedObjectReference();
    siRef.setType("ServiceInstance");
    siRef.set_value("ServiceInstance");

    locator = new VimServiceLocator();
    locator.setMaintainSession(true);
    service = locator.getVimPort(new URL(url));
    siContent = service.retrieveServiceContent(siRef);
    if (siContent.getSessionManager() != null) {
        service.login(siContent.getSessionManager(),
                userName,
                password,
                null);
    }

    refresh(service, siContent);
    collectProperties(service, siContent);

    service.logout(siContent.getSessionManager());
    service = null;
    siContent = null;
}
 
Example 36
Project: jbake-rtl-jalaali   File: RendererTest.java   Source Code and License 5 votes vote down vote up
@Before
   public void setup() throws Exception {
	URL sourceUrl = this.getClass().getResource("/");
	rootPath = new File(sourceUrl.getFile());
       if (!rootPath.exists()) {
           throw new Exception("Cannot find base path for test!");
       }
       outputPath = folder.newFolder("output");
	config = ConfigUtil.load(rootPath);		
}
 
Example 37
Project: incubator-netbeans   File: MoveJavaFileTest.java   Source Code and License 5 votes vote down vote up
public void test168923c() throws Exception { // #168923 - [Move] refactoring a package doesn't update star imports [68cat]
    writeFilesAndWaitForScan(src,
                             new File("t/package-info.java", "package t;"),
                             new File("A.java", "import u.*; import u.B; public class A { public void foo() { int d = B.c; } }"),
                             new File("u/B.java", "package u; public class B { public static int c = 5; }"));
    performMoveClass(Lookups.singleton(src.getFileObject("u/B.java")), new URL(src.getURL(), "t/"));
    verifyContent(src,
                  new File("t/package-info.java", "package t;"),
                  new File("A.java", "import t.B; public class A { public void foo() { int d = B.c; } }"),
                  new File("t/B.java", "package t; public class B { public static int c = 5; }"));
}
 
Example 38
Project: GeekZone   File: BaseStack.java   Source Code and License 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException,
        AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}
 
Example 39
Project: geomapapp   File: URLFactory.java   Source Code and License 5 votes vote down vote up
public static String checkForRedirect(String url) {
	try {
		HttpURLConnection con = (HttpURLConnection) new URL( url ).openConnection();
		if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
			url = con.getHeaderField("Location");
		}
	} catch(IOException e) {
		e.printStackTrace();
	}
	return url;
}
 
Example 40
Project: AWGW   File: WorldFrame.java   Source Code and License 5 votes vote down vote up
/**
 * Brings up a window with a scrolling text pane that display the help
 * information.
 */
private void showHelp() {
    JDialog dialog = new JDialog(this, resources.getString("dialog.help.title"));
    final JEditorPane helpText = new JEditorPane();
    try {
        URL url = getClass().getResource("GridWorldHelp.html");

        helpText.setPage(url);
    } catch (Exception eh) {
        helpText.setText(resources.getString("dialog.help.error"));
    }
    helpText.setEditable(false);
    helpText.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent ev) {
            if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
                try {
                    helpText.setPage(ev.getURL());
                } catch (Exception ex) {
                }
        }
    });
    JScrollPane sp = new JScrollPane(helpText);
    sp.setPreferredSize(new Dimension(650, 500));
    dialog.getContentPane().add(sp);
    dialog.setLocation(getX() + getWidth() - 200, getY() + 50);
    dialog.pack();
    dialog.setVisible(true);
}
 
Example 41
Project: jerrydog   File: ApplicationContext.java   Source Code and License 5 votes vote down vote up
/**
 * Return the 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.
 *
 * @param path The path to the desired resource
 *
 * @exception MalformedURLException if the path is not given
 *  in the correct form
 */
public URL getResource(String path)
    throws MalformedURLException {

    DirContext resources = context.getResources();
    if (resources != null) {
        String fullPath = context.getName() + path;

        // this is the problem. Host must not be null
        String hostName = context.getParent().getName();

        try {
            resources.lookup(path);
            if( System.getSecurityManager() != null ) {
                try {
                    PrivilegedGetResource dp =
                        new PrivilegedGetResource
                            (hostName, fullPath, resources);
                    return (URL)AccessController.doPrivileged(dp);
                } catch( PrivilegedActionException pe) {
                    throw pe.getException();
                }
            } else {
                return new URL
                    ("jndi", null, 0, getJNDIUri(hostName, fullPath),
                     new DirContextURLStreamHandler(resources));
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }
    return (null);

}
 
Example 42
Project: hadoop   File: TestApplicationClassLoader.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetResource() throws IOException {
  URL testJar = makeTestJar().toURI().toURL();
  
  ClassLoader currentClassLoader = getClass().getClassLoader();
  ClassLoader appClassloader = new ApplicationClassLoader(
      new URL[] { testJar }, currentClassLoader, null);

  assertNull("Resource should be null for current classloader",
      currentClassLoader.getResourceAsStream("resource.txt"));

  InputStream in = appClassloader.getResourceAsStream("resource.txt");
  assertNotNull("Resource should not be null for app classloader", in);
  assertEquals("hello", IOUtils.toString(in));
}
 
Example 43
Project: JAVA-   File: WeiXinWYUtils.java   Source Code and License 5 votes vote down vote up
/**
     * 报修处理进展通知
     */
    public static boolean progressNotic() {
        boolean isOk = false;
        String token = WeiXinUtils.getToken();
        if (token != null) {
            String urlString = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
            try {
//                op-51t-YG9RE_Pcfr9WD8e9MRYN0
                WXMessasgeTemplate wxMessasgeTemplate = new WXMessasgeTemplate();
//                wxMessasgeTemplate.setTouser("op-51t5m2L_VLsDvXXDdSm-BOToY");
                wxMessasgeTemplate.setTouser("op-51t-YG9RE_Pcfr9WD8e9MRYN0");
                wxMessasgeTemplate.setTemplate_id("7GabJuZ-w-0ZTKMdajfmXB3WBVCp55NAmnrUS_IqU3Y");
                wxMessasgeTemplate.setUrl("http://weixin.qq.com/download");
                JSONObject jsonObject = new JSONObject();
                JSONObject firstJsonObject = new JSONObject();
                firstJsonObject.put("value", "尊敬的耿adfasf:您的报修有新的进展。");
                jsonObject.put("first", firstJsonObject);

                JSONObject key1 = new JSONObject();
                key1.put("value", "郑汴路dfasfdf");
                jsonObject.put("keyword1", key1);

                JSONObject key2 = new JSONObject();
                key2.put("value", "郑汴路adfasf1");
                jsonObject.put("keyword2", key2);

                JSONObject key3 = new JSONObject();
                key3.put("value", "郑汴路2adfasf");
                jsonObject.put("keyword3", key3);

                JSONObject key4 = new JSONObject();
                key4.put("value", "郑汴路asdfasf3");
                jsonObject.put("keyword4", key4);

                JSONObject key5 = new JSONObject();
                key5.put("value", "郑汴路afdasf4");
                jsonObject.put("keyword5", key5);

                JSONObject remark = new JSONObject();
                remark.put("value", "3ks!");
                jsonObject.put("remark", remark);
                wxMessasgeTemplate.setData(jsonObject);
                URL url = new URL(urlString);
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                String kfAccountString = JSONObject.toJSONString(wxMessasgeTemplate);
                httpsURLConnection.setRequestProperty("Content-length", String.valueOf(kfAccountString.length()));
                httpsURLConnection.setRequestProperty("Content-Type", "application/json");
                httpsURLConnection.setDoOutput(true);
                httpsURLConnection.setDoInput(true);
                DataOutputStream dataOutputStream = new DataOutputStream(httpsURLConnection.getOutputStream());
                dataOutputStream.write(kfAccountString.getBytes());
                dataOutputStream.flush();
                dataOutputStream.close();
                DataInputStream dataInputStream = new DataInputStream(httpsURLConnection.getInputStream());
                StringBuffer stringBuffer = new StringBuffer();
                int inputByte = dataInputStream.read();
                while (inputByte != -1) {
                    stringBuffer.append((char) inputByte);
                    inputByte = dataInputStream.read();
                }
                String kfString = stringBuffer.toString();
                System.out.println(kfString);
                JSONObject jsonObject1 = JSON.parseObject(kfString);
                if (jsonObject1.containsKey("errcode")) {
                    int errcode = jsonObject1.getIntValue("errcode");
                    if (errcode == 0) {
                        isOk = true;
                    } else {
                        //TODO 添加客服账号失败
                        isOk = false;
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return isOk;
    }
 
Example 44
Project: IDBuilderFX   File: HelpController.java   Source Code and License 5 votes vote down vote up
@Override
	public void initialize(URL arg0, ResourceBundle arg1) {


String myvar = "<p><span style=\"color: #008080;\">IDBuilderFx</span> is a free desktop application built purely in JavaFx created for ease of Identity card creation which is more organised and consistent as compared to separately made Identity cards manually.</p>"+
"<p><span style=\"color: #008080;\">IDBuilderFx</span> works on essentially every popular platform. Challenge is to parse multiple resumes together which are in different types of formats and layouts and that too in a clean and efficient manner. It can read any type of resume in pdf format to give consistent Identity cards through evenly designed templates.</p>"+
"<p><span style=\"color: #008080;\"><em>Looking for a quick intro to IDBuilderFx?</em></span></p>"+
"<p>Check out a few quick tips to help you get started.</p>"+
"<ul>"+
"<li><strong>Login</strong> to your account from the right top corner login button on the home window to generate safe and secure outputs using confidential information of employees.</li>"+
"<li><strong>Browse for single or multiple resumes</strong> or CVs. Selecting one of the option will take you to the corresponding window (single or multiple) where you can choose the files.</li>"+
"<li>Next is <strong>Parser</strong> Click on Parse button to start parsing process and get the extracted data from the resumes.</li>"+
"<li>Get <strong>view of organised database </strong>in the form of an employee table.</li>"+
"<li><strong>Edit </strong>the details if required. <strong>Photos </strong>can be added or changed.</li>"+
"<li>Get to choose from <strong>attractive templates </strong>for Identity cards.</li>"+
"<li>In the <strong>Preview Template</strong> window, Enter the Organisation's name and select the output folder for the generated ID cards.</li>"+
"<li><strong>Generate! </strong>You can either view the output ID Cards or repeat to exploit more!</li>"+
"</ul>"+
"<hr />"+
"<p>�</p>"+
"<p>� Divyanshu Vishwakarma Mohammed Habeeb Ayushi Kakkar</p>"+
"<p><span style=\"color: #0000ff;\"><a href=\"https://github.com/djdivix/IDBuilderFX\">https://github.com/djdivix/IDBuilderFX</a></span></p>"+
"<p><span style=\"color: #000000;\">Email: [email protected]</span></p>"+
"<p>Contact : 9565484835</p>";
	

		WebEngine wEngine = wview.getEngine();
		wEngine.loadContent(myvar);
	}
 
Example 45
Project: hadoop   File: Fetcher.java   Source Code and License 5 votes vote down vote up
private void openConnectionWithRetry(MapHost host,
    Set<TaskAttemptID> remaining, URL url) throws IOException {
  long startTime = Time.monotonicNow();
  boolean shouldWait = true;
  while (shouldWait) {
    try {
      openConnection(url);
      shouldWait = false;
    } catch (IOException e) {
      if (!fetchRetryEnabled) {
         // throw exception directly if fetch's retry is not enabled
         throw e;
      }
      if ((Time.monotonicNow() - startTime) >= this.fetchRetryTimeout) {
        LOG.warn("Failed to connect to host: " + url + "after " 
            + fetchRetryTimeout + " milliseconds.");
        throw e;
      }
      try {
        Thread.sleep(this.fetchRetryInterval);
      } catch (InterruptedException e1) {
        if (stopped) {
          return;
        }
      }
    }
  }
}
 
Example 46
Project: Reer   File: IvyXmlModuleDescriptorParser.java   Source Code and License 5 votes vote down vote up
private ModuleDescriptor parseOtherIvyFileOnFileSystem(String location)
        throws ParseException, IOException {
    URL url = relativeUrlResolver.getURL(descriptorURL, location);
    LOGGER.debug("Trying to load included ivy file from {}", url);
    ExternalResource resource = UrlExternalResource.open(url);
    try {
        return parseModuleDescriptor(resource, url);
    } catch (MissingResourceException e) {
        // Ignore
        return null;
    } finally {
        resource.close();
    }
}
 
Example 47
Project: BiglyBT   File: TRTrackerScraperImpl.java   Source Code and License 5 votes vote down vote up
public boolean
redirectTrackerUrl(
	HashWrapper		hash,
	URL				old_url,
	URL				new_url )
{
	return( client_resolver.redirectTrackerUrl( hash, old_url, new_url ));
}
 
Example 48
Project: incubator-netbeans   File: JFXProjectProperties.java   Source Code and License 5 votes vote down vote up
PreloaderJarArtifact(final @NonNull URL[] classPathRoots, final @NonNull FileObject[] fileObjects, final @NonNull FileObject projectArtifact, 
        final @NonNull String classPathType, final @NonNull String ID) {
    this.classPathRoots = classPathRoots;
    this.fileObjects = fileObjects;
    this.projectArtifact = projectArtifact;
    this.classPathType = classPathType;
    this.ID = ID;
}
 
Example 49
Project: ditb   File: HttpServerFunctionalTest.java   Source Code and License 5 votes vote down vote up
/**
 * Read in the content from a URL
 * @param url URL To read
 * @return the text from the output
 * @throws IOException if something went wrong
 */
protected static String readOutput(URL url) throws IOException {
  StringBuilder out = new StringBuilder();
  InputStream in = url.openConnection().getInputStream();
  byte[] buffer = new byte[64 * 1024];
  int len = in.read(buffer);
  while (len > 0) {
    out.append(new String(buffer, 0, len));
    len = in.read(buffer);
  }
  return out.toString();
}
 
Example 50
Project: incubator-netbeans   File: URLDataObject.java   Source Code and License 5 votes vote down vote up
public void open() {
    String urlString = getURLString();
    if (urlString == null) {
        return;
    }
    URL url = getURLFromString(urlString);
    if (url == null) {
        return;
    }
    org.openide.awt.HtmlBrowser.URLDisplayer.getDefault().showURL(url);
}
 
Example 51
Project: MMORPG_Prototype   File: Assets.java   Source Code and License 5 votes vote down vote up
private static URL toURL(String userDir, String jar)
{
	try
	{
		String path = jar.trim().replace(" ", "%20");
		if(!new File(path).isAbsolute())
			return new URL("file:\\" + userDir + '\\' + path);
		
		return new URL("file:\\" + path);
	} catch (MalformedURLException e)
	{
		throw new RuntimeException(e);
	}
}
 
Example 52
Project: n4js   File: RsrcURLStreamHandler.java   Source Code and License 5 votes vote down vote up
@Override
protected void parseURL(URL url, String spec, int start, int limit) {
	String file;
	if (spec.startsWith(JIJConstants.INTERNAL_URL_PROTOCOL_WITH_COLON))
		file = spec.substring(5);
	else if (url.getFile().equals(JIJConstants.CURRENT_DIR))
		file = spec;
	else if (url.getFile().endsWith(JIJConstants.PATH_SEPARATOR))
		file = url.getFile() + spec;
	else
		file = spec;
	setURL(url, JIJConstants.INTERNAL_URL_PROTOCOL, "", -1, null, null, file, null, null); //$NON-NLS-1$
}
 
Example 53
Project: java-messenger-watchdog   File: IntentAnalyzerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void watchWebsiteIntent() throws MalformedURLException {
  Intent intent = IntentAnalyzer.analyzeIntent("Halte ein Auge auf https://www.apptiva.ch/");
  assertTrue(intent instanceof WatchWebsite);
  WatchWebsite watchWebsite = (WatchWebsite) intent;
  assertThat(watchWebsite.url(), is(new URL("https://www.apptiva.ch/")));
}
 
Example 54
Project: QN-ACTR-Release   File: HtmlPanel.java   Source Code and License 5 votes vote down vote up
/**
 * Builds a new HtmlPanel that shows given url
 * @param url url of the page to be displayed
 */
public HtmlPanel(URL url) {
	init();
	if (url != null) {
		setURL(url);
		putClientProperty(BasicHTML.documentBaseKey, url.getPath());
		// The following line fixes a problem with incorrectly drawn text inside tables.
		setCaretPosition(0);
	}
}
 
Example 55
Project: buenojo   File: ResourceHelper.java   Source Code and License 5 votes vote down vote up
public static final URL getResource(final boolean isFromGameResourceInput,String... fileResourcePathComponents)
{
	if (isFromGameResourceInput)
	{
		final String[] inputGameResourceArray = {BuenOjoFileUtils.GAME_RESOURCES_INPUT_DIR};
		fileResourcePathComponents = (String[]) ArrayUtils.addAll(inputGameResourceArray, fileResourcePathComponents);

	}	
	return getResource(fileResourcePathComponents);
}
 
Example 56
Project: GitHub   File: URLConnectionTest.java   Source Code and License 5 votes vote down vote up
@Test public void urlWithBadAsciiHost() throws Exception {
  URLConnection urlConnection = urlFactory.open(new URL("http://host\u0001/"));
  try {
    urlConnection.getInputStream();
    fail();
  } catch (UnknownHostException expected) {
  }
}
 
Example 57
Project: gitlab-branch-source-plugin   File: GitLabAPI.java   Source Code and License 5 votes vote down vote up
public List<GitlabRepositoryTree> getTree(int id, String ref, String path) throws GitLabAPIException {
    try {
        Query query = new Query()
                .appendIf("path", path)
                .appendIf("ref_name", ref);


        String tailUrl = GitlabProject.URL + "/" + id + "/repository" + GitlabRepositoryTree.URL + query.toString();
        GitlabRepositoryTree[] tree = getDelegate().retrieve().to(tailUrl, GitlabRepositoryTree[].class);
        return Arrays.asList(tree);
    } catch (Exception e) {
        throw new GitLabAPIException(e);
    }
}
 
Example 58
Project: FCat   File: PathUtil.java   Source Code and License 5 votes vote down vote up
public static String getResourceFilePath(String fileName) {
	URL url = PathUtil.class.getClassLoader().getResource(fileName);
	String filePath = (url != null ? url.getPath() : "");

	if (!(new File(filePath)).isFile()) {
		LOG.info("1 filePath=" + filePath + " is not exists!");
		filePath = PathUtil.getBaseRealPath() + "/WEB-INF/classes/" + fileName;
		if (!(new File(filePath)).isFile()) {
			LOG.info("2 filePath=" + filePath + " is not exists!");
			filePath = PathUtil.getBaseRealPath() + "/WEB-INF/" + fileName;
			if (!(new File(filePath)).isFile()) {
				LOG.info("3 filePath=" + filePath + " is not exists!");
				filePath = PathUtil.getBaseRealPath() + "/" + fileName;
				if (!(new File(filePath)).isFile()) {
					LOG.info("4 filePath=" + filePath + " is not exists!");
					// TODO 该方法确实非常特殊,与开发环境偶合了
					filePath = PathUtil.getBaseRealPath() + "/webapp/WEB-INF/" + fileName;
					if (!(new File(filePath)).isFile()) {
						LOG.info("5 filePath=" + filePath + " is not exists!");
					}
				}
			}
		}
	}

	while (filePath.indexOf(":") > 0 && (filePath.startsWith("/") || filePath.startsWith("\\"))) {// windows下删除第一个
		// linux下不要删除
		filePath = filePath.substring(1);
	}
	filePath = toPath(filePath);
	if (!(new File(filePath)).isFile()) {
		LOG.info("6 filePath=" + filePath + " is not exists!");
	}
	if (LOG.isInfoEnabled()) {
		LOG.info("getResourceFilePath(String fileName) fileName=" + fileName + " filePath=" + filePath);
	}
	return filePath;
}
 
Example 59
Project: ZhiHuIndex-master   File: HttpUtil.java   Source Code and License 4 votes vote down vote up
public static List<Problem> sendWithHttp(final URL urlAddress,final String problemJson){
   new Thread(new Runnable() {
     @Override
     public void run() {
         URL url = urlAddress;
         try{
             String problemStr = URLEncoder.encode(problemJson,"UTF-8");
             //打开链接
             connection = (HttpURLConnection)url.openConnection();
             //POST请求
             connection.setRequestMethod("POST");
             //允许此链接输入输出
             connection.setDoOutput(true);
             connection.setDoInput(true);
             connection.setRequestProperty("Accept-Charset", "utf-8");
             connection.setRequestProperty("contentType", "utf-8");
             connection.connect();
             //获得输出流
             DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
             //传送Json数据
             Log.v("HttpUtil1",problemStr);
             Log.v("HttpUtil1", URLDecoder.decode(problemStr,"UTF-8"));
             dos.writeBytes(problemStr);
             dos.flush();
             dos.close();
             //如果成功
             if(connection.getResponseCode()==200){
                   String str =getResponse();
                 Log.v("HttpUtil123",str);
                   //获得返回数据
                   problemList = GsonTool.getList(str);
             }
         }catch(Exception e){
             e.printStackTrace();
         }
         finally {
             if(connection!=null){
                 connection.disconnect();
             }
         }
     }
   }).start();
    return problemList;
}
 
Example 60
Project: geomapapp   File: OtherDBInputDialog.java   Source Code and License 4 votes vote down vote up
public void loadExcelURL(String c){
	try {
		URL url = URLFactory.url(c);
		int length = url.openConnection().getContentLength();
		JDialog d = new JDialog((Frame)null, "Loading File");
		JPanel p = new JPanel(new BorderLayout());
		p.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
		d.setLocationRelativeTo(null);
		JProgressBar pb = new JProgressBar(0,length);
		p.add(new JLabel("Loading " + (length / 1000) + " kb file"), BorderLayout.NORTH);
		p.add(pb);
		d.getContentPane().add(p);
		d.pack();
		d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		d.setVisible(true); 
		d.setAlwaysOnTop(true);
		Workbook wb = Workbook.getWorkbook(url.openStream());
		if (wb.getNumberOfSheets()==0) return;
		Sheet s = wb.getSheet(0);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.getRows(); i++) {
			for (int j = 0; j < s.getColumns(); j++)
			{
					if (s.getCell(j, i).getType() == CellType.NUMBER && !s.getCell(j, i).getContents().matches("\\d*")) {
						sb.append(((NumberCell)s.getCell(j, i)).getValue()+"\t");	
						pb.setValue(pb.getValue() + 16);
						pb.repaint();
					}
					else {
						pb.setValue(pb.getValue() + 2*s.getCell(j, i).getContents().length()+36);
						pb.repaint();
						sb.append(s.getCell(j, i).getContents()+"\t");
					}
					//if (j<s.getRows()-1) sb.append(s.getCell(j, i).getContents()+"\t");
				//else sb.append(s.getCell(j, i).getContents()+"\t");
			}
			sb.append("\n");
		}
		name.setText(url.getFile().substring(url.getFile().lastIndexOf('/')+1, url.getFile().lastIndexOf('.')));
		input.setText(sb.toString());
		wb.close();
		d.dispose();
	} catch (Exception e) {
		JOptionPane.showMessageDialog(null, "Error reading URL:\n"+e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		return;
	}
}