/** Test method getPattern */ @Test @SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION") public void testGetPattern() { assertNotNull(RegExPool.getPattern("xy")); assertSame(RegExPool.getPattern("xy"), RegExPool.getPattern("xy")); assertNotSame(RegExPool.getPattern("xy"), RegExPool.getPattern("yy")); try { // empty string not allowed RegExPool.getPattern(""); fail(); } catch (final IllegalArgumentException ex) { } try { // null not allowed RegExPool.getPattern(null); fail(); } catch (final NullPointerException ex) { } try { // Illegal regular expression RegExPool.getPattern("[a-z+"); fail(); } catch (final IllegalArgumentException ex) { assertNotNull(ex.getCause()); assertTrue(ex.getCause() instanceof PatternSyntaxException); } }
@Test public void testThrowMessageForMessageOnViolation() throws Exception { final ParametersPassesExpression annotation = proxyAnnotation( ParametersPassesExpression.class, "value", "myExpression", "messageOnViolation", "My message - ${#expression}"); final MethodCall<ParametersPassesExpressionUnitTest> methodCall = toMethodCall(ParametersPassesExpressionUnitTest.class, this, "test", "a", 1, "b", 2); try { new Evaluator().throwMessageFor(annotation, methodCall, null); fail("Exception missing"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("My message - " + annotation.value())); assertThat(e.getCause(), nullValue()); } final Throwable cause = new Throwable("myCause"); try { new Evaluator().throwMessageFor(annotation, methodCall, cause); fail("Exception missing"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("My message - " + annotation.value())); assertThat(e.getCause(), is(cause)); } }
@Override public long isReady(long tid, Master environment) throws Exception { try { String namespaceId = Tables.getNamespaceId(environment.getInstance(), tableId); return Utils.reserveNamespace(namespaceId, tid, false, false, TableOperation.DELETE) + Utils.reserveTable(tableId, tid, true, true, TableOperation.DELETE); } catch (IllegalArgumentException ex) { if (ex.getCause() != null && ex.getCause() instanceof TableNotFoundException) { return 0; } throw ex; } }
@Override public Repo<Master> call(long tid, Master environment) throws Exception { try { String namespaceId = Tables.getNamespaceId(environment.getInstance(), tableId); TableManager.getInstance().transitionTableState(tableId, TableState.DELETING); environment.getEventCoordinator().event("deleting table %s ", tableId); return new CleanUp(tableId, namespaceId); } catch (IllegalArgumentException ex) { if (ex.getCause() != null && ex.getCause() instanceof TableNotFoundException) { return null; } throw ex; } }
public static final Object apply(FunctionInfo fi, Object... args) { assert fi != null; if (!fi.acceptsUndefinedValues) { for (Object arg : args) { if ((arg == null) || (arg == Undefined.UNDEFINED)) { return Undefined.UNDEFINED; } } } for (Signature sig : fi.signatures) { if (sig.matches(args)) { try { Object result = sig.evaluateMethod.invoke(fi.function, args); assert Types.isValidGreqlValue(result); return result == null ? Undefined.UNDEFINED : result; } catch (IllegalArgumentException e) { if (e.getCause() instanceof GreqlException) { throw (GreqlException) e.getCause(); } else { throw new GreqlException( "When applying function " + fi.name + ": " + e.getMessage(), e.getCause()); } } catch (IllegalAccessException e) { if (e.getCause() instanceof GreqlException) { throw (GreqlException) e.getCause(); } else { throw new GreqlException( "When applying function " + fi.name + ": " + e.getMessage(), e.getCause()); } } catch (InvocationTargetException e) { if (e.getCause() instanceof GreqlException) { throw (GreqlException) e.getCause(); } else { throw new GreqlException( "When applying function " + fi.name + ": " + e.getMessage(), e.getCause()); } } } } StringBuilder sb = new StringBuilder(); sb.append("Function '").append(fi.name).append("' not defined for argument types ("); String delim = ""; for (Object arg : args) { sb.append(delim).append(Types.getGreqlTypeName(arg)); delim = ", "; } sb.append(")"); throw new GreqlException(sb.toString()); }
public void testAliasInvalidFilterValidJson() throws Exception { // invalid filter but valid json: put index template works fine, fails during index creation client() .admin() .indices() .preparePutTemplate("template_1") .setTemplate("te*") .addAlias(new Alias("invalid_alias").filter("{ \"invalid\": {} }")) .get(); GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates("template_1").get(); assertThat(response.getIndexTemplates().size(), equalTo(1)); assertThat(response.getIndexTemplates().get(0).getAliases().size(), equalTo(1)); assertThat( response.getIndexTemplates().get(0).getAliases().get("invalid_alias").filter().string(), equalTo("{\"invalid\":{}}")); try { createIndex("test"); fail( "index creation should have failed due to invalid alias filter in matching index template"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), equalTo("failed to parse filter for alias [invalid_alias]")); assertThat(e.getCause(), instanceOf(ParsingException.class)); assertThat(e.getCause().getMessage(), equalTo("No query registered for [invalid]")); } }
private String lastURL() throws URISyntaxException { try { Address adr = getAddress(); String scheme = decode(getScheme()).toString(); int port = adr.getPort(); if ((scheme.equals("http") && port == 80) || (scheme.equals("https") && port == 443)) { port = -1; } URI uri = new URI(scheme, null, adr.getHost(), port, null, null, null); uri = uri.resolve(getRequestURI()); return uri.toString(); } // URI can also throw IllegalArgumentException wrapping // a URISyntaxException. Unwrap it. catch (IllegalArgumentException x) { Throwable cause = x.getCause(); if ((cause != null) && (cause instanceof URISyntaxException)) { throw (URISyntaxException) cause; } else { throw x; } } }
/** Send the event notification. */ public void notify(T event) { Object instance = getInstance(); if (instance == null) return; Method method = _method.getJavaMember(); try { method.invoke(instance, getEventArguments(event)); } catch (IllegalArgumentException e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } catch (Exception e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } }
@ExceptionHandler(IllegalArgumentException.class) ResponseEntity<String> sendBadRequestException(IllegalArgumentException ex) { LOGGER.warn( "Exception was thrown, with cause " + ex.getCause() + "\nMessage: " + ex.getLocalizedMessage(), ex); return new ResponseEntity<>(ex.getLocalizedMessage(), HttpStatus.BAD_REQUEST); }
public void testHeaderMissingFile() throws Exception { final String missing = "no-such-file"; final String alias = "missing"; final String charsetName = "UTF-8"; try { FS.reserveFile(missing, charsetName, alias, true); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertTrue("Expected FNF", e.getCause() instanceof java.io.FileNotFoundException); } // Ensure second invocation gets same behaviour try { FS.reserveFile(missing, charsetName, alias, true); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertTrue("Expected FNF", e.getCause() instanceof java.io.FileNotFoundException); } }
public void testHeaderEmptyFile() throws Exception { final String empty = findTestPath("testfiles/empty.csv"); final String alias = "empty"; final String charsetName = "UTF-8"; try { String hdr = FS.reserveFile(empty, charsetName, alias, true); fail("Expected IllegalArgumentException|" + hdr + "|"); } catch (IllegalArgumentException e) { assertTrue("Expected EOF", e.getCause() instanceof java.io.EOFException); } // Ensure second invocation gets same behaviour try { FS.reserveFile(empty, charsetName, alias, true); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertTrue("Expected EOF", e.getCause() instanceof java.io.EOFException); } }
private boolean askedForStop() { File tempDir = fileSystem.getTempDir(); try (DefaultProcessCommands processCommands = new DefaultProcessCommands(tempDir, CURRENT_PROCESS_NUMBER, false)) { if (processCommands.askedForStop()) { return true; } } catch (IllegalArgumentException e) { // DefaultProcessCommand currently wraps IOException into a IllegalArgumentException // accessing the shared memory file may fail if a restart is in progress and the temp // directory // is currently deleted and not yet recreated if (e.getCause() instanceof IOException) { ignore((IOException) e.getCause()); } else { rethrow(e); } } catch (Exception e) { rethrow(e); } return false; }
/** * Create move refactoring session. * * @param cmr move settings, contains resource paths to move. * @return refactoring session id. * @throws JavaModelException when JavaModel has a failure * @throws RefactoringException when impossible to create move refactoring session */ @POST @Path("move/create") @Consumes("application/json") @Produces("text/plain") public String createMoveRefactoring(CreateMoveRefactoring cmr) throws JavaModelException, RefactoringException { IJavaProject javaProject = model.getJavaProject(cmr.getProjectPath()); IJavaElement[] javaElements; try { Function<ElementToMove, IJavaElement> map = javaElement -> { try { if (javaElement.isPack()) { return javaProject.findPackageFragment( new org.eclipse.core.runtime.Path(javaElement.getPath())); } else { return javaProject.findType(javaElement.getPath()).getCompilationUnit(); } } catch (JavaModelException e) { throw new IllegalArgumentException(e); } }; javaElements = cmr.getElements().stream().map(map).toArray(IJavaElement[]::new); } catch (IllegalArgumentException e) { if (e.getCause() instanceof JavaModelException) { throw (JavaModelException) e.getCause(); } else { throw e; } } if (RefactoringAvailabilityTester.isMoveAvailable(new IResource[0], javaElements)) { return manager.createMoveRefactoringSession(javaElements); } throw new RefactoringException("Can't create move refactoring."); }
private Object getValueOfField(String fieldname, Class<?> sourceClass, Object source) { String sourceClassName = sourceClass.getName(); Field field = null; try { field = sourceClass.getDeclaredField(fieldname); field.setAccessible(true); } catch (SecurityException e) { fail( "Unable to retrieve " + fieldname + " field from " + sourceClassName + ": " + e.getCause()); } catch (NoSuchFieldException e) { fail( "Unable to retrieve " + fieldname + " field from " + sourceClassName + ": " + e.getCause()); } assertNotNull("." + fieldname + " field is null!?!", field); Object fieldValue = null; try { fieldValue = field.get(source); } catch (IllegalArgumentException e) { fail( "Unable to retrieve value of " + fieldname + " from " + sourceClassName + ": " + e.getCause()); } catch (IllegalAccessException e) { fail( "Unable to retrieve value of " + fieldname + " from " + sourceClassName + ": " + e.getCause()); } return fieldValue; }
/** * Parse, validate and set native JE environment properties for a given environment config. * * @param envConfig The JE environment config for which to set the properties. * @param jeProperties The JE environment properties to parse, validate and set. * @param configAttrMap Component supported JE properties to their configuration attributes map. * @return An environment config instance with given properties set. * @throws ConfigException If there is an error while parsing, validating and setting any of the * properties provided. */ public static EnvironmentConfig setJEProperties( EnvironmentConfig envConfig, SortedSet<String> jeProperties, HashMap<String, String> configAttrMap) throws ConfigException { if (jeProperties.isEmpty()) { // return default config. return envConfig; } // Set to catch duplicate properties. HashSet<String> uniqueJEProperties = new HashSet<>(); // Iterate through the config values associated with a JE property. for (String jeEntry : jeProperties) { StringTokenizer st = new StringTokenizer(jeEntry, "="); if (st.countTokens() != 2) { throw new ConfigException(ERR_CONFIG_JE_PROPERTY_INVALID_FORM.get(jeEntry)); } String jePropertyName = st.nextToken(); String jePropertyValue = st.nextToken(); // Check if it is a duplicate. if (uniqueJEProperties.contains(jePropertyName)) { throw new ConfigException(ERR_CONFIG_JE_DUPLICATE_PROPERTY.get(jePropertyName)); } // Set JE property. try { envConfig.setConfigParam(jePropertyName, jePropertyValue); // If this property shadows an existing config attribute. if (configAttrMap.containsKey(jePropertyName)) { LocalizableMessage message = ERR_CONFIG_JE_PROPERTY_SHADOWS_CONFIG.get( jePropertyName, attrMap.get(jePropertyName)); throw new ConfigException(message); } // Add this property to unique set. uniqueJEProperties.add(jePropertyName); } catch (IllegalArgumentException e) { logger.traceException(e); LocalizableMessage message = ERR_CONFIG_JE_PROPERTY_INVALID.get(jeEntry, e.getMessage()); throw new ConfigException(message, e.getCause()); } } return envConfig; }
public void testGetAttribute() throws Exception { RawAttributeMapper rawMapper = RawAttributeMapper.of(setupGenRule()); List<Label> value = rawMapper.get("data", BuildType.LABEL_LIST); assertNotNull(value); assertThat(value).containsExactly(Label.create("x", "data_a"), Label.create("x", "data_b")); // Configurable attribute: trying to directly access from a RawAttributeMapper throws a // type mismatch exception. try { rawMapper.get("srcs", BuildType.LABEL_LIST); fail("Expected srcs lookup to fail since the returned type is a SelectorList and not a list"); } catch (IllegalArgumentException e) { assertThat(e.getCause().getMessage()) .contains("SelectorList cannot be cast to java.util.List"); } }
/** Tests that RawAttributeMapper can't handle label visitation with configurable attributes. */ public void testVisitLabels() throws Exception { RawAttributeMapper rawMapper = RawAttributeMapper.of(setupGenRule()); try { rawMapper.visitLabels( new AttributeMap.AcceptsLabelAttribute() { @Override public void acceptLabelAttribute(Label label, Attribute attribute) { // Nothing to do. } }); fail("Expected label visitation to fail since one attribute is configurable"); } catch (IllegalArgumentException e) { assertThat(e.getCause().getMessage()) .contains("SelectorList cannot be cast to java.util.List"); } }
@Test public void testEvaluationThrowsException() throws Exception { final MethodCall<ParametersPassesExpressionUnitTest> methodCall = toMethodCall(ParametersPassesExpressionUnitTest.class, this, "test", "a", 1, "b", '2'); try { new Evaluator() .evaluate( proxyAnnotation(ParametersPassesExpression.class, "value", "a eq b"), METHOD, "test", methodCall); fail("Expected exception missing."); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("Expression not passed: a eq b")); assertThat(e.getCause() instanceof SpelEvaluationException, is(true)); } }
private static MXBeanProxy findMXBeanProxy(Class<?> mxbeanInterface) { synchronized (mxbeanProxies) { WeakReference<MXBeanProxy> proxyRef = mxbeanProxies.get(mxbeanInterface); MXBeanProxy p = (proxyRef == null) ? null : proxyRef.get(); if (p == null) { try { p = new MXBeanProxy(mxbeanInterface); } catch (IllegalArgumentException e) { String msg = "Cannot make MXBean proxy for " + mxbeanInterface.getName() + ": " + e.getMessage(); IllegalArgumentException iae = new IllegalArgumentException(msg, e.getCause()); iae.setStackTrace(e.getStackTrace()); throw iae; } mxbeanProxies.put(mxbeanInterface, new WeakReference<MXBeanProxy>(p)); } return p; } }
public void testUpdateSettingsCanNotChangeThreadPoolType() throws InterruptedException { String threadPoolName = randomThreadPoolName(); ThreadPool.ThreadPoolType invalidThreadPoolType = randomIncorrectThreadPoolType(threadPoolName); ThreadPool.ThreadPoolType validThreadPoolType = ThreadPool.THREAD_POOL_TYPES.get(threadPoolName); ThreadPool threadPool = null; try { threadPool = new ThreadPool( Settings.builder() .put("node.name", "testUpdateSettingsCanNotChangeThreadPoolType") .build()); ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); threadPool.setClusterSettings(clusterSettings); clusterSettings.applySettings( Settings.builder() .put("threadpool." + threadPoolName + ".type", invalidThreadPoolType.getType()) .build()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals( "illegal value can't update [threadpool.] from [{}] to [{" + threadPoolName + ".type=" + invalidThreadPoolType.getType() + "}]", e.getMessage()); assertThat( e.getCause().getMessage(), is( "setting threadpool." + threadPoolName + ".type to " + invalidThreadPoolType.getType() + " is not permitted; must be " + validThreadPoolType.getType())); } finally { terminateThreadPoolIfNeeded(threadPool); } }
@Test public void unsupportedResponseTypesNotMatched() { try { service.object(); fail(); } catch (IllegalArgumentException e) { assertThat(e) .hasMessage( "" + "Unable to create converter for class java.lang.Object\n" + " for method Service.object"); assertThat(e.getCause()) .hasMessage( "" + "Could not locate ResponseBody converter for class java.lang.Object.\n" + " Tried:\n" + " * retrofit2.BuiltInConverters\n" + " * retrofit2.converter.scalars.ScalarsConverterFactory"); } }
@Test public void testParsedFilter() { String q1 = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and @field3 = 100000"; try { FilterList filterList = (FilterList) buildFilter(q1); Assert.assertEquals(FilterList.Operator.MUST_PASS_ONE, filterList.getOperator()); Assert.assertEquals(1, filterList.getFilters().size()); Assert.assertEquals(2, ((FilterList) filterList.getFilters().get(0)).getFilters().size()); } catch (EagleQueryParseException e) { Assert.fail(e.getMessage()); } String q2 = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 < 100000)"; try { FilterList filterList = (FilterList) buildFilter(q2); Assert.assertEquals(FilterList.Operator.MUST_PASS_ONE, filterList.getOperator()); Assert.assertEquals(2, filterList.getFilters().size()); Assert.assertEquals(2, ((FilterList) filterList.getFilters().get(0)).getFilters().size()); } catch (EagleQueryParseException e) { Assert.fail(e.getMessage()); } // Test parse success but bad type of value String q3 = "@cluster = \"cluster1\" and @datacenter = \"dc1\" and ( @field3 = 100000 or @field3 < \"bad_int_100000\")"; boolean q3Ex = false; try { Assert.assertNull(buildFilter(q3)); } catch (EagleQueryParseException e) { Assert.fail(e.getMessage()); } catch (IllegalArgumentException e) { LOG.debug("Expect: ", e); Assert.assertTrue(e.getCause() instanceof NumberFormatException); q3Ex = true; } Assert.assertTrue(q3Ex); }
public Iterator<Authorizable> execute(final String query) throws RepositoryException, IOException { try { return userManager.findAuthorizables( new Query() { public <T> void build(QueryBuilder<T> builder) { try { // Must request more than MAX_RESULT_COUNT records explicitly builder.setLimit(0, MAX_RESULT_COUNT); new QueryTranslator<T>(builder).translate(query); } catch (IOException e) { throw new IllegalArgumentException(e); } } }); } catch (IllegalArgumentException e) { Throwable cause = e.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else { throw e; } } }
/** Create a map-reduce scratch directory on demand and return it. */ public String getMRScratchDir() { // if we are executing entirely on the client side - then // just (re)use the local scratch directory if (isLocalOnlyExecutionMode()) { return getLocalScratchDir(!explain); } try { Path dir = FileUtils.makeQualified(nonLocalScratchPath, conf); URI uri = dir.toUri(); return getScratchDir(uri.getScheme(), uri.getAuthority(), !explain, uri.getPath()); } catch (IOException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException( "Error while making MR scratch " + "directory - check filesystem config (" + e.getCause() + ")", e); } }
/* UT */ IteratorSearchResponse searchByTerms( final Map<String, String> terms, final String repositoryId, final Integer from, final int count, final Boolean exact, final Boolean expandVersion, final Boolean collapseResults, final List<ArtifactInfoFilter> filters, final List<Searcher> searchers) throws NoSuchRepositoryException, ResourceException, IOException { try { for (Searcher searcher : searchers) { if (searcher.canHandle(terms)) { SearchType searchType = searcher.getDefaultSearchType(); if (exact != null) { if (exact) { searchType = SearchType.EXACT; } else { searchType = SearchType.SCORED; } } // copy the list, to be able to modify it but do not interleave with potential recursive // calls List<ArtifactInfoFilter> actualFilters = new ArrayList<ArtifactInfoFilter>(filters); if (collapseResults) { // filters should affect only Keyword and GAVSearch! // TODO: maybe we should left this to the given Searcher implementation to handle (like // kw and gav // searcher is) // Downside would be that REST query params would be too far away from incoming call // (too spread) if (searcher instanceof KeywordSearcher || searcher instanceof MavenCoordinatesSearcher) { UniqueArtifactFilterPostprocessor filter = new UniqueArtifactFilterPostprocessor(); filter.addField(MAVEN.GROUP_ID); filter.addField(MAVEN.ARTIFACT_ID); filter.addField(MAVEN.PACKAGING); filter.addField(MAVEN.CLASSIFIER); filter.addField(MAVEN.REPOSITORY_ID); if (Boolean.TRUE.equals(expandVersion)) { filter.addField(MAVEN.VERSION); } // add this last, to collapse results but _after_ collectors collects! actualFilters.add(filter); } } final IteratorSearchResponse searchResponse = searcher.flatIteratorSearch( terms, repositoryId, from, count, null, false, searchType, actualFilters); if (searchResponse != null) { if (collapseResults && searchResponse.getTotalHitsCount() < COLLAPSE_OVERRIDE_TRESHOLD) { searchResponse.close(); // FIXME: fix this, this is ugly // We are returning null, to hint that we need UNCOLLAPSED search! // Needed, to be able to "signal" the fact that we are overriding collapsed switch // since we have to send it back in DTOs to REST client return null; // old code was a recursive call: // this was a "collapsed" search (probably initiated by UI), and we have less then // treshold hits // override collapse // return searchByTerms( terms, repositoryId, from, count, exact, expandVersion, // false, filters // ); } else { return searchResponse; } } } } } catch (IllegalArgumentException e) { if (e.getCause() instanceof ParseException) { // NEXUS-4372: illegal query -> 400 response throw new PlexusResourceException( Status.CLIENT_ERROR_BAD_REQUEST, e.getCause(), getNexusErrorResponse("search", e.getCause().getMessage())); } else { throw e; } } throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Requested search query is not supported"); }
/** * Calls File.listFiles() or File.listFiles(FileFilter) File.listFiles(FilenameFilter) remote * method from the client side. <br> * * @param request the http request * @param commonsConfigurator the commons configurator defined by the user * @param fileConfigurator the file configurator defined by the user * @param out the servlet output stream * @param username the client login (for security check) * @param filename the filename to call * @throws Exception */ public void listFiles( HttpServletRequest request, CommonsConfigurator commonsConfigurator, FileConfigurator fileConfigurator, OutputStream out, String username, String filename) throws Exception { debug("in listFiles()"); FileFilter fileFilter = null; FilenameFilter filenameFilter = null; fileFilter = ServerFilterUtil.buidFileFilter(request, fileConfigurator, username); filenameFilter = ServerFilterUtil.buildFilenameFilter(request, fileConfigurator, username); debug("After ServerFilterUtil.buidFileFilter"); filename = HttpConfigurationUtil.addRootPath(fileConfigurator, username, filename); File file = new File(filename); File[] files = null; try { if (fileFilter == null && filenameFilter == null) { files = file.listFiles(); } else if (fileFilter != null) { files = file.listFiles(fileFilter); } else if (filenameFilter != null) { files = file.listFiles(filenameFilter); } else { // Can not happen throw new IllegalArgumentException( Tag.PRODUCT_PRODUCT_FAIL + " Impossible else condition."); } } catch (IllegalArgumentException e) { // Necessary because Reloader wich extends ClassLoader can nor throw ClassNotFoundException if (e.getCause() != null && e.getCause() instanceof ClassNotFoundException) { throw new ClassNotFoundException(e.getCause().getMessage()); } } if (files == null) { writeLine(out, TransferStatus.SEND_OK); writeLine(out, null); return; } if (files.length == 0) { writeLine(out, TransferStatus.SEND_OK); writeLine(out, "[]"); return; } writeLine(out, TransferStatus.SEND_OK); for (File theFile : files) { String fileStr = theFile.toString(); fileStr = ReturnFileFormatter.format(fileConfigurator, username, fileStr); fileStr = HtmlConverter.toHtml(fileStr); writeLine(out, fileStr); } }
public void apply(FaceletContext ctx, UIComponent parent) throws IOException { // only process if it's been created if (null == parent || (null == (parent = parent.getParent())) || !(ComponentHandler.isNew(parent))) { return; } Map<String, Object> attrs = parent.getAttributes(); CompositeComponentBeanInfo componentBeanInfo = (CompositeComponentBeanInfo) attrs.get(UIComponent.BEANINFO_KEY); assert (null != componentBeanInfo); List<PropertyDescriptor> declaredAttributes = componentBeanInfo.getPropertyDescriptorsList(); // Get the value of required the name propertyDescriptor ValueExpression ve = name.getValueExpression(ctx, String.class); String strValue = (String) ve.getValue(ctx); // Search the propertyDescriptors for one for this attribute for (PropertyDescriptor cur : declaredAttributes) { if (strValue.endsWith(cur.getName())) { // If we have a match, no need to waste time // duplicating and replacing it. return; } } PropertyDescriptor propertyDescriptor; try { propertyDescriptor = new CCAttributePropertyDescriptor(strValue, null, null); declaredAttributes.add(propertyDescriptor); } catch (IntrospectionException ex) { throw new TagException( tag, "Unable to create property descriptor for property " + strValue, ex); } TagAttribute defaultTagAttribute = null; PropertyHandler defaultHandler = null; for (TagAttribute tagAttribute : this.tag.getAttributes().getAll()) { String attributeName = tagAttribute.getLocalName(); if ("default".equals(attributeName)) { // store the TagAttribute and the PropertyHandler for later // execution, as the handler for the default-attribute requires, // that the PropertyHandler for 'type' - if it exists - has been // applied first. defaultTagAttribute = tagAttribute; defaultHandler = ATTRIBUTE_MANAGER.getHandler(ctx, "default"); } else { PropertyHandler handler = ATTRIBUTE_MANAGER.getHandler(ctx, attributeName); if (handler != null) { handler.apply(ctx, attributeName, propertyDescriptor, tagAttribute); } } } if (defaultHandler != null) { // If the 'default'-attribute of cc:attribute was set, apply the // previously stored PropertyHandler (see above) now, as now it is // guaranteed that if a 'type'-attribute existed, that its handler // was already applied try { defaultHandler.apply(ctx, "default", propertyDescriptor, defaultTagAttribute); } catch (IllegalArgumentException ex) { // If the type (according to the type-attribute) can not be // found, the DefaultPropertyHandler will wrapp the // ClassNotFoundException into an IllegalArgumentException, // which is unwrapped into a TagException here. throw new TagException( tag, "'type' could not be resolved: " + ex.getCause(), ex.getCause()); } } this.nextHandler.apply(ctx, parent); }
public void start( LockReleaser lockReleaser, PersistenceManager persistenceManager, RelationshipTypeCreator relTypeCreator, Map<Object, Object> params) { if (!startIsOk) { return; } String cacheTypeName = (String) params.get(Config.CACHE_TYPE); CacheType cacheType = null; try { cacheType = cacheTypeName != null ? CacheType.valueOf(cacheTypeName) : DEFAULT_CACHE_TYPE; } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Invalid cache type, please use one of: " + Arrays.asList(CacheType.values()) + " or keep empty for default (" + DEFAULT_CACHE_TYPE + ")", e.getCause()); } if (!readOnly) { nodeManager = new NodeManager( graphDbService, cacheManager, lockManager, lockReleaser, transactionManager, persistenceManager, idGenerator, relTypeCreator, cacheType); } else { nodeManager = new ReadOnlyNodeManager( graphDbService, cacheManager, lockManager, lockReleaser, transactionManager, persistenceManager, idGenerator, cacheType); } // load and verify from PS RelationshipTypeData relTypes[] = null; PropertyIndexData propertyIndexes[] = null; // beginTx(); relTypes = persistenceManager.loadAllRelationshipTypes(); propertyIndexes = persistenceManager.loadPropertyIndexes(INDEX_COUNT); // commitTx(); nodeManager.addRawRelationshipTypes(relTypes); nodeManager.addPropertyIndexes(propertyIndexes); if (propertyIndexes.length < INDEX_COUNT) { nodeManager.setHasAllpropertyIndexes(true); } nodeManager.start(params); startIsOk = false; }