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.appsimobile.appsii.module.weather.WeatherLoadingService.java

private static boolean downloadFile(Context context, ImageDownloadHelper.PhotoInfo photoInfo, String woeid,
        int idx) {

    WeatherUtils weatherUtils = AppInjector.provideWeatherUtils();

    File cacheDir = weatherUtils.getWeatherPhotoCacheDir(context);
    String fileName = weatherUtils.createPhotoFileName(woeid, idx);
    File photoImage = new File(cacheDir, fileName);
    try {/*from  w  w  w.ja  v  a 2  s.c  o m*/
        URL url = new URL(photoInfo.url);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(30000);
        InputStream in = new BufferedInputStream(connection.getInputStream());
        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(photoImage));

            int totalRead = 0;
            try {
                byte[] bytes = new byte[64 * 1024];
                int read;
                while ((read = in.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                    totalRead += read;
                }
                out.flush();
            } finally {
                out.close();
            }
            if (BuildConfig.DEBUG) {
                Log.d("WeatherLoadingService", "received " + totalRead + " bytes for: " + photoInfo.url);
            }
        } finally {
            in.close();
        }
        return true;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:fr.cls.atoll.motu.processor.wps.TestServiceMetadata.java

public static JAXBElement<?> testdom4j() {

    URL url = null;//from w w w. j av a2 s.  c  o m
    JAXBElement<?> jaxbElement = null;
    try {
        // url = new
        // URL("file:///c:/Documents and Settings/dearith/Mes documents/Atoll/SchemaIso/TestServiceMetadataOK.xml");
        // url = Organizer.findResource("src/main/resources/fmpp/src/ServiceMetadataOpendap.xml");
        url = Organizer.findResource("fmpp/out/serviceMetadata_motu-opendap-aviso.xml");
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        Element root = document.getRootElement();

        // iterate through child elements of root
        // for ( Iterator<Element> i = root.elementIterator(); i.hasNext(); ) {
        // Element element = (Element) i.next();
        // System.out.println(element);
        // // do something
        // }

        JAXBWriter jaxbWriter = new JAXBWriter(ServiceMetadata.ISO19139_SHEMA_PACK_NAME);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        jaxbWriter.setOutput(byteArrayOutputStream);

        // FileWriter fileWriter = new FileWriter("./testdom4j.xml");
        // jaxbWriter.setOutput(fileWriter);
        jaxbWriter.startDocument();
        jaxbWriter.writeElement(root);
        jaxbWriter.endDocument();
        // fileWriter.close();

        ServiceMetadata serviceMetadata = new ServiceMetadata();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                byteArrayOutputStream.toByteArray());
        jaxbElement = serviceMetadata.unmarshallIso19139(byteArrayInputStream);

        ServiceMetadata.dump(jaxbElement);

        ServiceMetadata servMetadata = new ServiceMetadata();
        jaxbElement = servMetadata.dom4jToJaxb(document);

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MotuMarshallException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MotuExceptionBase e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jaxbElement;

}

From source file:com.zzl.zl_app.cache.Utility.java

public static String uploadFile(File file, String RequestURL, String fileName) {
    Tools.log("IO", "RequestURL:" + RequestURL);
    String result = null;//w  w  w .j a v a2  s  . c  om
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(Utility.SET_SOCKET_TIMEOUT);
        conn.setConnectTimeout(Utility.SET_CONNECTION_TIMEOUT);
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestMethod("POST"); // ?
        conn.setRequestProperty("Charset", CHARSET); // ?
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename?????? :abc.png
             */
            sb.append("Content-Disposition: form-data; name=\"voice\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            Tools.log("FileSize", "file:" + file.length());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
                Tools.log("FileSize", "size:" + len);
            }

            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            dos.close();
            is.close();
            /**
             * ??? 200=? ?????
             */
            int res = conn.getResponseCode();
            Tools.log("IO", "ResponseCode:" + res);
            if (res == 200) {
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
            }

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

From source file:xqpark.ParkApi.java

/**
 * API?//from ww w.jav  a2s  .  com
 * @param ?url
 * @return APIJSON?
 * @throws JSONException
 * @throws IOException 
 * @throws ParseException 
 */
public static JSONObject loadJSON(String url) throws JSONException {
    StringBuilder json = new StringBuilder();
    try {
        URLEncoder.encode(url, "UTF-8");
        URL urlObject = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) urlObject.openConnection();

        uc.setDoOutput(true);//  URL 
        uc.setDoInput(true);//  URL 
        uc.setUseCaches(false);
        uc.setRequestMethod("POST");

        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONObject responseJson = new JSONObject(json.toString());
    return responseJson;
}

From source file:com.truebanana.http.HTTPRequest.java

/**
 * Creates an {@link HTTPRequest} to connect to the specified URL. Use the different setters to modify the request then use {@link HTTPRequest#executeAsync()} to execute the request. By default, the request method is GET with 10000ms connect timeout and read timeout.
 *
 * @param url The URL to connect to./*from  w  ww.j a  v  a 2s. c  om*/
 * @return An {@link HTTPRequest}
 */
public static HTTPRequest create(String url) {
    HTTPRequest request = new HTTPRequest();
    request.url = url;
    try {
        URL u = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Invalid URL.");
    }

    return request;
}

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Remove a mapset from a Location in the catalog.
 *
 * <p>Note: this doesn't remove the file. The file removal has to be done separately</p>
 *      /*from w  w  w . j  av a2 s  .c  o m*/
 * @param locationPath path to the location from which the mapset has to be removed.
 * @param mapsetName the name of the mapset to remove
 */
public synchronized static void removeMapsetFromCatalog(String locationPath, String mapsetName) {
    // URL locationId = JGrassService.createId(locationPath);
    try {
        File locationFile = new File(locationPath);
        ID locationId = new ID(locationFile.toURI().toURL());
        JGrassService location = CatalogPlugin.getDefault().getLocalCatalog().getById(JGrassService.class,
                locationId, ProgressManager.instance().get());
        location.removeMapset(mapsetName);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        String message = "An error occurred while removing the mapset to the catalog";
        ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, JGrassPlugin.PLUGIN_ID, e);
    }
}

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Add a mapset to a Location in the catalog.
 *
 * <p>Note: this doesn't add the file. The file adding has to be done separately</p>
 *      // ww  w.ja v  a2 s.c  o  m
 * @param locationPath path to the location to which the mapset has to be added.
 * @param mapsetName the name of the mapset to add
 * @return the added {@linkplain JGrassMapsetGeoResource mapset}
 */
public synchronized static JGrassMapsetGeoResource addMapsetToCatalog(String locationPath, String mapsetName) {
    // URL locationId = JGrassService.createId(locationPath);
    File locationFile = new File(locationPath);
    try {
        ID locationId = new ID(locationFile.toURI().toURL());
        JGrassService location = CatalogPlugin.getDefault().getLocalCatalog().getById(JGrassService.class,
                locationId, ProgressManager.instance().get());
        return location.addMapset(mapsetName);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        String message = "An error occurred while adding the mapset to the catalog";
        ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, JGrassPlugin.PLUGIN_ID, e);
        return null;
    }
}

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Adds a map to the catalog into the right Mapset.
 * /*from   www. ja  v a  2 s.co m*/
 * <p>Note: this doesn't add the file. The file adding has to be done separately</p>
 *
 * @param locationPath the path to the Location folder.
 * @param mapsetName the name of the Mapset into which to put the map.
 * @param mapName the name of the map to add.
 * @param mapType the format of the map to add.
 * @return the resource that has been added.
 */
