List of usage examples for java.net MalformedURLException getLocalizedMessage
public String getLocalizedMessage()
From source file:eu.codeplumbers.cosi.services.CosiFileDownloadService.java
@Override protected void onHandleIntent(Intent intent) { // Do the task here Log.i(CosiFileDownloadService.class.getName(), "Cosi Service running"); // Release the wake lock provided by the WakefulBroadcastReceiver. WakefulBroadcastReceiver.completeWakefulIntent(intent); Device device = Device.registeredDevice(); // cozy register device url fileUrl = device.getUrl() + "/ds-api/data/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); showNotification();//from www .j ava2 s.co m if (isNetworkAvailable()) { try { ArrayList<String> fileStrings = intent.getStringArrayListExtra("fileToDownload"); for (int i = 0; i < fileStrings.size(); i++) { File file = File.load(File.class, Long.valueOf(fileStrings.get(i))); String binaryRemoteId = file.getRemoteId(); if (!binaryRemoteId.isEmpty()) { mBuilder.setProgress(100, 0, false); mBuilder.setContentText("Downloading file: " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); URL urlO = null; try { urlO = new URL(fileUrl + binaryRemoteId + "/binaries/file"); 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("GET"); conn.connect(); int lenghtOfFile = conn.getContentLength(); // read the response int status = conn.getResponseCode(); if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { EventBus.getDefault() .post(new FileSyncEvent(SERVICE_ERROR, conn.getResponseMessage())); stopSelf(); } else { int count = 0; InputStream in = new BufferedInputStream(conn.getInputStream(), 8192); java.io.File newFile = file.getLocalPath(); if (!newFile.exists()) { newFile.createNewFile(); } // Output stream to write file OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files" + file.getPath() + "/" + file.getName()); byte data[] = new byte[1024]; long total = 0; while ((count = in.read(data)) != -1) { total += count; mBuilder.setProgress(lenghtOfFile, (int) total, false); mBuilder.setContentText("Downloading file: " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); // writing data to file output.write(data, 0, count); } // flushing output output.flush(); // closing streams output.close(); in.close(); file.setDownloaded(true); file.save(); } } catch (MalformedURLException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } mNotifyManager.cancel(notification_id); EventBus.getDefault().post(new FileSyncEvent(REFRESH, "Sync OK")); } catch (Exception e) { e.printStackTrace(); mSyncRunning = false; EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); } } else { mSyncRunning = false; EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "No Internet connection")); mBuilder.setContentText("Sync failed because no Internet connection was available"); mNotifyManager.notify(notification_id, mBuilder.build()); } }
From source file:eu.codeplumbers.cosi.services.CosiNoteService.java
@Override protected void onHandleIntent(Intent intent) { // Do the task here Log.i(CosiNoteService.class.getName(), "Cosi Service running"); // Release the wake lock provided by the WakefulBroadcastReceiver. WakefulBroadcastReceiver.completeWakefulIntent(intent); Device device = Device.registeredDevice(); // delete all local notes new Delete().from(Note.class).execute(); // cozy register device url this.url = device.getUrl() + "/ds-api/request/note/cosiall/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); showNotification();//from w w w. java 2s .c o m if (isNetworkAvailable()) { try { URL 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) { for (int i = 0; i < jsonArray.length(); i++) { String version = "0"; if (jsonArray.getJSONObject(i).has("version")) { version = jsonArray.getJSONObject(i).getString("version"); } JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value"); Note note = Note.getByRemoteId(noteJson.get("_id").toString()); if (note == null) { note = new Note(noteJson); } else { boolean versionIncremented = note.getVersion() < Integer .valueOf(noteJson.getString("version")); int modifiedOnServer = DateUtils.compareDateStrings( Long.valueOf(note.getLastModificationValueOf()), noteJson.getLong("lastModificationValueOf")); if (versionIncremented || modifiedOnServer == -1) { note.setTitle(noteJson.getString("title")); note.setContent(noteJson.getString("content")); note.setCreationDate(noteJson.getString("creationDate")); note.setLastModificationDate(noteJson.getString("lastModificationDate")); note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf")); note.setParentId(noteJson.getString("parent_id")); // TODO: 10/3/16 // handle note paths note.setPath(noteJson.getString("path")); note.setVersion(Integer.valueOf(version)); } } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Getting note : " + note.getTitle()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle())); note.save(); } } else { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response")); } in.close(); conn.disconnect(); mNotifyManager.cancel(notification_id); EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK")); } catch (MalformedURLException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } } else { mSyncRunning = false; EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection")); mBuilder.setContentText("Sync failed because no Internet connection was available"); mNotifyManager.notify(notification_id, mBuilder.build()); } }
From source file:org.deegree.maven.ithelper.ServiceIntegrationTestHelper.java
public void testLayers(String service) throws MojoFailureException { if (!service.equals("WMS")) { return;/* w ww.ja va 2s . c om*/ } String address = createBaseURL() + "services/wms?request=GetCapabilities&version=1.1.1&service=" + service; String currentLayer = null; try { WMSClient client = new WMSClient(new URL(address), 360, 360); for (String layer : client.getNamedLayers()) { log.info("Retrieving map for layer " + layer); currentLayer = layer; List<String> layers = singletonList(layer); String srs = client.getCoordinateSystems(layer).getFirst(); Envelope bbox = client.getBoundingBox(srs, layer); if (bbox == null) { bbox = client.getLatLonBoundingBox(layer); if (bbox == null) { bbox = new GeometryFactory().createEnvelope(-180, -90, 180, 90, CRSUtils.EPSG_4326); } bbox = new GeometryTransformer(CRSManager.lookup(srs)).transform(bbox); } GetMap gm = new GetMap(layers, 100, 100, bbox, CRSManager.lookup(srs), client.getFormats(GetMap).getFirst(), true); Object img = ImageIO.read(client.getMap(gm)); if (img == null) { throw new MojoFailureException("Retrieving map for " + layer + " failed."); } } } catch (MalformedURLException e) { log.debug(e); throw new MojoFailureException( "Retrieving capabilities for " + service + " failed: " + e.getLocalizedMessage(), e); } catch (IOException e) { log.debug(e); throw new MojoFailureException( "Retrieving map for " + currentLayer + " failed: " + e.getLocalizedMessage(), e); } catch (Throwable e) { log.debug(e); throw new MojoFailureException("Layer " + currentLayer + " had no bounding box.", e); } }
From source file:com.qut.middleware.esoemanager.manager.logic.impl.ServiceCryptoImpl.java
private String generateSubjectDN(String service) { try {// ww w .j a v a 2 s .c o m String result = new String(); URL serviceURL = new URL(service); String[] components = serviceURL.getHost().split("\\."); for (String component : components) { if (result.length() != 0) result = result + ","; result = result + "dc=" + component; } return result; } catch (MalformedURLException e) { this.logger.error("Error attempting to generate certificate subjectDN " + e.getLocalizedMessage()); this.logger.debug(e.toString()); return "dc=" + service; } }
From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java
public void sendChangesToCozy() { List<LoyaltyCard> unSyncedLoyaltyCards = LoyaltyCard.getAllUnsynced(); int i = 0;/*from w w w. ja v a 2 s. co m*/ for (LoyaltyCard loyaltyCard : unSyncedLoyaltyCards) { URL urlO = null; try { JSONObject jsonObject = loyaltyCard.toJsonObject(); mBuilder.setProgress(unSyncedLoyaltyCards.size(), i + 1, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault().post( new LoyaltyCardSyncEvent(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"); loyaltyCard.setRemoteId(result); loyaltyCard.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } i++; } }
From source file:se.trixon.jota.server.Server.java
private void startServer() { mRmiNameServer = JotaHelper.getRmiName(SystemHelper.getHostname(), mPort, JotaServer.class); try {/*w ww. jav a 2 s . c o m*/ LocateRegistry.createRegistry(mPort); mServerVmid = new VMID(); //mServerOptions = new ServerOptions(); Naming.rebind(mRmiNameServer, this); String message = String.format("started: %s (%s)", mRmiNameServer, mServerVmid.toString()); Xlog.timedOut(message); listJobs(); listTasks(); getStatus(); if (mOptions.isCronActive()) { cronOn(); } } catch (IllegalArgumentException e) { Xlog.timedErr(e.getLocalizedMessage()); Jota.exit(); } catch (RemoteException e) { //nvm - server was running Xlog.timedErr(e.getLocalizedMessage()); Jota.exit(); } catch (MalformedURLException ex) { Xlog.timedErr(ex.getLocalizedMessage()); Jota.exit(); } }
From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java
public void sendChangesToCozy() { List<Expense> unSyncedExpenses = Expense.getAllUnsynced(); int i = 0;//from ww w . ja va 2 s . c o m 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.apache.jmeter.protocol.ftp.sampler.FTPSampler.java
@Override public SampleResult sample(Entry e) { SampleResult res = new SampleResult(); res.setSuccessful(false); // Assume failure String remote = getRemoteFilename(); String local = getLocalFilename(); boolean binaryTransfer = isBinaryMode(); res.setSampleLabel(getName());//from w ww . jav a 2 s.com final String label = getLabel(); res.setSamplerData(label); try { res.setURL(new URL(label)); } catch (MalformedURLException e1) { log.warn("Cannot set URL: " + e1.getLocalizedMessage()); } InputStream input = null; OutputStream output = null; res.sampleStart(); FTPClient ftp = new FTPClient(); try { savedClient = ftp; final int port = getPortAsInt(); if (port > 0) { ftp.connect(getServer(), port); } else { ftp.connect(getServer()); } res.latencyEnd(); int reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftp.login(getUsername(), getPassword())) { if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } ftp.enterLocalPassiveMode();// should probably come from the setup dialog boolean ftpOK = false; if (isUpload()) { String contents = getLocalFileContents(); if (contents.length() > 0) { byte[] bytes = contents.getBytes(); // TODO - charset? input = new ByteArrayInputStream(bytes); res.setBytes(bytes.length); } else { File infile = new File(local); res.setBytes((int) infile.length()); input = new BufferedInputStream(new FileInputStream(infile)); } ftpOK = ftp.storeFile(remote, input); } else { final boolean saveResponse = isSaveResponse(); ByteArrayOutputStream baos = null; // No need to close this OutputStream target = null; // No need to close this if (saveResponse) { baos = new ByteArrayOutputStream(); target = baos; } if (local.length() > 0) { output = new FileOutputStream(local); if (target == null) { target = output; } else { target = new TeeOutputStream(output, baos); } } if (target == null) { target = new NullOutputStream(); } input = ftp.retrieveFileStream(remote); if (input == null) {// Could not access file or other error res.setResponseCode(Integer.toString(ftp.getReplyCode())); res.setResponseMessage(ftp.getReplyString()); } else { long bytes = IOUtils.copy(input, target); ftpOK = bytes > 0; if (saveResponse && baos != null) { res.setResponseData(baos.toByteArray()); if (!binaryTransfer) { res.setDataType(SampleResult.TEXT); } } else { res.setBytes((int) bytes); } } } if (ftpOK) { res.setResponseCodeOK(); res.setResponseMessageOK(); res.setSuccessful(true); } else { res.setResponseCode(Integer.toString(ftp.getReplyCode())); res.setResponseMessage(ftp.getReplyString()); } } else { res.setResponseCode(Integer.toString(ftp.getReplyCode())); res.setResponseMessage(ftp.getReplyString()); } } else { res.setResponseCode("501"); // TODO res.setResponseMessage("Could not connect"); //res.setResponseCode(Integer.toString(ftp.getReplyCode())); res.setResponseMessage(ftp.getReplyString()); } } catch (IOException ex) { res.setResponseCode("000"); // TODO res.setResponseMessage(ex.toString()); } finally { savedClient = null; if (ftp.isConnected()) { try { ftp.logout(); } catch (IOException ignored) { } try { ftp.disconnect(); } catch (IOException ignored) { } } IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } res.sampleEnd(); return res; }
From source file:org.kalypso.ogc.gml.loader.ShapeLoader.java
@Override public void save(final IPoolableObjectType key, final IProgressMonitor monitor, final Object data) throws LoaderException { final String source = key.getLocation(); final URL context = key.getContext(); final String targetSrs = parseSrs(source); try {/*w w w .ja va2 s . co m*/ // TODO: Save in the original coordinate system, // not the one from other sources (e.g map, kalypso coordinate system) final GMLWorkspace workspace = (GMLWorkspace) data; final URL shpURL = m_urlResolver.resolveURL(context, source.split("#")[0]); //$NON-NLS-1$ final IFile file = ResourceUtilities.findFileFromURL(shpURL); if (file != null) ShapeSerializer.serialize(workspace, file.getLocation().toFile().getAbsolutePath(), targetSrs); else throw new LoaderException(Messages.getString("org.kalypso.ogc.gml.loader.ShapeLoader.12") + shpURL); //$NON-NLS-1$ } catch (final MalformedURLException e) { e.printStackTrace(); throw new LoaderException(Messages.getString("org.kalypso.ogc.gml.loader.ShapeLoader.13") + 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.ShapeLoader.15") + e.getLocalizedMessage(), e); //$NON-NLS-1$ } }
From source file:com.snaplogic.snaps.lunex.BaseService.java
@Override protected void process(Document document, String inputViewName) { try {//from w ww . j a v a2s.c om if (isCredentialsSet) { /* Updating Auth header using credentials from input document */ setAuthHeaderProp(username.eval(document).toString(), password.eval(document).toString()); } RequestBuilder rBuilder = new RequestBuilder().addDoc(document).addEndPointIP(lunexHost) .addHeaders(headersProperties).addQueryParams(queryParams) .addRequestBody(prepareJson(requestContentInfo, document)).addResource(resourceType) .addSnapTye(snapsType).addMethod(httpMethod); String response = RequestProcessor.getInstance().execute(rBuilder); int statusCode = RequestProcessor.getInstance().getStatusCode(); /* * Writing HTTP STATUS codes in between 100-299 to success view and other codes will * move to Error view. * * Success: HTTP 1XX-Request received, continuing process. HTTP 2XX-Action requested by * the client was received, understood, accepted and processed successfully. * * Error: HTTP 3XX-The client must take additional action to complete the request. HTTP * 4XX-Intended for cases in which the client seems to have errored. HTTP 5XX-The server * failed to fulfill an apparently valid request. */ if (statusCode >= 100 && statusCode < HttpStatus.SC_MULTIPLE_CHOICES) { Map<String, Object> map = new HashMap<String, Object>(); map.put(STATUS_CODE_TAG, statusCode); map.put(resourceType, OBJECT_MAPPER.readValue(response, MAP_TYPE_REFERENCE)); outputViews.write(documentUtility.newDocument(map)); } else { writeToErrorView(statusCode, HTTP_ERROR_REASON, HTTP_ERROR_RESOLUTION, response); } } catch (MalformedURLException ex) { writeToErrorView(ex.getLocalizedMessage(), MALFORMEDURL_ERROR_REASON, MALFORMEDURL_ERROR_RESOLUTION, ex); } catch (IllegalStateException ex) { writeToErrorView(CONTENT_STREAM_ERROR, ILLEGAL_STATE_REASON, ILLEGAL_STATE_RESOLUTION, ex); } catch (JsonParseException ex) { writeToErrorView(JSON_PARSING_ERROR, JSON_PARSING_REASON, JSON_PARSING_RESOLUTION, ex); } catch (IOException ex) { writeToErrorView(IO_ERROR, IO_ERROR_REASON, IO_ERROR_RESOLUTION, ex); } catch (Exception ex) { writeToErrorView(ERRORMSG, ERROR_REASON, ERROR_RESOLUTION, ex); } }