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.nubits.nubot.notifications.jhipchat.HipChat.java

public List<Room> listRooms() {
    String query = String.format(HipChatConstants.ROOMS_LIST_QUERY_FORMAT, HipChatConstants.JSON_FORMAT,
            authToken);//  w  w  w. ja  v  a 2  s  .  c  o  m

    InputStream input = null;
    List<Room> results = null;
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_LIST + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoInput(true);
        input = connection.getInputStream();
        results = RoomParser.parseRoomList(this, input);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return results;
}

From source file:com.nubits.nubot.notifications.jhipchat.HipChat.java

public Room getRoom(String roomId) {
    String query = String.format(HipChatConstants.ROOMS_SHOW_QUERY_FORMAT, roomId, HipChatConstants.JSON_FORMAT,
            authToken);// w w  w  .j av  a2 s .  c  om

    InputStream input = null;
    Room result = null;
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_SHOW + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoInput(true);
        input = connection.getInputStream();
        result = RoomParser.parseRoom(this, input);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return result;
}

From source file:com.nubits.nubot.notifications.jhipchat.HipChat.java

public List<User> listUsers() {
    String query = String.format(HipChatConstants.USERS_LIST_QUERY_FORMAT, HipChatConstants.JSON_FORMAT,
            authToken);//from  www  .jav  a  2  s  .com

    InputStream input = null;
    List<User> results = null;
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.USERS_LIST + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoInput(true);
        input = connection.getInputStream();
        results = UserParser.parseUserList(this, input);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return results;
}

From source file:es.tekniker.framework.ktek.questionnaire.mng.server.EventServiceClient.java

public boolean subscribeContext(String codUser, String nameContext) {
    HttpURLConnection conn = null;
    StringBuffer strBOutput = new StringBuffer();
    boolean boolOK = true;
    String input = null;/*w w w.  j av a2s .com*/
    StringBuffer stbInput = new StringBuffer();

    try {
        log.debug("subscribeContext Start ");

        conn = getEventServiceSEConnection(methodSubscribeContext, endpointEventService, headerContentTypeJSON);

        stbInput.append("{\"entities\": [{\"type\": \"" + typeContextValue
                + "\",\"isPattern\": \"false\",\"id\": \"" + codUser + "\" } ],");
        stbInput.append("\"attributes\": [\"" + nameContext + "\"] ,");
        stbInput.append("\"reference\": \"" + notificationEndpoint + "\",");
        stbInput.append("\"duration\": \"P1M\",");
        stbInput.append("\"notifyConditions\": [ {\"type\": \"ONCHANGE\",\"condValues\": [\"" + nameContext
                + "\"]}],\"throttling\": \"PT5S\"}");

        input = stbInput.toString();
        log.debug(input);

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() == 200) {
            log.debug("subscribeContext Response code " + conn.getResponseCode());
        } else {
            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException(
                        "subscribeContext Failed : HTTP error code : " + conn.getResponseCode());
            }
        }

        log.debug("subscribeContext OutputStream wrote");

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        log.debug("subscribeContext Waiting server response ");

        String output;
        log.debug("subscribeContext Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            strBOutput.append(output);
            log.debug(output);
        }

        conn.disconnect();

        boolOK = true;

    } catch (MalformedURLException e) {
        log.error("subscribeContext MalformedURLException " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.error("subscribeContext IOException " + e.getMessage());
        e.printStackTrace();
    }

    return boolOK;
}

From source file:foam.littlej.android.app.net.MainHttpClient.java

public String SendMultiPartData(String URL, MultipartEntity postData) throws IOException {

    Log.d(CLASS_TAG, "PostFileUpload(): upload file to server.");

    // Dipo Fix//from   w  ww.  j  a  va 2s .c  o  m
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (postData != null) {
            Log.i(CLASS_TAG, "PostFileUpload(): ");
            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(postData);
            // Header
            // httpost.addHeader("Authorization","Basic "+
            // getCredentials(userName, userPassword));
            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                InputStream serverInput = respEntity.getContent();

                return GetText(serverInput);

            }
        }

    } catch (MalformedURLException ex) {
        log("MalformedURLException", ex.toString());
        ex.printStackTrace();
        return "";
        // fall through and return false
    } catch (Exception ex) {
        return "";
    }
    return "";
}