public synchronized static JGrassMapGeoResource addMapToCatalog(String locationPath, String mapsetName,
        String mapName, String mapType) {
    // URL mapsetId = JGrassMapsetGeoResource.createId(locationPath, mapsetName);

    JGrassMapsetGeoResource mapset = null;
    try {
        File locationFile = new File(locationPath);

        ID locationId = new ID(locationFile.toURI().toURL());
        URL mapsetUrl = JGrassMapsetGeoResource.createId(locationFile.getAbsolutePath(), mapsetName);
        ID mapsetId = new ID(mapsetUrl);
        ICatalog localCatalog = CatalogPlugin.getDefault().getLocalCatalog();
        mapset = localCatalog.getById(JGrassMapsetGeoResource.class, mapsetId,
                ProgressManager.instance().get());
        if (mapset == null) {
            // try with the service
            // URL locationId = JGrassService.createId(locationPath);
            JGrassService locationService = localCatalog.getById(JGrassService.class, locationId,
                    ProgressManager.instance().get());
            mapset = locationService.getMapsetGeoresourceByName(mapsetName);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        String message = "An error occurred while adding the map to the catalog";
        ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, JGrassPlugin.PLUGIN_ID, e);
    }
    if (mapset == null)
        return null;
    return mapset.addMap(mapName, mapType);
}

