Example usage for java.net URLConnection getClass

List of usage examples for java.net URLConnection getClass

Introduction

In this page you can find the example usage for java.net URLConnection getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.dianping.resource.io.util.ResourceUtils.java

/**
 * Set the {@link java.net.URLConnection#setUseCaches "useCaches"} flag on the
 * given connection, preferring {@code false} but leaving the
 * flag at {@code true} for JNLP based resources.
 * @param con the URLConnection to set the flag on
 *///from w  ww .j a  v  a 2 s .  co m
public static void useCachesIfNecessary(URLConnection con) {
    con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
}

From source file:com.opensource.frameworks.processframework.utils.ResourceUtils.java

/**
 * Set the {@link URLConnection#setUseCaches "useCaches"} flag on the
 * given connection, preferring <code>false</code> but leaving the
 * flag at <code>true</code> for JNLP based resources.
 * @param con the URLConnection to set the flag on
 *//*from  www.  ja  v a 2s .c  o m*/
public static void useCachesIfNecessary(URLConnection con) {
    con.setUseCaches(con.getClass().getName().startsWith("JNLP"));
}

From source file:com.technophobia.substeps.report.DefaultExecutionReportBuilder.java

public void copyResourcesRecursively(final URL originUrl, final File destination) throws IOException {
    final URLConnection urlConnection = originUrl.openConnection();
    if (urlConnection instanceof JarURLConnection) {
        copyJarResourcesRecursively(destination, (JarURLConnection) urlConnection);
    } else if (urlConnection instanceof FileURLConnection) {
        FileUtils.copyDirectory(new File(originUrl.getPath()), destination);
    } else {/*ww  w . j  ava2 s  .  c om*/
        throw new RuntimeException("URLConnection[" + urlConnection.getClass().getSimpleName()
                + "] is not a recognized/implemented connection type.");
    }
}

From source file:com.intellij.util.net.HttpConfigurable.java

/**
 * Opens HTTP connection to a given location using configured http proxy settings.
 * @param location url to connect to//from ww  w. ja  va 2  s.c o  m
 * @return instance of {@link HttpURLConnection}
 * @throws IOException in case of any I/O troubles or if created connection isn't instance of HttpURLConnection.
 */
@NotNull
public HttpURLConnection openHttpConnection(@NotNull String location) throws IOException {
    URLConnection urlConnection = openConnection(location);
    if (urlConnection instanceof HttpURLConnection) {
        return (HttpURLConnection) urlConnection;
    } else {
        throw new IOException("Expected " + HttpURLConnection.class + ", but got " + urlConnection.getClass());
    }
}

From source file:com.stacksync.desktop.Environment.java

public void copyResourcesRecursively(URL originUrl, File destination) throws Exception {
    URLConnection urlConnection = originUrl.openConnection();
    if (urlConnection instanceof JarURLConnection) {
        copyResourcesFromJar((JarURLConnection) urlConnection, destination);
    } else if (urlConnection instanceof FileURLConnection) {
        // I know that this is not so beatiful... I'll try to change in a future...
        if (operatingSystem == OperatingSystem.Mac || operatingSystem == OperatingSystem.Linux) {
            destination = defaultUserConfDir;
        }/*  w w w  .j  av a 2  s .  c  o m*/
        FileUtils.copyDirectoryToDirectory(new File(originUrl.getPath()), destination);
    } else {
        throw new Exception("URLConnection[" + urlConnection.getClass().getSimpleName()
                + "] is not a recognized/implemented connection type.");
    }
}

From source file:com.dragonflow.StandardMonitor.URLOriginalMonitor.java

