List of usage examples for java.net MalformedURLException toString
public String toString()
From source file:id.ac.idu.webui.administrasi.pegawai.MpegawaiDetailCtrl.java
public void onClick$btnFoto(Event event) throws InterruptedException { try {//from w w w.java 2 s . co m image.setContent(new org.zkoss.image.AImage(new URL(txtb_foto.getValue()))); } catch (MalformedURLException e) { ZksampleMessageUtils.showErrorMessage("Harap masukkan protokol, contoh: Http://"); } catch (IOException e) { ZksampleMessageUtils.showErrorMessage("Gambar tidak bisa dibaca atau ditemukan"); } catch (IllegalArgumentException e) { if (StringUtils.containsIgnoreCase(e.toString(), "host = null")) { ZksampleMessageUtils.showErrorMessage("Harap masukkan host, contoh: Http://host.com"); } } catch (NullPointerException e) { ZksampleMessageUtils.showErrorMessage("URL yang anda masukkan salah"); } }
From source file:org.onecmdb.core.utils.xml.XmlParser.java
private void loadBeans() { beans = new ArrayList<CiBean>(); for (String url : urls) { //log.info("Load provider url '" + url + "'"); if (this.beanConfig != null) { if (this.beanConfig.isImported(url)) { continue; }// w ww .java 2 s. c o m this.beanConfig.importURL(url); } // Need to locate this url. InputStream input = null; URL u = null; if (url.startsWith("res:") || url.startsWith("classpath:")) { int index = url.indexOf(':'); String resName = url.substring(index + 1); u = this.getClass().getClassLoader().getResource(resName); if (u == null) { //log.error("Resource '" + resName + "' not found"); throw new IllegalArgumentException("No resource with name " + resName + " found"); } } else { try { u = new URL(url); } catch (MalformedURLException e) { //log.error("Url '" + url + "' malformed"); e.printStackTrace(); throw new IllegalArgumentException("Not a corect url:" + e.toString(), e); } } //log.debug("load url <" + u.getPath() + ">"); try { input = u.openStream(); } catch (IOException e) { e.printStackTrace(); //log.error("Can't open url '" + u.toExternalForm() + "'"); throw new IllegalArgumentException("Can't open inputStream for url " + url + " :" + e.toString(), e); } try { beans.addAll(parseInputStream(input)); } catch (DocumentException e) { //log.error("Parsing url '" + u.toExternalForm() + "'", e); //e.printStackTrace(); System.out.println("ERROR in URL " + url); throw new IllegalAccessError("Can't parse XML URL[" + url + "]:" + e.toString()); } finally { // Close it or ? if (input != null) { try { input.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } // Build bean map. beanMap = new HashMap<String, CiBean>(); for (CiBean bean : beans) { beanMap.put(bean.getAlias(), bean); } this.beansLoaded = true; }
From source file:com.miz.mizuu.fragments.NetworkBrowserFragment.java
private void browse(final String path) { if (!isLoading && path.endsWith("/")) { new Thread() { @Override/*from w w w .j av a 2s . c o m*/ public void run() { try { getActivity().runOnUiThread(new Runnable() { @Override public void run() { setLoading(true); } }); // Get the user visible path visiblePath = path.substring(path.indexOf("@") + 1); // Get content of the currently selected path SmbFile currentPath = new SmbFile(path); currentPathName = currentPath.getName(); SmbFile[] list = currentPath.listFiles(); currentPathContent.clear(); final ArrayList<NetworkFile> currentList = new ArrayList<NetworkFile>(); for (int i = 0; i < list.length; i++) { currentList.add(new NetworkFile(list[i])); currentPathContent.add(list[i].getCanonicalPath()); } if (isAdded()) getActivity().runOnUiThread(new Runnable() { @Override public void run() { currentPathAdapter.setFiles(currentList); currentPathAdapter.notifyDataSetChanged(); } }); if (!currentPath.getParent().equals("smb://")) { // Set parent path parentPath = currentPath.getParent(); parentParentPath = new SmbFile(parentPath).getParent(); // Get content of the parent path SmbFile[] pList = new SmbFile(parentPath).listFiles(); parentPathContent.clear(); final ArrayList<NetworkFile> parentList = new ArrayList<NetworkFile>(); for (int i = 0; i < pList.length; i++) { if (pList[i].isDirectory()) { parentList.add(new NetworkFile(pList[i])); parentPathContent.add(pList[i].getCanonicalPath()); } } if (isAdded()) getActivity().runOnUiThread(new Runnable() { @Override public void run() { parentPathAdapter.setFiles(parentList); parentPathAdapter.notifyDataSetChanged(); } }); } else { if (isAdded()) getActivity().runOnUiThread(new Runnable() { @Override public void run() { parentPathAdapter.setFiles(new ArrayList<NetworkFile>()); parentPathAdapter.notifyDataSetChanged(); } }); } if (isAdded()) getActivity().runOnUiThread(new Runnable() { @Override public void run() { getActivity().getActionBar().setSubtitle(visiblePath); setLoading(false); } }); } catch (MalformedURLException e) { } catch (final SmbException e) { if (isAdded()) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show(); } } ); } } } }.start(); } }
From source file:edu.caltech.ipac.firefly.server.query.IpacTablePartProcessor.java
public void downloadFile(URL url, File outFile) throws IOException, EndUserException { URLConnection conn = null;// w w w. j a va 2 s . co m try { Map<String, String> cookies = isSecurityAware() ? ServerContext.getRequestOwner().getIdentityCookies() : null; conn = URLDownload.makeConnection(url, cookies); conn.setRequestProperty("Accept", "*/*"); URLDownload.getDataToFile(conn, outFile); } catch (MalformedURLException e) { LOGGER.error(e, "Bad URL"); throw makeException(e, "WISE Query Failed - bad url."); } catch (FailedRequestException e) { LOGGER.error(e, e.toString()); if (conn != null && conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int respCode = httpConn.getResponseCode(); String desc = respCode == 200 ? e.getMessage() : HttpStatus.getStatusText(respCode); throw new EndUserException("Search Failed: " + desc, e.getDetailMessage(), e); } else { throw makeException(e, "Query Failed - network error."); } } catch (IOException e) { if (conn != null && conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int respCode = httpConn.getResponseCode(); String desc = respCode == 200 ? e.getMessage() : HttpStatus.getStatusText(respCode); throw new EndUserException("Search Failed: " + desc, e.getMessage(), e); } else { throw makeException(e, "Query Failed - network error."); } } }
From source file:cz.muni.fi.japanesedictionary.parser.ParserService.java
/** * Downloads dictionaries.//from ww w. j a v a2 s . c o m */ protected void onHandleIntent() { Log.i(LOG_TAG, "Creating parser service"); Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class); resultIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(this).setAutoCancel(false).setOngoing(true) .setContentTitle(getString(R.string.dictionary_download_title)) .setContentText(getString(R.string.dictionary_download_in_progress) + " (1/5)") .setSmallIcon(R.drawable.ic_notification).setProgress(100, 0, false).setContentInfo("0%") .setContentIntent(resultPendingIntent); startForeground(0, mNotification); mNotifyManager.notify(0, mBuilder.build()); File storage; if (MainActivity.canWriteExternalStorage()) { // external storage available storage = getExternalCacheDir(); } else { storage = getCacheDir(); } if (storage == null) { throw new IllegalStateException("External storage isn't accessible"); } // free sapce controll StatFs stat = new StatFs(storage.getPath()); long bytesAvailable; if (Build.VERSION.SDK_INT < 18) { bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks(); } else { bytesAvailable = stat.getAvailableBytes(); } long megAvailable = bytesAvailable / 1048576; Log.d(LOG_TAG, "Megs free :" + megAvailable); if (megAvailable < 140) { mInternetReceiver = null; mNotEnoughSpace = true; stopSelf(mStartId); return; } this.registerReceiver(mInternetReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); boolean english = sharedPrefs.getBoolean("language_english", false); boolean french = sharedPrefs.getBoolean("language_french", false); boolean dutch = sharedPrefs.getBoolean("language_dutch", false); boolean german = sharedPrefs.getBoolean("language_german", false); boolean russian = sharedPrefs.getBoolean("language_russian", false); if (!english && !french && !dutch && !german && !russian) { Log.i(LOG_TAG, "Setting english as only translation language"); SharedPreferences.Editor editor_lang = sharedPrefs.edit(); editor_lang.putBoolean("language_english", true); editor_lang.commit(); } String dictionaryPath; String kanjiDictPath; URL url; try { url = new URL(ParserService.DICTIONARY_PATH); } catch (MalformedURLException ex) { Log.e(LOG_TAG, "Error: creating url for downloading dictionary"); return; } try { dictionaryPath = storage.getPath() + File.separator + "dictionary.zip"; File outputFile = new File(dictionaryPath); if (outputFile.exists()) { outputFile.delete(); } mDownloadJMDictFrom = url; mDownloadJMDictTo = outputFile; mDownloadingJMDict = true; mDownloadInProgress = true; // downloading kanjidict url = null; try { url = new URL(ParserService.KANJIDICT_PATH); } catch (MalformedURLException ex) { Log.e(LOG_TAG, "Error: creating url for downloading kanjidict2"); } if (url != null) { kanjiDictPath = storage.getPath() + File.separator + "kanjidict.zip"; File fileKanjidict = new File(kanjiDictPath); if (fileKanjidict.exists()) { fileKanjidict.delete(); } mDownloadingKanjidic = false; mDownloadKanjidicFrom = url; mDownloadKanjidicTo = fileKanjidict; } mDownloadTatoebaIndicesFrom = new URL(ParserService.TATOEBA_INDICES_PATH); mDownloadTatoebaIndicesTo = new File(storage, "tatoeba-japanese.zip"); if (mDownloadTatoebaIndicesTo.exists()) { mDownloadTatoebaIndicesTo.delete(); } mDownloadTatoebaSentencesFrom = new URL(ParserService.TATOEBA_SENTENCES_PATH); mDownloadTatoebaSentencesTo = new File(storage, "tatoeba-translation.zip"); if (mDownloadTatoebaSentencesTo.exists()) { mDownloadTatoebaSentencesTo.delete(); } mDownloadKanjiVGFrom = new URL(ParserService.KANJIVG_PATH); mDownloadKanjiVGTo = new File(storage, "kanjivg.zip"); if (mDownloadKanjiVGTo.exists()) { mDownloadKanjiVGTo.delete(); } downloadDictionaries(); } catch (MalformedURLException e) { Log.e(LOG_TAG, "MalformedURLException wrong format of URL: " + e.toString()); stopSelf(mStartId); } catch (IOException e) { Log.e(LOG_TAG, "IOException downloading interrupted: " + e.toString()); stopSelf(mStartId); } catch (Exception e) { e.printStackTrace(); Log.e(LOG_TAG, "Exception: " + e.toString()); stopSelf(mStartId); } }
From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java
/** * The <code>addImageToPdf</code> method is used to add image to pdf and make it searchable by adding image text in invisible mode * w.r.t parameter 'isPdfSearchable' passed. * //w ww . j av a 2s. c om * @param pdfWriter {@link PdfWriter} writer of pdf in which image has to be added * @param htmlUrl {@link HocrPage} corresponding html file for fetching text and coordinates * @param imageUrl {@link String} url of image to be added in pdf * @param isPdfSearchable true for searchable pdf else otherwise * @param widthOfLine */ private void addImageToPdf(PdfWriter pdfWriter, HocrPage hocrPage, String imageUrl, boolean isPdfSearchable, final int widthOfLine) { if (null != pdfWriter && null != imageUrl && imageUrl.length() > 0) { try { LOGGER.info("Adding image" + imageUrl + " to pdf using iText"); Image pageImage = Image.getInstance(imageUrl); float dotsPerPointX = pageImage.getDpiX() / PDF_RESOLUTION; float dotsPerPointY = pageImage.getDpiY() / PDF_RESOLUTION; PdfContentByte pdfContentByte = pdfWriter.getDirectContent(); pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY); pageImage.setAbsolutePosition(0, 0); // Add image to pdf pdfWriter.getDirectContentUnder().addImage(pageImage); pdfWriter.getDirectContentUnder().add(pdfContentByte); // If pdf is to be made searchable if (isPdfSearchable) { LOGGER.info("Adding invisible text for image: " + imageUrl); float pageImagePixelHeight = pageImage.getHeight(); Font defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK); // Fetch text and coordinates for image to be added Map<String, int[]> textCoordinatesMap = getTextWithCoordinatesMap(hocrPage, widthOfLine); Set<String> ketSet = textCoordinatesMap.keySet(); // Add text at specific location for (String key : ketSet) { int[] coordinates = textCoordinatesMap.get(key); float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX; float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY; pdfContentByte.beginText(); // To make text added as invisible pdfContentByte.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); pdfContentByte.setLineWidth(Math.round(bboxWidthPt)); // Ceil is used so that minimum font of any text is 1 // For exception of unbalanced beginText() and endText() if (bboxHeightPt > 0.0) { pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), (float) Math.ceil(bboxHeightPt)); } else { pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), 1); } float xCoordinate = (float) (coordinates[0] / dotsPerPointX); float yCoordinate = (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY); pdfContentByte.moveText(xCoordinate, yCoordinate); pdfContentByte.showText(key); pdfContentByte.endText(); } } pdfContentByte.closePath(); } catch (BadElementException badElementException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + badElementException.toString()); } catch (DocumentException documentException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + documentException.toString()); } catch (MalformedURLException malformedURLException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + malformedURLException.toString()); } catch (IOException ioException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + ioException.toString()); } } }
From source file:com.qut.middleware.deployer.logic.RegisterESOELogic.java
private String generateSubjectDN(String dn) { try {// w w w. j a v a2 s . com String result = new String(); URL serviceURL = new URL(dn); 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=" + dn; } }
From source file:de.fuberlin.wiwiss.r2r.FunctionFactoryLoader.java
/** * tries to instantiate an FunctionFactory object. * It tries to load the class referenced by the TransformationFunction URI from the class path first. * The it tries to load it from the code location. * @param URI The URI of the TransformationFunction * @return the FunctionFactory object described by the information found at the given URI or null. * @throws MalformedURLException/*from w ww . j ava2 s.c om*/ */ public FunctionFactory getFunctionFactory(String URI) throws MalformedURLException { boolean loadFromURLs = Config.getProperty("r2r.FunctionManager.loadFromURLs", "false") .equalsIgnoreCase("true"); FunctionFactory functionFactory = null; String codeLocation = null; String qualifiedClassName = null; String error = null; String query = "DESCRIBE <" + URI + ">"; Model model = repository.executeDescribeQuery(query); if (model.isEmpty()) { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> not found in repository."); return null; } Resource funcRes = model.getResource(URI); StmtIterator it = funcRes.listProperties(model.getProperty(R2R.qualifiedClassName)); if (it.hasNext()) qualifiedClassName = it.next().getString(); else { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> did not specify a qualified class name for loading!"); return null; } try { // First try to load from class path functionFactory = loadFunctionFactory(qualifiedClassName, ClassLoader.getSystemClassLoader()); // If FunctionFactory has been loaded, return it if (functionFactory != null) return functionFactory; if (!loadFromURLs) { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> could not be loaded from class path and loading by URL is disabled!"); return null; } // Now try the original code location it = funcRes.listProperties(model.getProperty(R2R.codeLocation)); if (it.hasNext()) codeLocation = it.next().getString(); else { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> could not be loaded from class path and did not specify any further code location!"); return null; } final String cl = codeLocation; URLClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { try { return new URLClassLoader(new URL[] { new URL(cl) }); } catch (MalformedURLException e) { if (log.isDebugEnabled()) log.debug("Malformed URL for code location: " + cl); return null; } } }); functionFactory = loadFunctionFactory(qualifiedClassName, loader); if (functionFactory != null) return functionFactory; else { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> could not be loaded: class " + qualifiedClassName + " could not be loaded from " + codeLocation + "."); return null; } } catch (InstantiationException e) { error = e.toString(); } catch (IllegalAccessException e) { error = e.toString(); } catch (ClassCastException e) { error = e.toString(); } if (error != null && log.isDebugEnabled()) log.debug("External Function <" + URI + "> could not be loaded: " + error); return functionFactory; }
From source file:com.sentaroh.android.SMBExplorer.FileIo.java
private static boolean deleteRemoteItem(NtlmPasswordAuthentication smb_auth, String url) { SmbFile sf;/*from w ww . j av a 2s . com*/ boolean result = false; if (!fileioThreadCtrl.isEnabled()) return false; sendDebugLogMsg(1, "I", "Delete remote file entered, File=" + url); try { result = true; sf = new SmbFile(url + "/", smb_auth); result = deleteRemoteFile(sf); } catch (MalformedURLException e) { e.printStackTrace(); sendLogMsg("E", "Remote file delete error:" + e.toString()); fileioThreadCtrl.setThreadMessage("Remote file delete error:" + e.toString()); result = false; return false; } return result; }
From source file:com.sentaroh.android.SMBExplorer.FileIo.java
private static boolean downloadRemoteFile(NtlmPasswordAuthentication smb_auth, boolean allcopy, String fromUrl, String toUrl) {/*from w w w . ja va 2s . c o m*/ SmbFile hf, hfd; File lf; boolean result = false; if (!fileioThreadCtrl.isEnabled()) return false; sendDebugLogMsg(1, "I", "Download Remote file, from item=" + fromUrl + ", to item=" + toUrl); try { hf = new SmbFile(fromUrl, smb_auth); if (hf.isDirectory()) { // Directory copy result = true; hfd = new SmbFile(fromUrl + "/", smb_auth); String[] children = hfd.list(); for (String element : children) { if (!fileioThreadCtrl.isEnabled()) return false; result = copyRemoteToLocal(smb_auth, fromUrl + "/" + element, toUrl + "/" + element); if (!result) return false; } } else { // file copy if (hf.getAttributes() < 16384) { //no EA, copy was done makeLocalDirs(toUrl); result = true; lf = new File(toUrl); if (!allcopy && !isFileDifferent(hf.lastModified(), hf.length(), lf.lastModified(), lf.length())) { sendDebugLogMsg(1, "I", "Download was cancelled because file does not changed."); } else { result = copyFileRemoteToLocal(hf, lf, toUrl, fromUrl, "Downloading"); } } else { result = false; sendLogMsg("E", "EA founded, copy canceled. path=" + fromUrl); fileioThreadCtrl.setThreadMessage("Download error:" + "EA founded, copy canceled"); } } } catch (MalformedURLException e) { e.printStackTrace(); sendLogMsg("E", "Download error:" + e.toString()); fileioThreadCtrl.setThreadMessage("Download error:" + e.toString()); result = false; return false; } catch (SmbException e) { e.printStackTrace(); sendLogMsg("E", "Download error:" + e.toString()); fileioThreadCtrl.setThreadMessage("Download error:" + e.toString()); result = false; return false; } catch (UnknownHostException e) { e.printStackTrace(); sendLogMsg("E", "Download error:" + e.toString()); fileioThreadCtrl.setThreadMessage("Download error:" + e.toString()); result = false; return false; } catch (FileNotFoundException e) { e.printStackTrace(); sendLogMsg("E", "Download error:" + e.toString()); fileioThreadCtrl.setThreadMessage("Download error:" + e.toString()); result = false; return false; } catch (IOException e) { e.printStackTrace(); sendLogMsg("E", "Download error:" + e.toString()); fileioThreadCtrl.setThreadMessage("Download error:" + e.toString()); result = false; return false; } return result; }