List of usage examples for java.net URI toURL
public URL toURL() throws MalformedURLException
From source file:org.eclipse.winery.repository.resources.artifacts.GenericArtifactsResource.java
/** * Generates the implementation artifact using the implementation artifact * generator. Also sets the proeprties according to the requirements of * OpenTOSCA./*from w w w.j a va2 s.c o m*/ * * @param interfaceNameStr * @param javapackage * @param uriInfo * @param artifactTemplateId * @param artifactTemplateResource the resource associated with the * artifactTempalteId. If null, the object is created in this * method * * @return {@inheritDoc} */ private Response generateImplementationArtifact(String interfaceNameStr, String javapackage, UriInfo uriInfo, ArtifactTemplateId artifactTemplateId, ArtifactTemplateResource artifactTemplateResource) { TInterface iface; assert (this instanceof ImplementationArtifactsResource); IHasTypeReference typeRes = (EntityTypeImplementationResource) this.res; QName type = typeRes.getType(); TOSCAComponentId typeId; TNodeType nodeType = null; if (typeRes instanceof NodeTypeImplementationResource) { // TODO: refactor: This is more a model/repo utilities thing than something which should happen here... typeId = new NodeTypeId(type); NodeTypeResource ntRes = (NodeTypeResource) AbstractComponentsResource .getComponentInstaceResource(typeId); // required for IA Generation nodeType = ntRes.getNodeType(); List<TInterface> interfaces = nodeType.getInterfaces().getInterface(); Iterator<TInterface> it = interfaces.iterator(); do { iface = it.next(); if (iface.getName().equals(interfaceNameStr)) { break; } } while (it.hasNext()); // iface now contains the right interface } else { assert (typeRes instanceof RelationshipTypeImplementationResource); return Response.serverError() .entity("IA creation for relation ship type implementations not yet possible").build(); } Path workingDir; try { workingDir = Files.createTempDirectory("winery"); } catch (IOException e2) { GenericArtifactsResource.logger.debug("Could not create temporary directory", e2); return Response.serverError().entity("Could not create temporary directory").build(); } URI artifactTemplateFilesUri = uriInfo.getBaseUri().resolve(Utils.getAbsoluteURL(artifactTemplateId)) .resolve("files/"); URL artifactTemplateFilesUrl; try { artifactTemplateFilesUrl = artifactTemplateFilesUri.toURL(); } catch (MalformedURLException e2) { GenericArtifactsResource.logger.debug("Could not convert URI to URL", e2); return Response.serverError().entity("Could not convert URI to URL").build(); } String name = this.generateName((NodeTypeId) typeId, interfaceNameStr); Generator gen = new Generator(iface, javapackage, artifactTemplateFilesUrl, name, workingDir.toFile()); File zipFile = gen.generateProject(); if (zipFile == null) { return Response.serverError().entity("IA generator failed").build(); } // store it // TODO: refactor: this is more a RepositoryUtils thing than a special thing here; see also importFile at CSARImporter ArtifactTemplateDirectoryId fileDir = new ArtifactTemplateDirectoryId(artifactTemplateId); RepositoryFileReference fref = new RepositoryFileReference(fileDir, zipFile.getName().toString()); try (InputStream is = Files.newInputStream(zipFile.toPath()); BufferedInputStream bis = new BufferedInputStream(is)) { String mediaType = Utils.getMimeType(bis, zipFile.getName()); // TODO: do the catch thing as in CSARImporter Repository.INSTANCE.putContentToFile(fref, bis, MediaType.valueOf(mediaType)); } catch (IOException e1) { throw new IllegalStateException("Could not import generated files", e1); } // cleanup dir try { FileUtils.forceDelete(workingDir); } catch (IOException e) { GenericArtifactsResource.logger.debug("Could not delete working directory", e); } // store the properties in the artifact template if (artifactTemplateResource == null) { artifactTemplateResource = (ArtifactTemplateResource) AbstractComponentsResource .getComponentInstaceResource(artifactTemplateId); } this.storeProperties(artifactTemplateResource, typeId, name); URI url = uriInfo.getBaseUri().resolve(Utils.getAbsoluteURL(fref)); return Response.created(url).build(); }
From source file:org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl.java
@SuppressWarnings("unchecked") @Override//from ww w. ja va 2 s .c o m public void cancelDelegationToken(final Token<TimelineDelegationTokenIdentifier> timelineDT) throws IOException, YarnException { final boolean isTokenServiceAddrEmpty = timelineDT.getService().toString().isEmpty(); final String scheme = isTokenServiceAddrEmpty ? null : (YarnConfiguration.useHttps(this.getConfig()) ? "https" : "http"); final InetSocketAddress address = isTokenServiceAddrEmpty ? null : SecurityUtil.getTokenServiceAddr(timelineDT); PrivilegedExceptionAction<Void> cancelDTAction = new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { // If the timeline DT to cancel is different than cached, replace it. // Token to set every time for retry, because when exception happens, // DelegationTokenAuthenticatedURL will reset it to null; if (!timelineDT.equals(token.getDelegationToken())) { token.setDelegationToken((Token) timelineDT); } DelegationTokenAuthenticatedURL authUrl = new DelegationTokenAuthenticatedURL(authenticator, connConfigurator); // If the token service address is not available, fall back to use // the configured service address. final URI serviceURI = isTokenServiceAddrEmpty ? resURI : new URI(scheme, null, address.getHostName(), address.getPort(), RESOURCE_URI_STR, null, null); authUrl.cancelDelegationToken(serviceURI.toURL(), token, doAsUser); return null; } }; operateDelegationToken(cancelDTAction); }
From source file:org.codice.ddf.catalog.content.resource.reader.DerivedContentActionProvider.java
@Override public <T> List<Action> getActions(T input) { if (!canHandle(input)) { return Collections.emptyList(); }/*from w w w .j av a2 s. c om*/ // Expect only 1 List<Action> resourceActions = resourceActionProvider.getActions(input); if (resourceActions.isEmpty()) { return Collections.emptyList(); } return ((Metacard) input).getAttribute(Metacard.DERIVED_RESOURCE_URI).getValues().stream().map(value -> { try { URI uri = new URI(value.toString()); URIBuilder builder = new URIBuilder(resourceActions.get(0).getUrl().toURI()); if (StringUtils.equals(uri.getScheme(), ContentItem.CONTENT_SCHEME)) { String qualifier = uri.getFragment(); builder.addParameters( Collections.singletonList(new BasicNameValuePair(ContentItem.QUALIFIER, qualifier))); return Optional.of(new ActionImpl(ID, "View " + qualifier, DESCRIPTION_PREFIX + qualifier, builder.build().toURL())); } else { return Optional.of(new ActionImpl(ID, "View " + uri.toString(), DESCRIPTION_PREFIX + uri.toString(), uri.toURL())); } } catch (URISyntaxException | MalformedURLException e) { LOGGER.debug("Unable to create action URL.", e); return Optional.<Action>empty(); } }).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); }
From source file:org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl.java
@SuppressWarnings("unchecked") @Override// w w w . j a va 2 s. c om public long renewDelegationToken(final Token<TimelineDelegationTokenIdentifier> timelineDT) throws IOException, YarnException { final boolean isTokenServiceAddrEmpty = timelineDT.getService().toString().isEmpty(); final String scheme = isTokenServiceAddrEmpty ? null : (YarnConfiguration.useHttps(this.getConfig()) ? "https" : "http"); final InetSocketAddress address = isTokenServiceAddrEmpty ? null : SecurityUtil.getTokenServiceAddr(timelineDT); PrivilegedExceptionAction<Long> renewDTAction = new PrivilegedExceptionAction<Long>() { @Override public Long run() throws Exception { // If the timeline DT to renew is different than cached, replace it. // Token to set every time for retry, because when exception happens, // DelegationTokenAuthenticatedURL will reset it to null; if (!timelineDT.equals(token.getDelegationToken())) { token.setDelegationToken((Token) timelineDT); } DelegationTokenAuthenticatedURL authUrl = new DelegationTokenAuthenticatedURL(authenticator, connConfigurator); // If the token service address is not available, fall back to use // the configured service address. final URI serviceURI = isTokenServiceAddrEmpty ? resURI : new URI(scheme, null, address.getHostName(), address.getPort(), RESOURCE_URI_STR, null, null); return authUrl.renewDelegationToken(serviceURI.toURL(), token, doAsUser); } }; return (Long) operateDelegationToken(renewDTAction); }
From source file:org.dita.dost.writer.ImageMetadataFilter.java
private InputStream getInputStream(final URI imgInput) throws IOException { if (imgInput.getScheme().equals("data")) { final String data = imgInput.getSchemeSpecificPart(); final int separator = data.indexOf(','); final String metadata = data.substring(0, separator); if (metadata.endsWith(";base64")) { logger.info("Base-64 encoded data URI"); return new ByteArrayInputStream(Base64.decodeBase64(data.substring(separator + 1))); } else {//from www.ja v a 2 s. com logger.info("ASCII encoded data URI"); return new ByteArrayInputStream(data.substring(separator).getBytes()); } } else { return imgInput.toURL().openConnection().getInputStream(); } }
From source file:org.apache.axis2.jaxws.description.impl.URIResolverImpl.java
/** * Gets input stream from the uri given. If we cannot find the stream, <code>null</code> is * returned.//from w w w . j ava 2 s . c o m * * @param uri * @return */ protected InputStream getInputStreamForURI(String uri) { URL streamURL = null; InputStream is = null; URI pathURI = null; try { streamURL = new URL(uri); is = openStream_doPriv(streamURL); } catch (Throwable t) { //Exception handling not needed if (log.isDebugEnabled()) { log.debug("Exception occured in getInputStreamForURI, ignoring exception continuing processing: " + t.getMessage()); } } if (is == null) { try { pathURI = new URI(uri); streamURL = pathURI.toURL(); is = openStream_doPriv(streamURL); } catch (Throwable t) { //Exception handling not needed if (log.isDebugEnabled()) { log.debug( "Exception occured in getInputStreamForURI, ignoring exception continuing processing: " + t.getMessage()); } } } if (is == null) { try { final File file = new File(uri); streamURL = (URL) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws MalformedURLException { return file.toURL(); } }); is = openStream_doPriv(streamURL); } catch (Throwable t) { //Exception handling not needed if (log.isDebugEnabled()) { log.debug( "Exception occured in getInputStreamForURI, ignoring exception continuing processing: " + t.getMessage()); } } } return is; }
From source file:com.threadswarm.imagefeedarchiver.processor.RssItemProcessor.java
private void downloadRssMediaContent(ProcessedRssItem processedItem, RssMediaContent mediaContent) { DownloadStatus downloadStatus = DownloadStatus.FAILED; HttpEntity responseEntity = null;//from w w w.ja v a 2 s .c om try { String targetUrlString = mediaContent.getUrlString(); if (forceHttps) targetUrlString = FeedUtils.rewriteUrlStringToHttps(targetUrlString); URI targetURI = FeedUtils.getUriFromUrlString(targetUrlString); boolean freshURI = processedURISet.add(targetURI); if (!freshURI) { LOGGER.warn("Skipping previously processed URI: {}", targetURI); return; //abort processing } LOGGER.info("Attempting to download {}", targetURI); HttpGet imageGet = new HttpGet(targetURI); for (Header header : headerList) imageGet.addHeader(header); HttpResponse imageResponse = httpClient.execute(imageGet); String originalFileName = StringUtils.stripStart(targetURI.toURL().getFile(), "/"); originalFileName = StringUtils.replace(originalFileName, "/", "_"); File outputFile = getOutputFile(originalFileName); long expectedContentLength = FeedUtils.calculateBestExpectedContentLength(imageResponse, mediaContent); responseEntity = imageResponse.getEntity(); BufferedInputStream bis = null; DigestOutputStream fos = null; int bytesRead = 0; try { bis = new BufferedInputStream(responseEntity.getContent()); fos = new DigestOutputStream(new FileOutputStream(outputFile), MessageDigest.getInstance("SHA")); byte[] buffer = new byte[8192]; while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) { fos.write(buffer, 0, bytesRead); } fos.flush(); MessageDigest messageDigest = fos.getMessageDigest(); byte[] digestBytes = messageDigest.digest(); String digestString = Hex.encodeHexString(digestBytes); LOGGER.info("Downloaded - {} (SHA: {})", targetURI, digestString); processedItem.setDownloadDate(new Date()); downloadStatus = DownloadStatus.COMPLETED; processedItem.setHash(digestString); processedItem.setFilename(outputFile.toString()); } catch (ConnectionClosedException e) { LOGGER.error("An Exception was thrown while attempting to read HTTP entity content", e); } catch (NoSuchAlgorithmException e) { LOGGER.error("The SHA-1 hashing algorithm is not available on this JVM", e); } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(fos); EntityUtils.consumeQuietly(responseEntity); if (downloadStatus == DownloadStatus.FAILED || (outputFile.exists() && outputFile.length() != expectedContentLength)) { LOGGER.warn("Deleted partial/failed file: {}", outputFile); outputFile.delete(); processedItem.setDownloadStatus(DownloadStatus.FAILED); } } } catch (IOException e) { LOGGER.error("An Exception was thrown while attempting to download image content", e); } catch (URISyntaxException e) { LOGGER.error("The supplied URI, {}, violates syntax rules", e); } finally { EntityUtils.consumeQuietly(responseEntity); } processedItem.setDownloadStatus(downloadStatus); itemDAO.save(processedItem); }
From source file:eu.planets_project.tb.impl.data.util.DataHandlerImpl.java
public URI storeUriContent(URI u) throws MalformedURLException, IOException { URI ref = null;/*from ww w. ja v a 2 s.c om*/ InputStream in = null; try { URLConnection c = u.toURL().openConnection(); in = c.getInputStream(); ref = this.storeBytestream(in, u.toString()); } finally { in.close(); } return ref; }
From source file:org.alfresco.web.forms.RenderingEngineTemplateImpl.java
/** * Builds the model to pass to the rendering engine. *//*w ww.ja v a2s . c o m*/ protected Map<QName, Object> buildModel(final FormInstanceData formInstanceData, final Rendition rendition) throws IOException, SAXException { final String formInstanceDataAvmPath = formInstanceData.getPath(); final String renditionAvmPath = rendition.getPath(); final String parentPath = AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[0]; final String sandboxUrl = AVMUtil.getPreviewURI(AVMUtil.getStoreName(formInstanceDataAvmPath)); final String webappUrl = AVMUtil.buildWebappUrl(formInstanceDataAvmPath); final HashMap<QName, Object> model = new HashMap<QName, Object>(); // add simple scalar parameters model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "date", namespacePrefixResolver), new Date()); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "avm_sandbox_url", namespacePrefixResolver), sandboxUrl); model.put(RenderingEngineTemplateImpl.PROP_RESOURCE_RESOLVER, new RenderingEngine.TemplateResourceResolver() { public InputStream resolve(final String name) { final NodeService nodeService = RenderingEngineTemplateImpl.this.getServiceRegistry() .getNodeService(); final NodeRef parentNodeRef = nodeService .getPrimaryParent(RenderingEngineTemplateImpl.this.getNodeRef()).getParentRef(); if (logger.isDebugEnabled()) { logger.debug("request to resolve resource " + name + " webapp url is " + webappUrl + " and data dictionary workspace is " + parentNodeRef); } final NodeRef result = nodeService.getChildByName(parentNodeRef, ContentModel.ASSOC_CONTAINS, name); if (result != null) { final ContentService contentService = RenderingEngineTemplateImpl.this .getServiceRegistry().getContentService(); try { if (logger.isDebugEnabled()) { logger.debug("found " + name + " in data dictonary: " + result); } return contentService.getReader(result, ContentModel.PROP_CONTENT) .getContentInputStream(); } catch (Exception e) { logger.warn(e); } } if (name.startsWith(WEBSCRIPT_PREFIX)) { try { final FacesContext facesContext = FacesContext.getCurrentInstance(); final ExternalContext externalContext = facesContext.getExternalContext(); final HttpServletRequest request = (HttpServletRequest) externalContext .getRequest(); String decodedName = URLDecoder.decode(name.substring(WEBSCRIPT_PREFIX.length())); String rewrittenName = decodedName; if (decodedName.contains("${storeid}")) { rewrittenName = rewrittenName.replace("${storeid}", AVMUtil.getStoreName(formInstanceDataAvmPath)); } else { if (decodedName.contains("{storeid}")) { rewrittenName = rewrittenName.replace("{storeid}", AVMUtil.getStoreName(formInstanceDataAvmPath)); } } if (decodedName.contains("${ticket}")) { AuthenticationService authenticationService = Repository .getServiceRegistry(facesContext).getAuthenticationService(); final String ticket = authenticationService.getCurrentTicket(); rewrittenName = rewrittenName.replace("${ticket}", ticket); } else { if (decodedName.contains("{ticket}")) { AuthenticationService authenticationService = Repository .getServiceRegistry(facesContext).getAuthenticationService(); final String ticket = authenticationService.getCurrentTicket(); rewrittenName = rewrittenName.replace("{ticket}", ticket); } } final String webscriptURI = (request.getScheme() + "://" + request.getServerName() + ':' + request.getServerPort() + request.getContextPath() + "/wcservice/" + rewrittenName); if (logger.isDebugEnabled()) { logger.debug("loading webscript: " + webscriptURI); } final URI uri = new URI(webscriptURI); return uri.toURL().openStream(); } catch (Exception e) { logger.warn(e); } } try { final String[] path = (name.startsWith("/") ? name.substring(1) : name).split("/"); for (int i = 0; i < path.length; i++) { path[i] = URLEncoder.encode(path[i]); } final URI uri = new URI(webappUrl + '/' + StringUtils.join(path, '/')); if (logger.isDebugEnabled()) { logger.debug("loading " + uri); } return uri.toURL().openStream(); } catch (Exception e) { logger.warn(e); return null; } } }); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "form_instance_data_file_name", namespacePrefixResolver), AVMNodeConverter.SplitBase(formInstanceDataAvmPath)[1]); model.put( QName.createQName(NamespaceService.ALFRESCO_PREFIX, "rendition_file_name", namespacePrefixResolver), AVMNodeConverter.SplitBase(renditionAvmPath)[1]); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parent_path", namespacePrefixResolver), parentPath); final FacesContext fc = FacesContext.getCurrentInstance(); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "request_context_path", namespacePrefixResolver), fc.getExternalContext().getRequestContextPath()); // add methods final FormDataFunctions fdf = this.getFormDataFunctions(); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "encodeQuotes", namespacePrefixResolver), new RenderingEngine.TemplateProcessorMethod() { public Object exec(final Object[] arguments) throws IOException, SAXException { if (arguments.length != 1) { throw new IllegalArgumentException( "expected 1 argument to encodeQuotes. got " + arguments.length); } if (!(arguments[0] instanceof String)) { throw new ClassCastException("expected arguments[0] to be a " + String.class.getName() + ". got a " + arguments[0].getClass().getName() + "."); } String text = (String) arguments[0]; if (logger.isDebugEnabled()) { logger.debug("tpm_encodeQuotes('" + text + "'), parentPath = " + parentPath); } final String result = fdf.encodeQuotes(text); return result; } }); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocument", namespacePrefixResolver), new RenderingEngine.TemplateProcessorMethod() { public Object exec(final Object[] arguments) throws IOException, SAXException { if (arguments.length != 1) { throw new IllegalArgumentException( "expected 1 argument to parseXMLDocument. got " + arguments.length); } if (!(arguments[0] instanceof String)) { throw new ClassCastException("expected arguments[0] to be a " + String.class.getName() + ". got a " + arguments[0].getClass().getName() + "."); } String path = (String) arguments[0]; path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE); if (logger.isDebugEnabled()) { logger.debug("tpm_parseXMLDocument('" + path + "'), parentPath = " + parentPath); } final Document d = fdf.parseXMLDocument(path); return d != null ? d.getDocumentElement() : null; } }); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "parseXMLDocuments", namespacePrefixResolver), new RenderingEngine.TemplateProcessorMethod() { public Object exec(final Object[] arguments) throws IOException, SAXException { if (arguments.length > 2) { throw new IllegalArgumentException("expected exactly one or two arguments to " + "parseXMLDocuments. got " + arguments.length); } if (!(arguments[0] instanceof String)) { throw new ClassCastException("expected arguments[0] to be a " + String.class.getName() + ". got a " + arguments[0].getClass().getName() + "."); } if (arguments.length == 2 && !(arguments[1] instanceof String)) { throw new ClassCastException("expected arguments[1] to be a " + String.class.getName() + ". got a " + arguments[1].getClass().getName() + "."); } String path = arguments.length == 2 ? (String) arguments[1] : ""; path = AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE); final String formName = (String) arguments[0]; if (logger.isDebugEnabled()) { logger.debug("tpm_parseXMLDocuments('" + formName + "','" + path + "'), parentPath = " + parentPath); } final Map<String, Document> resultMap = fdf.parseXMLDocuments(formName, path); if (logger.isDebugEnabled()) { logger.debug("received " + resultMap.size() + " documents in " + path + " with form name " + formName); } // create a root document for rooting all the results. we do this // so that each document root element has a common parent node // and so that xpath axes work properly final Document rootNodeDocument = XMLUtil.newDocument(); final Element rootNodeDocumentEl = rootNodeDocument.createElementNS( NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_list"); rootNodeDocumentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI); rootNodeDocument.appendChild(rootNodeDocumentEl); final List<Node> result = new ArrayList<Node>(resultMap.size()); for (Map.Entry<String, Document> e : resultMap.entrySet()) { final Element documentEl = e.getValue().getDocumentElement(); documentEl.setAttribute("xmlns:" + NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI); documentEl.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":file_name", e.getKey()); final Node n = rootNodeDocument.importNode(documentEl, true); rootNodeDocumentEl.appendChild(n); result.add(n); } return result.toArray(new Node[result.size()]); } }); model.put(QName.createQName(NamespaceService.ALFRESCO_PREFIX, "_getAVMPath", namespacePrefixResolver), new RenderingEngine.TemplateProcessorMethod() { public Object exec(final Object[] arguments) { if (arguments.length != 1) { throw new IllegalArgumentException( "expected one argument to _getAVMPath. got " + arguments.length); } if (!(arguments[0] instanceof String)) { throw new ClassCastException("expected arguments[0] to be a " + String.class.getName() + ". got a " + arguments[0].getClass().getName() + "."); } final String path = (String) arguments[0]; if (logger.isDebugEnabled()) { logger.debug("tpm_getAVMPAth('" + path + "'), parentPath = " + parentPath); } return AVMUtil.buildPath(parentPath, path, AVMUtil.PathRelation.WEBAPP_RELATIVE); } }); // add the xml document model.put(RenderingEngine.ROOT_NAMESPACE, formInstanceData.getDocument()); return model; }
From source file:org.dspace.installer_edm.InstallerEDMBase.java
/** * validar un cadena como uri/* w w w. j a v a 2s .c o m*/ * * @param uriStr cadena original * @return validez de la uri */ protected boolean isValidURI(String uriStr) { try { URI uri = new URI(uriStr); uri.toURL(); return true; } catch (URISyntaxException e) { return false; } catch (MalformedURLException e) { return false; } catch (IllegalArgumentException e) { return false; } }