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:cn.com.zzwfang.http.HttpExecuter.java

@Override
public byte[] img(String urlString) {
    HttpURLConnection httpURLConnection = null;
    InputStream inputStream = null;
    ByteArrayOutputStream outputStream = null;
    try {// w ww.jav a  2 s.  c  om
        URL url = new URL(urlString);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setReadTimeout(10 * 1000);
        if (httpURLConnection.getResponseCode() == 200) {
            inputStream = httpURLConnection.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();
            return outputStream.toByteArray();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.vdispatcher.GetBaseInformation.java

@Override
public void run() {
    StringBuilder result = new StringBuilder();
    URL url = null;/*from w ww  .  ja  v a2 s . c om*/
    HttpURLConnection conn = null;
    try {
        url = new URL(BASE_URL);
        conn = (HttpURLConnection) url.openConnection();

        InputStreamReader in = new InputStreamReader(conn.getInputStream());
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            result.append(buff, 0, read);
        }

        JSONObject jsonObject = new JSONObject(result.toString());
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 1; i < data.length(); i++) {
            bases.add(Base.fromJSONArray(data.getJSONArray(i)));
        }

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

From source file:edu.cens.loci.components.GoogleLocalSearchHandler.java

@Override
protected String doInBackground(String... params) {

    String url = null;// w  ww .  ja  v a 2s  .c  o  m
    String keyword = params[0];

    String serverResponse = "";
    String thisLine = "";

    try {
        url = new String(LociConfig.LOCAL_SEARCH_URL + "?v=1.0&sll=" + mCenter.getLatitude() + ","
                + mCenter.getLongitude() + "&q=" + URLEncoder.encode(keyword, "UTF-8") + "&rsz=8" + "&key="
                + LociConfig.MAP_KEY);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }

    HttpGet httpGet = new HttpGet(url);
    HttpClient httpClient = new DefaultHttpClient();

    try {
        HttpResponse response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            while ((thisLine = br.readLine()) != null) {
                serverResponse += thisLine;
            }
        }

    } catch (MalformedURLException me) {
        me.printStackTrace();
    } catch (UnsupportedEncodingException ue) {
        ue.printStackTrace();
    } catch (IOException ie) {
        ie.printStackTrace();
    }

    return serverResponse;
}

From source file:eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java

@Override
protected List<Place> doInBackground(Void... voids) {
    URL urlO = null;/*ww  w  .j  a v  a2 s . co  m*/
    try {
        urlO = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject placeJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Place place = Place.getByLocation(placeJson.get("description").toString(),
                            placeJson.get("latitude").toString(), placeJson.get("longitude").toString());

                    if (place == null) {
                        place = new Place(placeJson);
                    } else {
                        place.setDeviceId(placeJson.getString("deviceId"));
                        place.setAddress(placeJson.getString("address"));
                        place.setDateAndTime(placeJson.getString("dateAndTime"));
                        place.setLongitude(placeJson.getDouble("longitude"));
                        place.setLatitude(placeJson.getDouble("latitude"));
                        place.setRemoteId(placeJson.getString("_id"));
                    }

                    publishProgress("Saving place : " + place.getAddress());
                    place.save();

                    allPlaces.add(place);
                }
            } else {
                publishProgress("Your Cozy has no places stored.");
                return allPlaces;
            }
        } else {
            errorMessage = "Failed to parse API response";
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }

    return allPlaces;
}

From source file:BusinessLogic.Controller.RestController.java