From source file:com.jerrellmardis.amphitheatre.task.DownloadTaskHelper.java

public static List<SmbFile> getFiles(String user, String password, String path) {
    Log.d(TAG, path + " " + user + "//" + password);
    NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", user, password);

    List<SmbFile> files = Collections.emptyList();
    //Manually delete all entries. Is this the best way to do it? No.
    List<Video> videos = Select.from(Video.class).where(Condition.prop("video_url").like("%" + path + "%"))
            .list();/*  www.  j  a v a  2s . c  om*/
    Log.d(TAG, "Purging " + videos.size() + " videos from source");
    for (Video vx : videos) {
        vx.delete();
    }

    //Let's do this in a way that's not going to blow out the memory of the device
    Log.d(TAG, "getting files from dir " + path + " with auth " + auth.getDomain() + " " + auth.getName() + " "
            + auth.getUsername() + " " + auth.getPassword());
    SmbFile baseDir = null;
    try {
        baseDir = new SmbFile(path, auth);
        Log.d(TAG, "Base Directory: " + baseDir.getName() + ", " + baseDir.getPath());
        traverseSmbFiles(baseDir, auth);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (SmbException e) {
        e.printStackTrace();
        Log.e(TAG, "SmbException: " + e.getMessage());
    }

    return files;
}

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Reload the service, to which the location refers to. This is ment to be used when new maps
 * are added inside a mapset and the catalog doesn't care to see them. So the tree has to be
 * reloaded.//from w w  w  .  j  ava2s  .c o  m
 * 
 * @param locationPath the path to the affected location
 * @param monitor the progress monitor
 */
public static void refreshJGrassService(String locationPath, final IProgressMonitor monitor) {

    System.out.println("Lock on locationPath = " + Thread.holdsLock(locationPath));
    synchronized (locationPath) {

        /*
         * if the catalog is active, refresh the location in the catalog window
         */
        ID id = null;
        if (JGrassPlugin.getDefault() != null) {
            File locationFile = new File(locationPath);
            try {
                id = new ID(locationFile.toURI().toURL());
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return;
            }
        } else {
            return;
        }
        /*
         * test code to make the catalog understand that the map should be added
         */
        final ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
        final JGrassService originalJGrassService = catalog.getById(JGrassService.class, id, monitor);

        /*
         * create the same service
         */
        if (originalJGrassService == null)
            return;
        final URL ID = originalJGrassService.getIdentifier();
        Map<String, Serializable> connectionParams = originalJGrassService.getConnectionParams();
        IServiceFactory locator = CatalogPlugin.getDefault().getServiceFactory();
        final List<IService> rereadService = locator.acquire(ID, connectionParams);

        /*
         * replace the service
         */
        if (rereadService.size() > 0) {
            Runnable refreshCatalogRunner = new Runnable() {
                public void run() {
                    final IService newJGrassService = rereadService.get(0);
                    catalog.remove(originalJGrassService);
                    catalog.add(newJGrassService);
                }
            };

            new Thread(refreshCatalogRunner).start();
        }
    }
}