List of usage examples for java.io UnsupportedEncodingException toString
public String toString()
From source file:org.etudes.mneme.impl.AttachmentServiceImpl.java
/** * Translate the resource's body html with the translations. * * @param ref//from w w w.ja v a 2 s . co m * The resource reference. * @param translations * The complete set of translations. * @param context * The context. */ protected void translateHtmlBody(Reference ref, Collection<Translation> translations, String context) { // ref is the destination ("to" in the translations) resource - we need the "parent ref" from the source ("from" in the translations) resource String parentRef = ref.getReference(); for (Translation translation : translations) { parentRef = translation.reverseTranslate(parentRef); } // bypass security when reading the resource to copy pushAdvisor(); try { // Reference does not know how to make the id from a private docs reference. String id = ref.getId(); if (id.startsWith("/content/")) { id = id.substring("/content".length()); } // get the resource ContentResource resource = this.contentHostingService.getResource(id); String type = resource.getContentType(); // translate if we are html if (type.equals("text/html")) { byte[] body = resource.getContent(); if (body != null) { String bodyString = new String(body, "UTF-8"); String translated = translateEmbeddedReferences(bodyString, translations, parentRef); body = translated.getBytes("UTF-8"); ContentResourceEdit edit = this.contentHostingService.editResource(resource.getId()); edit.setContent(body); this.contentHostingService.commitResource(edit, 0); } } } catch (UnsupportedEncodingException e) { M_log.warn("translateHtmlBody: " + e.toString()); } catch (PermissionException e) { M_log.warn("translateHtmlBody: " + e.toString()); } catch (IdUnusedException e) { M_log.warn("translateHtmlBody: " + e.toString()); } catch (TypeException e) { M_log.warn("translateHtmlBody: " + e.toString()); } catch (ServerOverloadException e) { M_log.warn("translateHtmlBody: " + e.toString()); } catch (InUseException e) { M_log.warn("translateHtmlBody: " + e.toString()); } catch (OverQuotaException e) { M_log.warn("translateHtmlBody: " + e.toString()); } finally { popAdvisor(); } }
From source file:com.lgallardo.qbittorrentclient.RefreshListener.java
private void handleUrlTorrent() { // permission was granted, yay! Do the // contacts-related task you need to do. // if there is not a path to the file, open de file picker if (urlTorrent == null) { openFilePicker();/*from ww w. j ava 2 s . c o m*/ } else { try { if (urlTorrent.substring(0, 7).equals("content")) { urlTorrent = "file://" + getFilePathFromUri(this, Uri.parse(urlTorrent)); } if (urlTorrent.substring(0, 4).equals("file")) { // File addTorrentFile(Uri.parse(urlTorrent).getPath()); } else { urlTorrent = Uri.decode(URLEncoder.encode(urlTorrent, "UTF-8")); // If It is a valid torrent or magnet link if (urlTorrent.contains(".torrent") || urlTorrent.contains("magnet:")) { // Log.d("Debug", "URL: " + urlTorrent); addTorrent(urlTorrent); } else { // Open not valid torrent or magnet link in browser Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlTorrent)); startActivity(browserIntent); } } } catch (UnsupportedEncodingException e) { Log.e("Debug", "Check URL: " + e.toString()); } catch (NullPointerException e) { Log.e("Debug", "urlTorrent is null: " + e.toString()); } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java
private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl) throws ClassNotFoundException { // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths String pckgname = pkg;/*from www . j ava 2 s .c om*/ ArrayList<File> directories = new ArrayList<File>(); try { String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cl.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)"); } throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr2", pckgname)); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("IOException was thrown when trying to get all resources for " + pckgname); } throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr3", pckgname)); } ArrayList<Class> classes = new ArrayList<Class>(); // For every directory identified capture all the .class files for (File directory : directories) { if (log.isDebugEnabled()) { log.debug(" Adding JAXB classes from directory: " + directory.getName()); } if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { // we are only interested in .class files if (file.endsWith(".class")) { // removes the .class extension // TODO Java2 Sec String className = pckgname + '.' + file.substring(0, file.length() - 6); try { Class clazz = forName(className, false, getContextClassLoader()); // Don't add any interfaces or JAXWS specific classes. // Only classes that represent data and can be marshalled // by JAXB should be added. if (!clazz.isInterface() && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null || ClassUtils.getDefaultPublicConstructor(clazz) != null) && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz) && !java.lang.Exception.class.isAssignableFrom(clazz)) { // Ensure that all the referenced classes are loadable too clazz.getDeclaredMethods(); clazz.getDeclaredFields(); if (log.isDebugEnabled()) { log.debug("Adding class: " + file); } classes.add(clazz); // REVIEW: // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present. // This is a hack until we can determine how to get this information. // The arrayName and loadable name are different. Get the loadable // name, load the array class, and add it to our list //className += "[]"; //String loadableName = ClassUtils.getLoadableClassName(className); //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader()); } //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that //does not extend Exception } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Tried to load class " + className + " while constructing a JAXBContext. This class will be skipped. Processing Continues."); log.debug(" The reason that class could not be loaded:" + e.toString()); log.trace(JavaUtils.stackToString(e)); } } } } } } return classes; }
From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java
private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl) throws ClassNotFoundException { // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths String pckgname = pkg;/*w ww .j a v a 2s.c o m*/ ArrayList<File> directories = new ArrayList<File>(); try { String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cl.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)"); } throw new ClassNotFoundException( pckgname + " might not be a valid package because the encoding is unsupported."); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("IOException was thrown when trying to get all resources for " + pckgname); } throw new ClassNotFoundException( "An IOException error was thrown when trying to get all of the resources for " + pckgname); } ArrayList<Class> classes = new ArrayList<Class>(); // For every directory identified capture all the .class files for (File directory : directories) { if (log.isDebugEnabled()) { log.debug(" Adding JAXB classes from directory: " + directory.getName()); } if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { // we are only interested in .class files if (file.endsWith(".class")) { // removes the .class extension // TODO Java2 Sec String className = pckgname + '.' + file.substring(0, file.length() - 6); try { Class clazz = forName(className, false, getContextClassLoader()); // Don't add any interfaces or JAXWS specific classes. // Only classes that represent data and can be marshalled // by JAXB should be added. if (!clazz.isInterface() && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null || ClassUtils.getDefaultPublicConstructor(clazz) != null) && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz) && !Exception.class.isAssignableFrom(clazz)) { // Ensure that all the referenced classes are loadable too clazz.getDeclaredMethods(); clazz.getDeclaredFields(); if (log.isDebugEnabled()) { log.debug("Adding class: " + file); } classes.add(clazz); // REVIEW: // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present. // This is a hack until we can determine how to get this information. // The arrayName and loadable name are different. Get the loadable // name, load the array class, and add it to our list //className += "[]"; //String loadableName = ClassUtils.getLoadableClassName(className); //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader()); } //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that //does not extend Exception } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Tried to load class " + className + " while constructing a JAXBContext. This class will be skipped. Processing Continues."); log.debug(" The reason that class could not be loaded:" + e.toString()); log.trace(JavaUtils.stackToString(e)); } } } } } } return classes; }
From source file:org.forester.archaeopteryx.TreePanel.java
final private void openSeqWeb(final PhylogenyNode node) { if (!isCanOpenSeqWeb(node)) { cannotOpenBrowserWarningMessage("sequence"); return;//from w w w . ja va2 s. c om } String uri_str = null; final Sequence seq = node.getNodeData().getSequence(); final String source = seq.getAccession().getSource().toLowerCase(); final WebLink weblink = getConfiguration().getWebLink(source); try { uri_str = weblink.getUrl() + URLEncoder.encode(seq.getAccession().getValue(), ForesterConstants.UTF8); } catch (final UnsupportedEncodingException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } if (!ForesterUtil.isEmpty(uri_str)) { try { JApplet applet = null; if (isApplet()) { applet = obtainApplet(); } Util.launchWebBrowser(new URI(uri_str), isApplet(), applet, "_aptx_seq"); } catch (final IOException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } catch (final URISyntaxException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } } else { cannotOpenBrowserWarningMessage("sequence"); } }
From source file:org.forester.archaeopteryx.TreePanel.java
final private void openTaxWeb(final PhylogenyNode node) { if (!isCanOpenTaxWeb(node)) { cannotOpenBrowserWarningMessage("taxonomic"); return;//w ww. j a v a 2s . c o m } String uri_str = null; final Taxonomy tax = node.getNodeData().getTaxonomy(); if ((tax.getIdentifier() != null) && !ForesterUtil.isEmpty(tax.getIdentifier().getProvider())) { final String type = tax.getIdentifier().getProvider().toLowerCase(); if (getConfiguration().isHasWebLink(type)) { final WebLink weblink = getConfiguration().getWebLink(type); try { uri_str = weblink.getUrl() + URLEncoder.encode(tax.getIdentifier().getValue(), ForesterConstants.UTF8); } catch (final UnsupportedEncodingException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } } } else if (!ForesterUtil.isEmpty(tax.getScientificName())) { try { uri_str = "http://www.eol.org/search?q=" + URLEncoder.encode(tax.getScientificName(), ForesterConstants.UTF8); } catch (final UnsupportedEncodingException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } } else if (!ForesterUtil.isEmpty(tax.getTaxonomyCode())) { try { uri_str = "http://www.uniprot.org/taxonomy/?query=" + URLEncoder.encode(tax.getTaxonomyCode(), ForesterConstants.UTF8); } catch (final UnsupportedEncodingException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } } else if (!ForesterUtil.isEmpty(tax.getCommonName())) { try { uri_str = "http://www.eol.org/search?q=" + URLEncoder.encode(tax.getCommonName(), ForesterConstants.UTF8); } catch (final UnsupportedEncodingException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } } if (!ForesterUtil.isEmpty(uri_str)) { try { JApplet applet = null; if (isApplet()) { applet = obtainApplet(); } Util.launchWebBrowser(new URI(uri_str), isApplet(), applet, "_aptx_tax"); } catch (final IOException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } catch (final URISyntaxException e) { Util.showErrorMessage(this, e.toString()); e.printStackTrace(); } } else { cannotOpenBrowserWarningMessage("taxonomic"); } }
From source file:org.apache.cloudstack.storage.resource.NfsSecondaryStorageResource.java
public String postUpload(String uuid, String filename) { UploadEntity uploadEntity = uploadEntityStateMap.get(uuid); int installTimeoutPerGig = 180 * 60 * 1000; String resourcePath = uploadEntity.getInstallPathPrefix(); String finalResourcePath = uploadEntity.getTmpltPath(); // template download UploadEntity.ResourceType resourceType = uploadEntity.getResourceType(); String fileSavedTempLocation = uploadEntity.getInstallPathPrefix() + "/" + filename; String uploadedFileExtension = FilenameUtils.getExtension(filename); String userSelectedFormat = uploadEntity.getFormat().toString(); if (uploadedFileExtension.equals("zip") || uploadedFileExtension.equals("bz2") || uploadedFileExtension.equals("gz")) { userSelectedFormat += "." + uploadedFileExtension; }//from w w w .j av a 2 s. c o m String formatError = ImageStoreUtil.checkTemplateFormat(fileSavedTempLocation, userSelectedFormat); if (StringUtils.isNotBlank(formatError)) { String errorString = "File type mismatch between uploaded file and selected format. Selected file format: " + userSelectedFormat + ". Received: " + formatError; s_logger.error(errorString); return errorString; } int imgSizeGigs = getSizeInGB(_storage.getSize(fileSavedTempLocation)); int maxSize = uploadEntity.getMaxSizeInGB(); if (imgSizeGigs > maxSize) { String errorMessage = "Maximum file upload size exceeded. Physical file size: " + imgSizeGigs + "GB. Maximum allowed size: " + maxSize + "GB."; s_logger.error(errorMessage); return errorMessage; } imgSizeGigs++; // add one just in case long timeout = (long) imgSizeGigs * installTimeoutPerGig; Script scr = new Script(getScriptLocation(resourceType), timeout, s_logger); scr.add("-s", Integer.toString(imgSizeGigs)); scr.add("-S", Long.toString(UploadEntity.s_maxTemplateSize)); if (uploadEntity.getDescription() != null && uploadEntity.getDescription().length() > 1) { scr.add("-d", uploadEntity.getDescription()); } if (uploadEntity.isHvm()) { scr.add("-h"); } String checkSum = uploadEntity.getChksum(); if (StringUtils.isNotBlank(checkSum)) { scr.add("-c", checkSum); } // add options common to ISO and template String extension = uploadEntity.getFormat().getFileExtension(); String templateName = ""; if (extension.equals("iso")) { templateName = uploadEntity.getUuid().trim().replace(" ", "_"); } else { try { templateName = UUID .nameUUIDFromBytes( (uploadEntity.getFilename() + System.currentTimeMillis()).getBytes("UTF-8")) .toString(); } catch (UnsupportedEncodingException e) { templateName = uploadEntity.getUuid().trim().replace(" ", "_"); } } // run script to mv the temporary template file to the final template // file String templateFilename = templateName + "." + extension; uploadEntity.setTemplatePath(finalResourcePath + "/" + templateFilename); scr.add("-n", templateFilename); scr.add("-t", resourcePath); scr.add("-f", fileSavedTempLocation); // this is the temporary // template file downloaded if (uploadEntity.getChksum() != null && uploadEntity.getChksum().length() > 1) { scr.add("-c", uploadEntity.getChksum()); } scr.add("-u"); // cleanup String result; result = scr.execute(); if (result != null) { return result; } // Set permissions for the downloaded template File downloadedTemplate = new File(resourcePath + "/" + templateFilename); _storage.setWorldReadableAndWriteable(downloadedTemplate); // Set permissions for template/volume.properties String propertiesFile = resourcePath; if (resourceType == UploadEntity.ResourceType.TEMPLATE) { propertiesFile += "/template.properties"; } else { propertiesFile += "/volume.properties"; } File templateProperties = new File(propertiesFile); _storage.setWorldReadableAndWriteable(templateProperties); TemplateLocation loc = new TemplateLocation(_storage, resourcePath); try { loc.create(uploadEntity.getEntityId(), true, uploadEntity.getFilename()); } catch (IOException e) { s_logger.warn("Something is wrong with template location " + resourcePath, e); loc.purge(); return "Unable to upload due to " + e.getMessage(); } Map<String, Processor> processors = _dlMgr.getProcessors(); for (Processor processor : processors.values()) { FormatInfo info = null; try { info = processor.process(resourcePath, null, templateName); } catch (InternalErrorException e) { s_logger.error("Template process exception ", e); return e.toString(); } if (info != null) { loc.addFormat(info); uploadEntity.setVirtualSize(info.virtualSize); uploadEntity.setPhysicalSize(info.size); break; } } if (!loc.save()) { s_logger.warn("Cleaning up because we're unable to save the formats"); loc.purge(); } uploadEntity.setStatus(UploadEntity.Status.COMPLETED); uploadEntityStateMap.put(uploadEntity.getUuid(), uploadEntity); return null; }