public Plan updatePlan(Plan plan) throws Exception {
    StringBuilder responseS = new StringBuilder();

    try {/*  www.j  av  a 2 s.  c o  m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://locahost/JoyCenter/resources/plans/" + plan.getId());

        Gson gson = new Gson();
        StringEntity input = new StringEntity(gson.toJson(plan));
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    Gson gson = new Gson();
    return gson.fromJson(responseS.toString(), Plan.class);

}

From source file:Activities.java

private String addData(String endpoint) {
    String data = null;/*from w ww  .  jav a 2  s . com*/
    try {
        // Construct request payload
        JSONObject attrObj = new JSONObject();
        attrObj.put("name", "URL");
        attrObj.put("value", "http://www.nvidia.com/game-giveaway");

        JSONArray attrArray = new JSONArray();
        attrArray.add(attrObj);

        TimeZone tz = TimeZone.getTimeZone("UTC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
        df.setTimeZone(tz);
        String dateAsISO = df.format(new Date());

        // Required attributes
        JSONObject obj = new JSONObject();
        obj.put("leadId", "1001");
        obj.put("activityDate", dateAsISO);
        obj.put("activityTypeId", "1001");
        obj.put("primaryAttributeValue", "Game Giveaway");
        obj.put("attributes", attrArray);
        System.out.println(obj);

        // Make request
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-type", "application/json");
        urlConn.setRequestProperty("accept", "application/json");
        urlConn.connect();
        OutputStream os = urlConn.getOutputStream();
        os.write(obj.toJSONString().getBytes());
        os.close();

        // Inspect response
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            System.out.println("Status: 200");
            InputStream inStream = urlConn.getInputStream();
            data = convertStreamToString(inStream);
            System.out.println(data);
        } else {
            System.out.println(responseCode);
            data = "Status:" + responseCode;
        }
    } catch (MalformedURLException e) {
        System.out.println("URL not valid.");
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }

    return data;
}

From source file:ai.h2o.servicebuilder.MakePythonWarServlet.java

public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    try {/*  ww w  .  j  a va  2  s .  co  m*/
        servletPath = new File(servletConfig.getServletContext().getResource("/").getPath());
        logger.debug("servletPath = " + servletPath);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

From source file:org.datalift.sdmxdatacube.SDMXDataCubeTransformer.java

public ByteArrayOutputStream convertSDMXToDataCube(InputStream sourceStream, RDFFormat rdfFormat) {
    // TODO replace structures and data with dataset.
    ReadableDataLocation dataset = readableDataLocationFactory.getReadableDataLocation(sourceStream);
    ReadableDataLocation structures = null;
    ReadableDataLocation data = null;//from www.  j  a va 2s .c  o m
    try {
        structures = readableDataLocationFactory.getReadableDataLocation(new URL(
                "http://imf.sdmxregistry.org/ws/restInterfaceV2_1/dataflow/ALL/ALL/LATEST/?detail=full&references=descendants"));
        data = readableDataLocationFactory.getReadableDataLocation(new URL(
                "http://imf.sdmxregistry.org/ws/restInterfaceV2_1/Data/IMF,PGI,1.0/193+223+156.BCA+BGS...?lastNObservations=12"));

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /* Working on structure */

    // Build an object representation of the SDMX.
    SdmxBeans beans = structureParsingManager.parseStructures(structures).getStructureBeans(false);

    // Write to the in memory manager, this is used to resolve cross-referenced structures later
    inMemoryRetrievalManager.saveStructures(beans);

    structureWritingManager.writeStructures(beans, new RDFStructureOutputFormat(rdfFormat),
            new ByteArrayOutputStream());

    /* Working on data */

    // Create a reader, we either need the datastructure at this point, or access to get the datastructure.
    DataReaderEngine dataReader = dataReaderManager.getDataReaderEngine(data,
            new InMemoryRetrievalManager(beans));

    ByteArrayOutputStream convertedStream = new ByteArrayOutputStream();
    DataWriterEngine dataWriter = dataWriterManager.getDataWriterEngine(
            new RDFDataOutputFormat((DataflowBean) beans.getDataflows().toArray()[0], rdfFormat),
            convertedStream);

    // Copy to writer, copyheader=true, closewriter on completion=true
    dataReaderWriterTransform.copyToWriter(dataReader, dataWriter, true, true);

    return convertedStream;
}

From source file:de.nava.informa.impl.hibernate.TestInformaPersistence.java

private Channel getChannel(String string, Channel existing) {
    log.info("Getting channel: " + string);
    synchronized (builder) {
        Channel aChannel = null;//from  w  ww.j a  va 2s .com
        try {
            builder.beginTransaction();
            if (existing == null) {
                aChannel = (Channel) channelRegistry.addChannel(new URL(string), 30, false);
            } else {
                aChannel = (Channel) channelRegistry.addChannel(existing, false, 30);
            }
            long chanid = aChannel.getId();
            log.info("Got channel: " + aChannel + "(id =" + chanid + ")");
            aChannel.addObserver(this);
            builder.endTransaction();
            channelRegistry.activateChannel(aChannel, 60);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ChannelBuilderException e1) {
            e1.printStackTrace();
        }
        return aChannel;
    }
}

From source file:edu.lternet.pasta.dml.parser.document.DocumentDataPackageParserTest.java

private DataPackage loadDataPackage() throws Exception {

    DataPackage dataPackage = null;/*from  www .  j  a v  a  2 s  . c o m*/
    String documentURL = TEST_SERVER + "?action=read&qformat=xml&docid=" + TEST_DOCID;
    InputStream inputStream = null;
    boolean success;
    URL url;

    //create the DataPackage with data table Entity
    try {
        url = new URL(documentURL);
        inputStream = url.openStream();
        dataPackage = dataManager.parseMetadata(inputStream);
        //load the data table to the database
        success = dataManager.loadDataToDB(dataPackage, endPointInfo);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw (e);
    } catch (IOException e) {
        e.printStackTrace();
        throw (e);
    } catch (Exception e) {
        e.printStackTrace();
        throw (e);
    }
    return dataPackage;
}