Example usage for java.net MalformedURLException printStackTrace

List of usage examples for java.net MalformedURLException printStackTrace

Introduction

In this page you can find the example usage for java.net MalformedURLException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.mono.applink.Facebook.java

public static Element simpleParser(HttpResponse response) {
    Document docs = null;/*w w  w .jav a  2  s  .  com*/
    try {
        docs = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getEntity().getContent());
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SAXException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ParserConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    Element root = docs.getDocumentElement();

    return root;
}

From source file:de.betterform.agent.web.WebFactory.java

/**
 * allow absolute paths otherwise resolve relative to the servlet context
 *
 * @param resolvePath XPath locationpath
 * @return the absolute path or path relative to the servlet context
 * @deprecated/*from   w  ww . ja  v  a  2s.  c o m*/
 */
public static final String resolvePath(String resolvePath, ServletContext servletContext) {
    String path = resolvePath;
    try {
        if (path != null && !(path.startsWith("/"))) {
            path = "/" + path;
        }
        URL pathURL = servletContext.getResource(path);
        if (pathURL != null) {
            path = java.net.URLDecoder.decode(pathURL.getPath(), StandardCharsets.UTF_8.name());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return path;
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceInitializer.java

/**
 * Initializes the security service in a standalone mode - used for applications outside of a container or when
 * run as a standalone jar.//from   w  w  w  . j  a  va 2 s . c  o m
 *
 * @param configFile - The security configuration file to utilize
 * @param logConfig - The logging configuration file to utilize
 * @param startConnections - Configure, load and start repository connections
 * @throws SecurityServiceException @{link com.cws.esolutions.security.exception.SecurityServiceException}
 * if an exception occurs during initialization
 */
public static void initializeService(final String configFile, final String logConfig,
        final boolean startConnections) throws SecurityServiceException {
    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ClassLoader classLoader = SecurityServiceInitializer.class.getClassLoader();
    final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("configFileFile")
            : configFile;
    final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("secLogConfig")
            : logConfig;

    try {
        try {
            DOMConfigurator.configure(Loader.getResource(loggingConfig));
        } catch (NullPointerException npx) {
            try {
                DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL());
            } catch (NullPointerException npx1) {
                System.err.println("Unable to load logging configuration. No logging enabled!");
                System.err.println("");
                npx1.printStackTrace();
            }
        }

        xmlURL = classLoader.getResource(serviceConfig);

        if (xmlURL == null) {
            // try loading from the filesystem
            xmlURL = FileUtils.getFile(serviceConfig).toURI().toURL();
        }

        context = JAXBContext.newInstance(SecurityConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

        SecurityServiceInitializer.svcBean.setConfigData(configData);

        if (startConnections) {
            DAOInitializer.configureAndCreateAuthConnection(
                    new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                    false, SecurityServiceInitializer.svcBean);

            Map<String, DataSource> dsMap = SecurityServiceInitializer.svcBean.getDataSources();

            if (DEBUG) {
                DEBUGGER.debug("dsMap: {}", dsMap);
            }

            if (configData.getResourceConfig() != null) {
                if (dsMap == null) {
                    dsMap = new HashMap<String, DataSource>();
                }

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    if (!(dsMap.containsKey(mgr.getDsName()))) {
                        StringBuilder sBuilder = new StringBuilder()
                                .append("connectTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("socketTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("autoReconnect=" + mgr.getAutoReconnect() + ";")
                                .append("zeroDateTimeBehavior=convertToNull");

                        if (DEBUG) {
                            DEBUGGER.debug("StringBuilder: {}", sBuilder);
                        }

                        BasicDataSource dataSource = new BasicDataSource();
                        dataSource.setDriverClassName(mgr.getDriver());
                        dataSource.setUrl(mgr.getDataSource());
                        dataSource.setUsername(mgr.getDsUser());
                        dataSource.setConnectionProperties(sBuilder.toString());
                        dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getDsSalt(),
                                configData.getSecurityConfig().getSecretAlgorithm(),
                                configData.getSecurityConfig().getIterations(),
                                configData.getSecurityConfig().getKeyBits(),
                                configData.getSecurityConfig().getEncryptionAlgorithm(),
                                configData.getSecurityConfig().getEncryptionInstance(),
                                configData.getSystemConfig().getEncoding()));

                        if (DEBUG) {
                            DEBUGGER.debug("BasicDataSource: {}", dataSource);
                        }

                        dsMap.put(mgr.getDsName(), dataSource);
                    }
                }

                if (DEBUG) {
                    DEBUGGER.debug("dsMap: {}", dsMap);
                }

                SecurityServiceInitializer.svcBean.setDataSources(dsMap);
            }
        }
    } catch (JAXBException jx) {
        jx.printStackTrace();
        throw new SecurityServiceException(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        fnfx.printStackTrace();
        throw new SecurityServiceException(fnfx.getMessage(), fnfx);
    } catch (MalformedURLException mux) {
        mux.printStackTrace();
        throw new SecurityServiceException(mux.getMessage(), mux);
    } catch (SecurityException sx) {
        sx.printStackTrace();
        throw new SecurityServiceException(sx.getMessage(), sx);
    }
}

From source file:fi.tuukka.weather.utils.Utils.java

public static Bitmap loadBitmapFromUrl(String imageAddress) {
    try {//from  ww w. ja  v  a2 s  . c  o m
        URL url = new URL(imageAddress);
        Object content = url.getContent();
        InputStream stream = (InputStream) content;
        // System.out.println("downloaded " + imageAddress);
        return BitmapFactory.decodeStream(stream);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
    }
    return null;
}

From source file:gov.nih.nci.nbia.StandaloneDMV2.java

private static List<String> connectAndReadFromURL(URL url, String fileName, String userId, String passWd) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override//ww  w  .j ava 2  s  .  c  o m
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair("serverManifestLoc", fileName));
        if (userId != null && passWd != null) {
            postParams.add(new BasicNameValuePair("userId", userId));
            httpPostMethod.addHeader("password", passWd);
        }

        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("!!!!!Response code for requesting datda file:
        // " + responseCode);

        if (responseCode != HttpURLConnection.HTTP_OK) {
            return null;
        } else {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}

From source file:com.log4ic.compressor.utils.HttpUtils.java

/**
 * /*from   w  ww  .  j  av  a2s  . co  m*/
 *
 * @param httpUrl
 * @return
 * @throws java.io.IOException
 */
public static String requestFile(String httpUrl) {
    URL url = null;
    try {
        url = new URL(httpUrl);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    if (url == null) {
        return null;
    }
    InputStream in = null;
    InputStreamReader streamReader = null;
    BufferedReader reader = null;
    try {
        in = url.openStream();
        streamReader = new InputStreamReader(in);
        reader = new BufferedReader(streamReader);
        String lineCode;
        StringBuilder pageCodeBuffer = new StringBuilder();
        while ((lineCode = reader.readLine()) != null) {
            pageCodeBuffer.append(lineCode);
            pageCodeBuffer.append("\n");
        }

        return pageCodeBuffer.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (streamReader != null) {
            try {
                streamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.kubotaku.android.openweathermap.lib.util.GeocodeUtil.java

/**
 * Get location name from Address./*from ww  w . jav a  2s  .co  m*/
 * <p/>
 * Use Google Maps Geocode api.
 * <p/>
 *
 * @param locale Locale.
 * @param latlng Address.
 * @return Location name of target address.
 */
public static String pointToName(final Locale locale, final LatLng latlng) {
    String name = "";
    try {
        String requestURL = String.format(API_FROM_LOCATION, latlng.latitude, latlng.longitude);

        String lang = locale.getLanguage();
        requestURL += "&language=" + lang;

        URL url = new URL(requestURL);
        InputStream is = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while (null != (line = reader.readLine())) {
            sb.append(line);
        }
        String data = sb.toString();

        name = GeocodeParser.parseLocationName(data);

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

    return name;
}

From source file:com.kubotaku.android.openweathermap.lib.util.GeocodeUtil.java

/**
 * Get location address from target location name.
 * <p/>/*w  ww .j  av  a  2 s .c o  m*/
 * Use Google Maps Geocode api.
 * <p/>
 *
 * @param locale Locale.
 * @param name   Location name.
 * @return Location address.
 */
public static LatLng nameToPoint(final Locale locale, final String name) {
    LatLng address = null;

    try {
        String utf8Name = URLEncoder.encode(name, "UTF-8");
        String requestURL = String.format(API_FROM_NAME, utf8Name);

        String lang = locale.getLanguage();
        requestURL += "&language=" + lang;

        URL url = new URL(requestURL);
        InputStream is = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while (null != (line = reader.readLine())) {
            sb.append(line);
        }
        String data = sb.toString();

        address = GeocodeParser.parseLocation(data);

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

    return address;
}

From source file:at.ac.uniklu.mobile.sportal.util.Utils.java

/**
 * Downloads a file from the network.// w  ww  .  j  ava  2  s . c  o  m
 * 
 * This function can fail in some cases (e.g. slow network), so if you really need the file, it
 * is recommended to do a few retries.
 * source: http://code.google.com/p/android/issues/detail?id=6066
 *
 * @param sourceUrl the url where the file is located
 * @param retries the number of retries in case the download fails
 * @return the stream if successful, else null
 */
public static byte[] downloadFile(String sourceUrl, int retries) {
    byte[] data = null;

    boolean successful = false;
    retries++; // add the first try
    do {
        try {
            retries--;
            URL url = new URL(sourceUrl);
            URLConnection urlConnection = url.openConnection();

            // set session cookie for authorization purposes (loading id pictures without being logged in is now [2011-07-04] disabled)
            Cookie cookie = Studentportal.getSportalClient().getSessionCookie();
            if (cookie != null) {
                urlConnection.addRequestProperty("Cookie", cookieHeaderString(cookie));
            }

            InputStream in = new BufferedInputStream(urlConnection.getInputStream(), 1024 * 32);
            data = streamToArray(in);
            in.close();
            successful = true;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // if the file doesn't exist, it's pointless to retry
            Log.d(TAG, "file does not exist: " + sourceUrl);
            retries = 0;
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (!successful && retries > 0);

    return data;
}

From source file:com.mpower.mintel.android.utilities.WebUtils.java

public static void addCredentials(String username, String password) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MIntel.getAppContext());
    String scheduleUrl = prefs.getString(PreferencesActivity.KEY_SERVER_URL, null);

    String host = "";

    try {/* w  w  w .  j a  va2s.c om*/
        host = new URL(URLDecoder.decode(scheduleUrl, "utf-8")).getHost();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    addCredentials(username, password, host);
}