private static long getURLStatus_ForBackupToRegularMeansOnly(SocketSession socketsession, long l, String s,
        int i, int j) {
    if (i >= j) {
        System.out.println("URLOriginalMonitor KEEPTRYING!!! - URL: " + s + "FAILED THIS MANY TIMES: " + i);
        return l;
    }//from w  ww.ja va 2  s  . com
    if (l != 200L && l != 302L && l != 301L) {
        System.out.println(
                "URLOriginalMonitor KEEPTRYING!!! - URL: " + s + " status: " + l + " times attempted: " + i);
        int k = 0;
        if (socketsession.context.getSetting("_timeout").length() > 0) {
            k = TextUtils.toInt(socketsession.context.getSetting("_timeout")) * 1000;
        } else {
            k = 60000;
        }
        Platform.sleep(k);
        StringBuffer stringbuffer = new StringBuffer();
        try {
            URL url = new URL(s);
            URLConnection urlconnection = url.openConnection();
            System.out.println(
                    "URLOriginalMonitor KEEPTRYING Received a : " + urlconnection.getClass().getName());
            System.out.println(
                    "URLOriginalMonitor KEEPTRYING Received connection string : " + urlconnection.toString());
            urlconnection.setDoInput(true);
            urlconnection.setUseCaches(false);
            System.out.println("URLOriginalMonitor KEEPTRYING Getting an input stream...");
            java.io.InputStream inputstream = urlconnection.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            for (String s5 = null; (s5 = bufferedreader.readLine()) != null;) {
                stringbuffer.append(s5);
            }

            System.out.println("URLOriginalMonitor KEEPTRYING CONTENTS: " + stringbuffer.toString());
        } catch (MalformedURLException malformedurlexception) {
            String s1 = "URLOriginalMonitor KEEPTRYING error attempted backup URL retrieval: " + s
                    + " exception: " + malformedurlexception.toString();
            LogManager.log("Error", s1);
            LogManager.log("Error", FileUtils.stackTraceText(malformedurlexception));
            System.out.println(s1);
            malformedurlexception.printStackTrace();
            return getURLStatus_ForBackupToRegularMeansOnly(socketsession, l, s, ++i, j);
        } catch (IOException ioexception) {
            String s2 = "URLOriginalMonitor KEEPTRYING error attempted backup URL retrieval: " + s
                    + " exception: " + ioexception.toString();
            LogManager.log("Error", s2);
            LogManager.log("Error", FileUtils.stackTraceText(ioexception));
            System.out.println(s2);
            ioexception.printStackTrace();
            return getURLStatus_ForBackupToRegularMeansOnly(socketsession, l, s, ++i, j);
        } catch (Exception exception) {
            String s3 = "URLOriginalMonitor KEEPTRYING error attempted backup URL retrieval: " + s
                    + " exception: " + exception.toString();
            LogManager.log("Error", s3);
            LogManager.log("Error", FileUtils.stackTraceText(exception));
            System.out.println(s3);
            exception.printStackTrace();
            return getURLStatus_ForBackupToRegularMeansOnly(socketsession, l, s, ++i, j);
        } catch (Throwable throwable) {
            String s4 = "URLOriginalMonitor KEEPTRYING error attempted backup URL retrieval: " + s
                    + " exception: " + throwable.toString();
            LogManager.log("Error", s4);
            LogManager.log("Error", FileUtils.stackTraceText(throwable));
            System.out.println(s4);
            throwable.printStackTrace();
            return getURLStatus_ForBackupToRegularMeansOnly(socketsession, l, s, ++i, j);
        }
        return 200L;
    } else {
        return l;
    }
}

From source file:org.activiti.rest.osgi.OsgiClassPathStoreResourceResolver.java

protected Resource resolveRootDirResource(Resource original) throws IOException {
    Resource resolved = super.resolveRootDirResource(original);
    if (resolved == original) {
        // Equinox/Felix specific hack
        try {/*w w w . j a  va  2  s  .  com*/
            URL url = original.getURL();
            URLConnection con = url.openConnection();
            try {
                Method mth = con.getClass().getMethod("getLocalURL");
                mth.setAccessible(true);
                URL localUrl = (URL) mth.invoke(con);
                if (localUrl != null) {
                    return new UrlResource(localUrl);
                }
            } catch (NoSuchMethodException t) {
                Object targetModule = getField(con, "m_targetModule");
                int classPathIdx = (Integer) getField(con, "m_classPathIdx");
                Object content;
                if (classPathIdx == 0) {
                    content = getField(targetModule, "m_content");
                } else {
                    Object[] contentPath = (Object[]) getField(targetModule, "m_contentPath");
                    content = contentPath[classPathIdx - 1];
                }
                URL localUrl = getContentUrl(content, url.getPath());
                return new UrlResource(localUrl);
            }
        } catch (Throwable t) {
            logger.debug("Could not resolve url");
        }
    }
    return original;
}

From source file:org.codehaus.groovy.grails.io.support.GrailsResourceUtils.java

public static void useCachesIfNecessary(URLConnection con) {
    con.setUseCaches(con.getClass().getName().startsWith("JNLP"));
}

From source file:org.openymsg.network.Session.java

