List of usage examples for java.net MalformedURLException getLocalizedMessage
public String getLocalizedMessage()
From source file:eu.codeplumbers.cosi.services.CosiCallService.java
/** * Make remote request to get all calls stored in Cozy *///w w w . j av a2 s . c o m public String getRemoteCalls() { URL urlO = null; try { urlO = new URL(designUrl); 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) { EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored.")); Call.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Reading calls on Cozy " + i + "/" + jsonArray.length() + "...")); JSONObject callJson = jsonArray.getJSONObject(i).getJSONObject("value"); Call call = Call.getByRemoteId(callJson.get("_id").toString()); if (call == null) { call = new Call(callJson); } else { call.setRemoteId(callJson.getString("_id")); call.setCallerId(callJson.getString("callerId")); call.setCallerNumber(callJson.getString("callerNumber")); call.setDuration(callJson.getLong("duration")); call.setDateAndTime(callJson.getString("dateAndTime")); call.setType(callJson.getInt("type")); } call.save(); allCalls.add(call); } } } else { errorMessage = new JSONObject(result).getString("error"); EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, errorMessage)); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } return errorMessage; }
From source file:eu.codeplumbers.cosi.services.CosiCallService.java
public void sendChangesToCozy() { List<Call> unSyncedCalls = Call.getAllUnsynced(); int i = 0;/*from w w w . j ava 2 s . c om*/ for (Call call : unSyncedCalls) { URL urlO = null; try { JSONObject jsonObject = call.toJsonObject(); mBuilder.setProgress(unSyncedCalls.size(), i, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new CallSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_calls_send_changes))); 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"); call.setRemoteId(result); call.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } i++; } }
From source file:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFolders() { //File.deleteAllFolders(); URL urlO = null;//w ww .ja v a2 s .c o m try { urlO = new URL(folderUrl); 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) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value"); File file = File.getByRemoteId(folderJson.get("_id").toString()); if (file == null) { file = new File(folderJson, true); } else { file.setName(folderJson.getString("name")); file.setPath(folderJson.getString("path")); file.setCreationDate(folderJson.getString("creationDate")); file.setLastModification(folderJson.getString("lastModification")); file.setTags(folderJson.getString("tags")); } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Indexing remote folder : " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName())); file.save(); createFolder(file.getPath(), file.getName()); allFiles.add(file); } } else { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response")); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } }
From source file:eu.codeplumbers.cosi.services.CosiSmsService.java
private List<Sms> getRemoteMessages() { allSms.clear();//from w w w . j a va 2s .com URL urlO = null; try { urlO = new URL(designUrl); 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) { EventBus.getDefault() .post(new SmsSyncEvent(SYNC_MESSAGE, "Your Cozy has no Text messages stored.")); Sms.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { mBuilder.setProgress(jsonArray.length(), i, false); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_cozy))); JSONObject smsJson = jsonArray.getJSONObject(i).getJSONObject("value"); Sms sms = Sms.getBySystemIdAddressAndBody(smsJson.get("systemId").toString(), smsJson.getString("address"), smsJson.getString("body")); if (sms == null) { sms = new Sms(smsJson); } else { sms.setRemoteId(smsJson.getString("_id")); sms.setSystemId(smsJson.getString("systemId")); sms.setAddress(smsJson.getString("address")); sms.setBody(smsJson.getString("body")); if (smsJson.has("readState")) { sms.setReadState(smsJson.getBoolean("readState")); } sms.setDateAndTime(smsJson.getString("dateAndTime")); sms.setType(smsJson.getInt("type")); } sms.save(); allSms.add(sms); } } } else { errorMessage = "Failed to parse API response"; EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, "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 allSms; }
From source file:eu.codeplumbers.cosi.services.CosiSmsService.java
public void sendChangesToCozy() { List<Sms> unSyncedSms = Sms.getAllUnsynced(); int i = 0;//from w w w. j av a 2 s . co m for (Sms sms : unSyncedSms) { URL urlO = null; try { JSONObject jsonObject = sms.toJsonObject(); mBuilder.setProgress(unSyncedSms.size(), i, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_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"); sms.setRemoteId(result); sms.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } i++; } }
From source file:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFiles() { URL urlO = null;/* w w w .j a v a 2 s .c o m*/ try { urlO = new URL(fileUrl); 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) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value"); File file = File.getByRemoteId(fileJson.get("_id").toString()); if (file == null) { file = new File(fileJson, false); } else { file.setName(fileJson.getString("name")); file.setPath(fileJson.getString("path")); file.setCreationDate(fileJson.getString("creationDate")); file.setLastModification(fileJson.getString("lastModification")); file.setTags(fileJson.getString("tags")); if (fileJson.has("binary")) { file.setBinary(fileJson.getJSONObject("binary").toString()); } file.setIsFile(true); file.setFileClass(fileJson.getString("class")); file.setMimeType(fileJson.getString("mime")); file.setSize(fileJson.getLong("size")); } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Indexing file : " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName())); file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory() + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files" + file.getPath() + "/" + file.getName())); file.save(); allFiles.add(file); } } else { EventBus.getDefault() .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error"))); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } }
From source file:org.eclipse.jubula.app.dbtool.core.DBToolClient.java
/** * Import a project from an export file//from www . ja v a2 s . c o m * @param fileName export file name * @param exportDir directory to use * @param monitor the progress monitor to use */ private void importProject(String fileName, String exportDir, IProgressMonitor monitor) { File impFile = new File(fileName); if (!impFile.isAbsolute()) { impFile = new File(new File(exportDir), fileName); } try { List<URL> fileURLs = new ArrayList<URL>(1); fileURLs.add(impFile.toURI().toURL()); FileStorageBP.importFiles(fileURLs, monitor, this, false); } catch (PMException pme) { writeErrorLine(pme.getLocalizedMessage()); } catch (ProjectDeletedException gdpde) { writeErrorLine(gdpde.getLocalizedMessage()); } catch (MalformedURLException e) { writeErrorLine(e.getLocalizedMessage()); } }
From source file:org.kalypso.ogc.gml.loader.SldLoader.java
@Override public void save(final IPoolableObjectType key, final IProgressMonitor monitor, final Object data) throws LoaderException { final URL context = key.getContext(); final String source = key.getLocation(); if (data instanceof Marshallable) { try {//from www . j ava 2 s. c o m /* create filename */ final File userFile = findUserFile(source); /* Check if already exists -> error */ if (userFile == null) saveToWorkspace(context, source, (Marshallable) data, monitor); else saveToUserStore(userFile, (Marshallable) data, monitor); } catch (final MalformedURLException e) { e.printStackTrace(); throw new LoaderException(Messages.getString("org.kalypso.ogc.gml.loader.SldLoader.7") + source //$NON-NLS-1$ + "\n" + e.getLocalizedMessage(), e); //$NON-NLS-1$ } catch (final Throwable e) { e.printStackTrace(); throw new LoaderException( Messages.getString("org.kalypso.ogc.gml.loader.SldLoader.9") + e.getLocalizedMessage(), e); //$NON-NLS-1$ } } }
From source file:com.lhtechnologies.DoorApp.AuthenticatorService.java
@Override protected void onHandleIntent(Intent intent) { if (intent.getAction().equals(stopAction)) { stopSelf();//from w w w . j a v a 2s . com } else if (intent.getAction().equals(authenticateAction)) { //Check if we want to open the front door or flat door String doorToOpen = FrontDoor; String authCode = null; if (intent.hasExtra(FlatDoor)) { doorToOpen = FlatDoor; authCode = intent.getCharSequenceExtra(FlatDoor).toString(); } if (intent.hasExtra(LetIn)) { doorToOpen = LetIn; } //Now run the connection code (Hope it runs asynchronously and we do not need AsyncTask --- NOPE --YES urlConnection = null; URL url; //Prepare the return intent Intent broadcastIntent = new Intent(AuthenticationFinishedBroadCast); try { //Try to create the URL, return an error if it fails url = new URL(address); if (!url.getProtocol().equals("https")) { throw new MalformedURLException("Please only use https protocol!"); } String password = "password"; KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(getResources().getAssets().open("LH Technologies Root CA.bks"), password.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); urlConnection.setConnectTimeout(15000); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setChunkedStreamingMode(0); OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); //Write our stuff to the output stream; out.write("deviceName=" + deviceName + "&udid=" + udid + "&secret=" + secret + "&clientVersion=" + clientVersion + "&doorToOpen=" + doorToOpen); if (doorToOpen.equals(FlatDoor)) { out.write("&authCode=" + authCode); //Put an extra in so the return knows we opened the flat door broadcastIntent.putExtra(FlatDoor, FlatDoor); } out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); //Read the answer String decodedString; String returnString = ""; while ((decodedString = in.readLine()) != null) { returnString += decodedString; } in.close(); broadcastIntent.putExtra(AuthenticatorReturnCode, returnString); } catch (MalformedURLException e) { broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorMalformedURL); } catch (Exception e) { broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorUndefined); broadcastIntent.putExtra(AuthenticatorErrorDescription, e.getLocalizedMessage()); } finally { if (urlConnection != null) urlConnection.disconnect(); //Now send a broadcast with the result sendOrderedBroadcast(broadcastIntent, null); Log.e(this.getClass().getSimpleName(), "Send Broadcast!"); } } }
From source file:org.geotools.gce.imagemosaic.ImageMosaicFormat.java
/** * @see AbstractGridFormat#getReader(Object, Hints) *//*from www . jav a2s .c om*/ @Override public ImageMosaicReader getReader(Object source, Hints hints) { try { final ImageMosaicReader reader = new ImageMosaicReader(source, hints); return reader; } catch (MalformedURLException e) { if (LOGGER.isLoggable(Level.WARNING)) LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e); return null; } catch (IOException e) { if (LOGGER.isLoggable(Level.WARNING)) LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e); return null; } }