From source file:es.tekniker.framework.ktek.questionnaire.mng.server.EventServiceClient.java

public boolean updateContext(String codUser, String nameContext, String typeContext, String valueContext,
        boolean valueIsjson) {
    HttpURLConnection conn = null;
    StringBuffer strBOutput = new StringBuffer();
    boolean boolOK = true;
    String input = null;/*from ww  w  . j a  va  2  s . c o m*/
    StringBuffer stbInput = new StringBuffer();

    try {
        log.debug("updateContext Start ");

        conn = getEventServiceSEConnection(methodUpdateContext, endpointEventService, headerContentTypeJSON);

        stbInput.append("{\"contextElements\": [{\"type\": \"" + typeContextValue
                + "\",\"isPattern\": \"false\",\"id\": \"" + codUser + "\",\"attributes\":");
        if (valueIsjson)
            stbInput.append(" [{\"name\": \"" + nameContext + "\",\"type\": \"" + typeContext + "\",\"value\": "
                    + valueContext + "}]}]");
        else
            stbInput.append(" [{\"name\": \"" + nameContext + "\",\"type\": \"" + typeContext
                    + "\",\"value\": \"" + valueContext + "\"}]}]");
        stbInput.append(",\"updateAction\": \"APPEND\"}");

        input = stbInput.toString();
        log.debug(input);

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() == 200) {
            log.debug("updateContext Response code " + conn.getResponseCode());
        } else {
            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException(
                        "updateContext Failed : HTTP error code : " + conn.getResponseCode());
            }
        }

        log.debug("updateContext OutputStream wrote");

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        log.debug("updateContext Waiting server response ");

        String output;
        log.debug("updateContext Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            strBOutput.append(output);
            log.debug(output);
        }

        conn.disconnect();

        boolOK = true;

    } catch (MalformedURLException e) {
        log.error("updateContext MalformedURLException " + e.getMessage());
        e.printStackTrace();
        boolOK = false;
    } catch (IOException e) {
        log.error("updateContext IOException " + e.getMessage());
        e.printStackTrace();
        boolOK = false;
    }

    return boolOK;
}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

public void sendChangesToCozy() {
    List<Expense> unSyncedExpenses = Expense.getAllUnsynced();
    int i = 0;/* w  ww  .j  av a  2s . com*/
    for (Expense expense : unSyncedExpenses) {
        URL urlO = null;
        try {
            JSONObject jsonObject = expense.toJsonObject();
            mBuilder.setProgress(unSyncedExpenses.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new ExpenseSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_expense_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

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

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                expense.setRemoteId(result);
                expense.save();
            }

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

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:org.odk.collect.android.tasks.DownloadFormsTask.java

/**
 * Common routine to download a document from the downloadUrl and save the contents in the file
 * 'f'. Shared by media file download and form file download.
 * /*from   w  w w .jav  a2 s  . c om*/
 * @param f
 * @param downloadUrl
 * @throws Exception
 */
private void downloadFile(File f, String downloadUrl) throws Exception {
    URI uri = null;
    try {
        URL url = new URL(downloadUrl);
        uri = url.toURI();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw e;
    } catch (URISyntaxException e) {
        e.printStackTrace();
        throw e;
    }

    // get shared HttpContext so that authentication and cookies are retained.
    HttpContext localContext = Collect.getInstance().getHttpContext();

    HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(uri);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != 200) {
            String errMsg = Collect.getInstance().getString(R.string.file_fetch_failed, f.getAbsolutePath(),
                    response.getStatusLine().getReasonPhrase(), statusCode);
            Log.e(t, errMsg);
            throw new Exception(errMsg);
        }

        // write connection to file
        InputStream is = null;
        OutputStream os = null;
        try {
            is = response.getEntity().getContent();
            os = new FileOutputStream(f);
            byte buf[] = new byte[1024];
            int len;
            while ((len = is.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            os.flush();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}