private String[] yahooAuth16Stage1(final String seed)
        throws LoginRefusedException, IOException, NoSuchAlgorithmException {
    String authLink = "https://" + this.yahooLoginHost + "/config/pwtoken_get?src=ymsgr&ts=&login="
            + this.loginID.getId() + "&passwd=" + URLEncoder.encode(this.password, "UTF-8") + "&chal="
            + URLEncoder.encode(seed, "UTF-8");

    URL u = new URL(authLink);
    URLConnection uc = u.openConnection();
    uc.setConnectTimeout(LOGIN_HTTP_TIMEOUT);

    if (uc instanceof HttpsURLConnection) {
        HttpsURLConnection httpUc = (HttpsURLConnection) uc;
        // used to simulate failures
        //             if  (triesBeforeFailure++ % 3 == 0) {
        //                 throw new SocketException("Test failure");
        //             }
        if (!this.yahooLoginHost.equalsIgnoreCase(LOGIN_YAHOO_COM))
            httpUc.setHostnameVerifier(new HostnameVerifier() {

                @Override/*from  www.  jav  a 2 s .c o  m*/
                public boolean verify(final String hostname, final SSLSession session) {
                    Principal principal = null;
                    try {
                        principal = session.getPeerPrincipal();
                    } catch (SSLPeerUnverifiedException e) {
                    }
                    String localName = "no set";
                    if (principal != null)
                        localName = principal.getName();
                    log.debug("Hostname verify: " + hostname + "localName: " + localName);
                    return true;
                }
            });

        int responseCode = httpUc.getResponseCode();
        this.setSessionStatus(SessionState.STAGE1);
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = uc.getInputStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int read = -1;
            byte[] buff = new byte[256];
            while ((read = in.read(buff)) != -1)
                out.write(buff, 0, read);
            in.close();

            StringTokenizer toks = new StringTokenizer(out.toString(), "\r\n");
            if (toks.countTokens() <= 0)
                // errrorrrr
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 1:" + httpUc.getResponseMessage());

            int responseNo = -1;
            try {
                responseNo = Integer.valueOf(toks.nextToken());
            } catch (NumberFormatException e) {
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 1:" + httpUc.getResponseMessage());
            }

            if (responseNo != 0 || !toks.hasMoreTokens())
                switch (responseNo) {
                case 1235:
                    throw new LoginRefusedException("Login Failed, Invalid username",
                            AuthenticationState.BADUSERNAME);
                case 1212:
                    throw new LoginRefusedException("Login Failed, Wrong password", AuthenticationState.BAD);
                case 1213:
                    throw new LoginRefusedException("Login locked: Too many failed login attempts",
                            AuthenticationState.LOCKED);
                case 1236:
                    throw new LoginRefusedException("Login locked", AuthenticationState.LOCKED);
                case 100:
                    throw new LoginRefusedException("Username or password missing", AuthenticationState.BAD);
                default:
                    throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);
                }

            String ymsgr = toks.nextToken();

            if (ymsgr.indexOf("ymsgr=") == -1 && toks.hasMoreTokens())
                ymsgr = toks.nextToken();

            ymsgr = ymsgr.replaceAll("ymsgr=", "");

            return yahooAuth16Stage2(ymsgr, seed);
        } else {
            log.error("Failed opening login url: " + authLink + " return code: " + responseCode);
            throw new LoginRefusedException(
                    "Login Failed, Login url: " + authLink + " return code: " + responseCode);
        }
    } else {
        Class<? extends URLConnection> ucType = null;
        if (uc != null)
            ucType = uc.getClass();
        log.error("Failed opening login url: " + authLink + " returns: " + ucType);
        throw new LoginRefusedException("Login Failed, Unable to submit login url");
    }

    //throw new LoginRefusedException("Login Failed, unable to retrieve stage 1 url");
}

From source file:org.ow2.bonita.runtime.AbstractClassLoader.java

private void releaseConnection(URL url) {
    if (LOG.isLoggable(Level.INFO)) {
        LOG.info("Releasing class loader: " + this);
    }//from w  w  w. ja va  2s .  co m
    try {
        final URLConnection conn = url.openConnection();
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info("Getting connection of url: " + url + ", conn=" + conn);
        }
        final String fileURLConnectionClassName = "sun.net.www.protocol.file.FileURLConnection";
        if (conn instanceof JarURLConnection) {
            JarFile jarfile = ((JarURLConnection) conn).getJarFile();
            if (LOG.isLoggable(Level.INFO)) {
                LOG.info("Closing jar file: " + jarfile.getName());
            }
            jarfile.close();
        } else if (conn.getClass().getName().equals(fileURLConnectionClassName)) {
            if (LOG.isLoggable(Level.INFO)) {
                LOG.info("Closing connection (" + fileURLConnectionClassName + ": " + conn);
            }
            Method close = conn.getClass().getMethod("close", (Class[]) null);
            close.invoke(conn, (Object[]) null);
        }
    } catch (Exception e) {
        if (LOG.isLoggable(Level.WARNING)) {
            LOG.warning("Error while releasing classloader: " + this + ": " + Misc.getStackTraceFrom(e));
        }
        e.printStackTrace();
    }
    close();
}