commit_id
stringlengths
40
40
project
stringclasses
11 values
commit_message
stringlengths
3
3.04k
type
stringclasses
3 values
url
stringclasses
11 values
git_diff
stringlengths
555
691k
b840ee2fb3875069fa1148c9c51a57fed5a9632c
intellij-community
IDEADEV-25382: idiotic "...please recompile"- error message killed--
c
https://github.com/JetBrains/intellij-community
diff --git a/compiler/impl/com/intellij/openapi/deployment/DeploymentUtilImpl.java b/compiler/impl/com/intellij/openapi/deployment/DeploymentUtilImpl.java index 87b13ed5164a3..d15996469fa1b 100644 --- a/compiler/impl/com/intellij/openapi/deployment/DeploymentUtilImpl.java +++ b/compiler/impl/com/intellij/openapi/deployment/DeploymentUtilImpl.java @@ -56,7 +56,7 @@ public boolean addModuleOutputContents(@NotNull CompileContext context, String[] sourceRoots = getSourceRootUrlsInReadAction(sourceModule); boolean ok = true; if (outputPath != null && sourceRoots.length != 0) { - ok = checkModuleOutputExists(outputPath, sourceModule, context); + ok = outputPath.exists(); boolean added = addItemsRecursively(items, outputPath, targetModule, outputRelativePath, fileFilter, possibleBaseOuputPath); if (!added) { LOG.assertTrue(possibleBaseOuputPath != null); @@ -91,18 +91,6 @@ public File compute() { }); } - private static boolean checkModuleOutputExists(final File outputPath, final Module sourceModule, CompileContext context) { - if (outputPath == null || !outputPath.exists()) { - String moduleName = ModuleUtil.getModuleNameInReadAction(sourceModule); - final String message = CompilerBundle.message("message.text.directory.not.found.please.recompile", - outputPath == null ? moduleName : FileUtil.toSystemDependentName(outputPath.getPath()), - moduleName); - context.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); - return false; - } - return true; - } - public void addLibraryLink(@NotNull final CompileContext context, @NotNull final BuildRecipe items, @NotNull final LibraryLink libraryLink, @@ -433,7 +421,6 @@ private static void addJarJavaModuleOutput(BuildRecipe instructions, final String[] sourceUrls = getSourceRootUrlsInReadAction(module); if (sourceUrls.length > 0) { final File outputPath = getModuleOutputPath(module); - checkModuleOutputExists(outputPath, module, context); if (outputPath != null) { if ("/".equals(relativePath) || "".equals(relativePath) || getRelativePathForManifestLinking("/").equals(relativePath)) { context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("message.text.invalid.output.path.for.module.jar", relativePath, module.getName(), linkContainerDescription), null, -1, -1);
b0f0d2f28988eeffff9f6f6bd211c77565cc2704
spring-framework
Polishing--
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java index c0ff6e5596c4..3d0840d0b774 100644 --- a/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java +++ b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ public void setExecutor(Executor defaultExecutor) { * Set the {@link BeanFactory} to be used when looking up executors by qualifier. */ @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } diff --git a/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java index 45df36843042..2fa911960a3e 100644 --- a/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java +++ b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java @@ -72,6 +72,7 @@ public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport private AsyncUncaughtExceptionHandler exceptionHandler; + /** * Create a new {@code AsyncExecutionInterceptor}. * @param defaultExecutor the {@link Executor} (typically a Spring {@link AsyncTaskExecutor} @@ -90,6 +91,7 @@ public AsyncExecutionInterceptor(Executor defaultExecutor) { this(defaultExecutor, new SimpleAsyncUncaughtExceptionHandler()); } + /** * Supply the {@link AsyncUncaughtExceptionHandler} to use to handle exceptions * thrown by invoking asynchronous methods with a {@code void} return type. @@ -98,6 +100,7 @@ public void setExceptionHandler(AsyncUncaughtExceptionHandler exceptionHandler) this.exceptionHandler = exceptionHandler; } + /** * Intercept the given method invocation, submit the actual calling of the method to * the correct task executor and return immediately to the caller. @@ -150,7 +153,6 @@ public Object call() throws Exception { * for all other cases, the exception will not be transmitted back to the client. * In that later case, the current {@link AsyncUncaughtExceptionHandler} will be * used to manage such exception. - * * @param ex the exception to handle * @param method the method that was invoked * @param params the parameters used to invoke the method @@ -159,13 +161,14 @@ protected void handleError(Throwable ex, Method method, Object... params) throws if (method.getReturnType().isAssignableFrom(Future.class)) { ReflectionUtils.rethrowException(ex); } - else { // Could not transmit the exception to the caller with default executor + else { + // Could not transmit the exception to the caller with default executor try { - exceptionHandler.handleUncaughtException(ex, method, params); + this.exceptionHandler.handleUncaughtException(ex, method, params); } - catch (Exception e) { - logger.error("exception handler has thrown an unexpected " + - "exception while invoking '" + method.toGenericString() + "'", e); + catch (Throwable ex2) { + logger.error("Exception handler for async method '" + method.toGenericString() + + "' threw unexpected exception itself", ex2); } } } @@ -175,8 +178,8 @@ protected void handleError(Throwable ex, Method method, Object... params) throws * Subclasses may override to provide support for extracting qualifier information, * e.g. via an annotation on the given method. * @return always {@code null} - * @see #determineAsyncExecutor(Method) * @since 3.1.2 + * @see #determineAsyncExecutor(Method) */ @Override protected String getExecutorQualifier(Method method) { diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java b/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java index 755feb26e4dc..834f63b55ab0 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java @@ -147,7 +147,7 @@ public enum SpelMessage { "The value ''{0}'' cannot be parsed as a long"), INVALID_FIRST_OPERAND_FOR_MATCHES_OPERATOR(Kind.ERROR, 1037, - "First operand to matches operator must be a string. ''{0}'' is not"), + "First operand to matches operator must be a string. ''{0}'' is not"), INVALID_SECOND_OPERAND_FOR_MATCHES_OPERATOR(Kind.ERROR, 1038, "Second operand to matches operator must be a string. ''{0}'' is not"), @@ -166,7 +166,7 @@ public enum SpelMessage { "Problem parsing right operand"), NOT_EXPECTED_TOKEN(Kind.ERROR, 1043, - "Unexpected token. Expected ''{0}'' but was ''{1}''"), + "Unexpected token. Expected ''{0}'' but was ''{1}''"), OOD(Kind.ERROR, 1044, "Unexpectedly ran out of input"),
76fcc81bc61342ed85f7a8a0c325e58162ff24e8
spring-framework
New method to return string representation of- typeDescriptor--
a
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/TypeDescriptor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/TypeDescriptor.java index 0d686c3832e2..f01863014e45 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/TypeDescriptor.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/TypeDescriptor.java @@ -25,6 +25,7 @@ import org.springframework.core.MethodParameter; import org.springframework.util.Assert; +// TODO doesn't support more than depth of one (eg. Map<String,List<Foo>> or List<String>[]) /** * Type metadata about a bindable target value. * @@ -269,6 +270,33 @@ public static TypeDescriptor forObject(Object object) { return valueOf(object.getClass()); } } + + /** + * @return a textual representation of the type descriptor (eg. Map<String,Foo>) for use in messages + */ + public String asString() { + StringBuffer stringValue = new StringBuffer(); + if (isArray()) { + // TODO should properly handle multi dimensional arrays + stringValue.append(getArrayComponentType().getName()).append("[]"); + } else { + stringValue.append(getType().getName()); + if (isCollection()) { + Class<?> collectionType = getCollectionElementType(); + if (collectionType!=null) { + stringValue.append("<").append(collectionType.getName()).append(">"); + } + } else if (isMap()) { + Class<?> keyType = getMapKeyType(); + Class<?> valType = getMapValueType(); + if (keyType!=null && valType!=null) { + stringValue.append("<").append(keyType.getName()).append(","); + stringValue.append(valType).append(">"); + } + } + } + return stringValue.toString(); + } // internal helpers
d6c09ee130cc88cc8317c7c2b02452ff6993f177
orientdb
Fixed bug on database drop in Maven Tests--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/test/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinitionTest.java b/core/src/test/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinitionTest.java index 3fe018f8f28..caa8598aa62 100644 --- a/core/src/test/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinitionTest.java +++ b/core/src/test/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinitionTest.java @@ -148,7 +148,6 @@ public void testReload() { final OSimpleKeyIndexDefinition loadedKeyIndexDefinition = new OSimpleKeyIndexDefinition(); loadedKeyIndexDefinition.fromStream(loadDocument); - databaseDocumentTx.close(); databaseDocumentTx.drop(); Assert.assertEquals(loadedKeyIndexDefinition, simpleKeyIndexDefinition); diff --git a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTest.java b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTest.java index b08ce2567de..0bd71d872a8 100644 --- a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTest.java +++ b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTest.java @@ -12,18 +12,18 @@ @Test public class OStorageLocalTest { - private boolean oldStorageOpen; + private boolean oldStorageOpen; - @BeforeMethod - public void beforeMethod() { - oldStorageOpen = OGlobalConfiguration.STORAGE_KEEP_OPEN.getValueAsBoolean(); - OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false); - } + @BeforeMethod + public void beforeMethod() { + oldStorageOpen = OGlobalConfiguration.STORAGE_KEEP_OPEN.getValueAsBoolean(); + OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false); + } - @AfterMethod - public void afterMethod() { - OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(oldStorageOpen); - } + @AfterMethod + public void afterMethod() { + OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(oldStorageOpen); + } public void withLegacyPath() { String dbPath = getDatabasePath(); @@ -40,7 +40,6 @@ public void withLegacyPath() { // Something was added to dbPath so the legacy situation was simulated dbPath += "/foo"; db = new ODatabaseDocumentTx("local:" + dbPath).open("admin", "admin"); - db.close(); db.drop(); Assert.assertTrue(true); }
8fcbc4e91c9dd1e7b5a69a416146960f7af1e711
hbase
HBASE-4169 FSUtils LeaseRecovery for non HDFS- FileSystems; added 4169-correction.txt correction--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1155441 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/src/main/java/org/apache/hadoop/hbase/util/FSMapRUtils.java b/src/main/java/org/apache/hadoop/hbase/util/FSMapRUtils.java index edca7f4d5ef3..e70b0d476e5f 100644 --- a/src/main/java/org/apache/hadoop/hbase/util/FSMapRUtils.java +++ b/src/main/java/org/apache/hadoop/hbase/util/FSMapRUtils.java @@ -29,10 +29,10 @@ /** * <a href="http://www.mapr.com">MapR</a> implementation. */ -public class FSMapRUtils { +public class FSMapRUtils extends FSUtils { private static final Log LOG = LogFactory.getLog(FSMapRUtils.class); - public static void recoverFileLease(final FileSystem fs, final Path p, + public void recoverFileLease(final FileSystem fs, final Path p, Configuration conf) throws IOException { LOG.info("Recovering file " + p.toString() + " by changing permission to readonly");
8eb76715a1a4a7cabc56a17c0d44bc6bb9d2ebcf
ReactiveX-RxJava
Add Single.doAfterTerminate()--
a
https://github.com/ReactiveX/RxJava
diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java index b577f9a812..3880da9b0c 100644 --- a/src/main/java/rx/Single.java +++ b/src/main/java/rx/Single.java @@ -36,6 +36,7 @@ import rx.internal.operators.OperatorDelay; import rx.internal.operators.OperatorDoOnEach; import rx.internal.operators.OperatorDoOnUnsubscribe; +import rx.internal.operators.OperatorFinally; import rx.internal.operators.OperatorMap; import rx.internal.operators.OperatorObserveOn; import rx.internal.operators.OperatorOnErrorReturn; @@ -2020,4 +2021,25 @@ public void call(SingleSubscriber<? super T> singleSubscriber) { public final Single<T> doOnUnsubscribe(final Action0 action) { return lift(new OperatorDoOnUnsubscribe<T>(action)); } + + /** + * Registers an {@link Action0} to be called when this {@link Single} invokes either + * {@link SingleSubscriber#onSuccess(Object)} onSuccess} or {@link SingleSubscriber#onError onError}. + * <p> + * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/finallyDo.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * + * @param action + * an {@link Action0} to be invoked when the source {@link Single} finishes. + * @return a {@link Single} that emits the same item or error as the source {@link Single}, then invokes the + * {@link Action0} + * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> + */ + @Experimental + public final Single<T> doAfterTerminate(Action0 action) { + return lift(new OperatorFinally<T>(action)); + } } diff --git a/src/test/java/rx/SingleTest.java b/src/test/java/rx/SingleTest.java index 0fa8750709..17e3367835 100644 --- a/src/test/java/rx/SingleTest.java +++ b/src/test/java/rx/SingleTest.java @@ -51,7 +51,6 @@ import rx.schedulers.Schedulers; import rx.subscriptions.Subscriptions; - public class SingleTest { @Test @@ -891,4 +890,55 @@ public void call(SingleSubscriber<? super Object> singleSubscriber) { testSubscriber.assertNoValues(); testSubscriber.assertNoTerminalEvent(); } + + @Test + public void doAfterTerminateActionShouldBeInvokedAfterOnSuccess() { + Action0 action = mock(Action0.class); + + TestSubscriber<String> testSubscriber = new TestSubscriber<String>(); + + Single + .just("value") + .doAfterTerminate(action) + .subscribe(testSubscriber); + + testSubscriber.assertValue("value"); + testSubscriber.assertNoErrors(); + + verify(action).call(); + } + + @Test + public void doAfterTerminateActionShouldBeInvokedAfterOnError() { + Action0 action = mock(Action0.class); + + TestSubscriber<Object> testSubscriber = new TestSubscriber<Object>(); + + Throwable error = new IllegalStateException(); + + Single + .error(error) + .doAfterTerminate(action) + .subscribe(testSubscriber); + + testSubscriber.assertNoValues(); + testSubscriber.assertError(error); + + verify(action).call(); + } + + @Test + public void doAfterTerminateActionShouldNotBeInvokedUntilSubscriberSubscribes() { + Action0 action = mock(Action0.class); + + Single + .just("value") + .doAfterTerminate(action); + + Single + .error(new IllegalStateException()) + .doAfterTerminate(action); + + verifyZeroInteractions(action); + } }
74066765bb8ca85864f75bde6091f96207f988cf
hbase
HBASE-2889 Tool to look at HLogs -- parse and- tail -f; added part 1, some fixup of hlog main--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@995222 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hbase
diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java b/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java index e32b9816a6b6..a06bd13d8da7 100644 --- a/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java @@ -1869,7 +1869,7 @@ public static void main(String[] args) throws IOException { split(conf, logPath); } } catch (Throwable t) { - t.printStackTrace(); + t.printStackTrace(System.err); System.exit(-1); } }
ace77ef53fafa3194ce3c18d1cf00237f82a1dbc
restlet-framework-java
Removed Representation-getDigester* methods. There- is no reason to favor this way to wrap a Representation.--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.test/pom.xml b/modules/org.restlet.test/pom.xml index 849374dbdd..85ae717822 100644 --- a/modules/org.restlet.test/pom.xml +++ b/modules/org.restlet.test/pom.xml @@ -108,6 +108,12 @@ <artifactId>org.restlet.ext.netty</artifactId> <version>2.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.restlet.dev</groupId> + <artifactId>org.restlet.ext.odata</artifactId> + <version>2.0-SNAPSHOT</version> + </dependency> <dependency> <groupId>org.restlet.dev</groupId> diff --git a/modules/org.restlet.test/src/org/restlet/test/representation/DigestTestCase.java b/modules/org.restlet.test/src/org/restlet/test/representation/DigestTestCase.java index 0a376810f9..0f272a5476 100644 --- a/modules/org.restlet.test/src/org/restlet/test/representation/DigestTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/representation/DigestTestCase.java @@ -70,28 +70,26 @@ public Restlet createInboundRoot() { @Override public void handle(Request request, Response response) { Representation rep = request.getEntity(); - DigesterRepresentation digester = rep.getDigester(); try { // Such representation computes the digest while // consuming the wrapped representation. + DigesterRepresentation digester = new DigesterRepresentation( + rep); digester.exhaust(); - } catch (IOException e1) { - } - if (digester.checkDigest()) { - response.setStatus(Status.SUCCESS_OK); - StringRepresentation f = new StringRepresentation( - "9876543210"); - digester = f.getDigester(); - try { + if (digester.checkDigest()) { + response.setStatus(Status.SUCCESS_OK); + StringRepresentation f = new StringRepresentation( + "9876543210"); + digester = new DigesterRepresentation(f); // Consume first digester.exhaust(); - } catch (IOException e) { + // Set the digest + digester.setDigest(digester.computeDigest()); + response.setEntity(digester); + } else { + response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } - // Set the digest - digester.setDigest(digester.computeDigest()); - response.setEntity(digester); - } else { - response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); + } catch (Exception e1) { } } @@ -126,19 +124,23 @@ public void testGet() throws IOException, NoSuchAlgorithmException { Request request = new Request(Method.PUT, "http://localhost:" + TEST_PORT + "/"); StringRepresentation rep = new StringRepresentation("0123456789"); - DigesterRepresentation digester = rep.getDigester(); - // Such representation computes the digest while - // consuming the wrapped representation. - digester.exhaust(); - // Set the digest with the computed one - digester.setDigest(digester.computeDigest()); - request.setEntity(digester); + try { + DigesterRepresentation digester = new DigesterRepresentation(rep); + // Such representation computes the digest while + // consuming the wrapped representation. + digester.exhaust(); + // Set the digest with the computed one + digester.setDigest(digester.computeDigest()); + request.setEntity(digester); - Response response = client.handle(request); + Response response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); - digester = response.getEntity().getDigester(); - digester.exhaust(); - assertTrue(digester.checkDigest()); + assertEquals(Status.SUCCESS_OK, response.getStatus()); + digester = new DigesterRepresentation(response.getEntity()); + digester.exhaust(); + assertTrue(digester.checkDigest()); + } catch (Exception e) { + fail(e.getMessage()); + } } }
aecde5a15d035beb421ef31c4a005e273b2912a0
intellij-community
just one more DnDEnabler little fix :)--
c
https://github.com/JetBrains/intellij-community
diff --git a/source/com/intellij/ide/dnd/DnDEnabler.java b/source/com/intellij/ide/dnd/DnDEnabler.java index 68ee93a99a03d..c68cbb1276084 100644 --- a/source/com/intellij/ide/dnd/DnDEnabler.java +++ b/source/com/intellij/ide/dnd/DnDEnabler.java @@ -148,10 +148,6 @@ public void eventDispatched(AWTEvent event) { if (myDnDSource.getComponent().isFocusable()) { myDnDSource.getComponent().requestFocus(); } - - if (myOriginalDragGestureRecognizer != null) { - dispatchMouseEvent(myOriginalDragGestureRecognizer, e); - } } else { myDnDSource.processMouseEvent(e); @@ -164,6 +160,10 @@ public void eventDispatched(AWTEvent event) { } } } + + if (myOriginalDragGestureRecognizer != null) { + dispatchMouseEvent(myOriginalDragGestureRecognizer, e); + } } } }
c059f5382365930c7b87ff1dbaab0eae5452808a
spring-framework
SPR-7305 -- o.s.http.client.SimpleClientHttpRequestFactory does not allow to specify a- java.net.Proxy--
a
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java b/org.springframework.web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java index d41a06949989..cf864fcfc077 100644 --- a/org.springframework.web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java +++ b/org.springframework.web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,9 @@ import java.io.IOException; import java.net.HttpURLConnection; +import java.net.Proxy; import java.net.URI; +import java.net.URL; import java.net.URLConnection; import org.springframework.http.HttpMethod; @@ -34,17 +36,40 @@ */ public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory { + private Proxy proxy; + + /** + * Sets the {@link Proxy} to use for this request factory. + */ + public void setProxy(Proxy proxy) { + this.proxy = proxy; + } + public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { - URLConnection urlConnection = uri.toURL().openConnection(); - Assert.isInstanceOf(HttpURLConnection.class, urlConnection); - HttpURLConnection connection = (HttpURLConnection) urlConnection; + HttpURLConnection connection = openConnection(uri.toURL(), proxy); prepareConnection(connection, httpMethod.name()); return new SimpleClientHttpRequest(connection); } /** - * Template method for preparing the given {@link HttpURLConnection}. <p>The default implementation prepares the - * connection for input and output, and sets the HTTP method. + * Opens and returns a connection to the given URL. + * <p>The default implementation uses the given {@linkplain #setProxy(java.net.Proxy) proxy} - if any - to open a + * connection. + * + * @param url the URL to open a connection to + * @param proxy the proxy to use, may be {@code null} + * @return the opened connection + * @throws IOException in case of I/O errors + */ + protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException { + URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection(); + Assert.isInstanceOf(HttpURLConnection.class, urlConnection); + return (HttpURLConnection) urlConnection; + } + + /** + * Template method for preparing the given {@link HttpURLConnection}. + * <p>The default implementation prepares the connection for input and output, and sets the HTTP method. * * @param connection the connection to prepare * @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.) diff --git a/org.springframework.web/src/main/java/org/springframework/http/client/support/ProxyFactoryBean.java b/org.springframework.web/src/main/java/org/springframework/http/client/support/ProxyFactoryBean.java new file mode 100644 index 000000000000..0ba4e8154163 --- /dev/null +++ b/org.springframework.web/src/main/java/org/springframework/http/client/support/ProxyFactoryBean.java @@ -0,0 +1,87 @@ +/* + * Copyright 2002-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.http.client.support; + +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.SocketAddress; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.Assert; + +/** + * {@link FactoryBean} that creates a {@link Proxy java.net.Proxy}. + * + * @author Arjen Poutsma + * @since 3.0.4 + * @see FactoryBean + * @see Proxy + */ +public class ProxyFactoryBean implements FactoryBean<Proxy>, InitializingBean { + + private Proxy.Type type = Proxy.Type.HTTP; + + private String hostname; + + private int port = -1; + + private Proxy proxy; + + /** + * Sets the proxy type. Defaults to {@link Proxy.Type#HTTP}. + */ + public void setType(Proxy.Type type) { + this.type = type; + } + + /** + * Sets the proxy host name. + */ + public void setHostname(String hostname) { + this.hostname = hostname; + } + + /** + * Sets the proxy port. + */ + public void setPort(int port) { + this.port = port; + } + + public void afterPropertiesSet() throws IllegalArgumentException { + Assert.notNull(type, "'type' must not be null"); + Assert.hasLength(hostname, "'hostname' must not be empty"); + Assert.isTrue(port >= 0 && port <= 65535, "'port' out of range: " + port); + + SocketAddress socketAddress = new InetSocketAddress(hostname, port); + this.proxy = new Proxy(type, socketAddress); + + } + + public Proxy getObject() { + return proxy; + } + + public Class<?> getObjectType() { + return Proxy.class; + } + + public boolean isSingleton() { + return true; + } +} diff --git a/org.springframework.web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTest.java b/org.springframework.web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTest.java new file mode 100644 index 000000000000..1bb2e0e52426 --- /dev/null +++ b/org.springframework.web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTest.java @@ -0,0 +1,74 @@ +/* + * Copyright 2002-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.http.client.support; + +import java.net.InetSocketAddress; +import java.net.Proxy; + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; + +/** + * @author Arjen Poutsma + */ +public class ProxyFactoryBeanTest { + + ProxyFactoryBean factoryBean; + + @Before + public void setUp() { + factoryBean = new ProxyFactoryBean(); + } + + @Test(expected = IllegalArgumentException.class) + public void noType() { + factoryBean.setType(null); + factoryBean.afterPropertiesSet(); + } + + @Test(expected = IllegalArgumentException.class) + public void noHostname() { + factoryBean.setHostname(""); + factoryBean.afterPropertiesSet(); + } + + @Test(expected = IllegalArgumentException.class) + public void noPort() { + factoryBean.setHostname("example.com"); + factoryBean.afterPropertiesSet(); + } + + @Test + public void normal() { + Proxy.Type type = Proxy.Type.HTTP; + factoryBean.setType(type); + String hostname = "example.com"; + factoryBean.setHostname(hostname); + int port = 8080; + factoryBean.setPort(port); + factoryBean.afterPropertiesSet(); + + Proxy result = factoryBean.getObject(); + + assertEquals(type, result.type()); + InetSocketAddress address = (InetSocketAddress) result.address(); + assertEquals(hostname, address.getHostName()); + assertEquals(port, address.getPort()); + } + +}
6b3cef06538b2ba3ad1a67b8f0a67473b5596812
restlet-framework-java
- Cleaned code to remove Eclipse 3.4 warnings and- errors.--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/com.noelios.restlet.ext.javamail_1.4/src/com/noelios/restlet/ext/javamail/TriggerResource.java b/modules/com.noelios.restlet.ext.javamail_1.4/src/com/noelios/restlet/ext/javamail/TriggerResource.java index 9e1341b7b5..a0ce6e6c87 100644 --- a/modules/com.noelios.restlet.ext.javamail_1.4/src/com/noelios/restlet/ext/javamail/TriggerResource.java +++ b/modules/com.noelios.restlet.ext.javamail_1.4/src/com/noelios/restlet/ext/javamail/TriggerResource.java @@ -340,7 +340,6 @@ protected List<String> getMailIdentifiers() throws ResourceException { * @return The URI of the mail. * @throws ResourceException */ - @SuppressWarnings("unused") protected Reference getMailRef(String identifier) throws ResourceException { Template mailTemplate = new Template(getMailUriTemplate()); Reference result = new Reference(mailTemplate.format(new MailResolver( @@ -435,7 +434,6 @@ protected Status getResponseStatus(List<String> mailsSuccessful, * @return The target challengeResponse object. * @throws ResourceException */ - @SuppressWarnings("unused") protected ChallengeResponse getTargetChallengeResponse( Resolver<String> resolver) throws ResourceException { ChallengeScheme challengeScheme = ChallengeScheme.valueOf(resolver @@ -497,7 +495,6 @@ protected Method getTargetMethod(Resolver<String> resolver) { * @return The target reference. * @throws ResourceException */ - @SuppressWarnings("unused") protected Reference getTargetRef(Resolver<String> resolver) throws ResourceException { Template targetTemplate = new Template(getTargetUri()); diff --git a/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java b/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java index 2595846004..4558ccf553 100644 --- a/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java +++ b/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java @@ -381,7 +381,7 @@ protected Component createComponent() { // Define the list of supported client protocols. String clientProtocolsString = getInitParameter(CLIENTS_KEY, null); - if (component != null && clientProtocolsString != null) { + if (clientProtocolsString != null) { String[] clientProtocols = clientProtocolsString.split(" "); for (String clientProtocol : clientProtocols) { component.getClients().add(Protocol.valueOf(clientProtocol)); @@ -439,6 +439,7 @@ public void destroy() { * * @return The application. */ + @SuppressWarnings("null") public Application getApplication() { Application result = this.application; @@ -485,6 +486,7 @@ protected Class<?> getClass(String className) throws ClassNotFoundException { * * @return The component. */ + @SuppressWarnings("null") public Component getComponent() { Component result = this.component; @@ -547,6 +549,7 @@ public String getInitParameter(String name, String defaultValue) { * The HTTP Servlet request. * @return The HTTP server handling calls. */ + @SuppressWarnings("null") public HttpServerHelper getServer(HttpServletRequest request) { HttpServerHelper result = this.helper; diff --git a/modules/com.noelios.restlet.ext.xdb_11.1/src/com/noelios/restlet/ext/xdb/XdbServletConverter.java b/modules/com.noelios.restlet.ext.xdb_11.1/src/com/noelios/restlet/ext/xdb/XdbServletConverter.java index 52cca2326f..230341a2ed 100644 --- a/modules/com.noelios.restlet.ext.xdb_11.1/src/com/noelios/restlet/ext/xdb/XdbServletConverter.java +++ b/modules/com.noelios.restlet.ext.xdb_11.1/src/com/noelios/restlet/ext/xdb/XdbServletConverter.java @@ -117,7 +117,6 @@ public XdbServletConverter(ServletContext context, Restlet target) { CallableStatement preparedstatement = null; try { conn = XdbServerServlet.getConnection(); - @SuppressWarnings("unused") int endPoint = 1; preparedstatement = conn .prepareCall("{ call dbms_xdb.getListenerEndPoint(1,?,?,?) }"); @@ -152,7 +151,6 @@ public XdbServletConverter(ServletContext context, Restlet target) { * @throws ServletException * @throws IOException */ - @SuppressWarnings("unused") public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (getTarget() != null) { diff --git a/modules/com.noelios.restlet.ext.xdb_11.1/src/com/noelios/restlet/ext/xdb/XdbServletWarClientHelper.java b/modules/com.noelios.restlet.ext.xdb_11.1/src/com/noelios/restlet/ext/xdb/XdbServletWarClientHelper.java index 9ab45a63d8..3a13e1f642 100644 --- a/modules/com.noelios.restlet.ext.xdb_11.1/src/com/noelios/restlet/ext/xdb/XdbServletWarClientHelper.java +++ b/modules/com.noelios.restlet.ext.xdb_11.1/src/com/noelios/restlet/ext/xdb/XdbServletWarClientHelper.java @@ -104,7 +104,6 @@ public ServletConfig getConfig() { return this.config; } - @SuppressWarnings("unchecked") @Override public void handle(Request request, Response response) { PreparedStatement stmt = null; diff --git a/modules/com.noelios.restlet.test/src/com/noelios/restlet/test/ChunkedEncodingPutTestCase.java b/modules/com.noelios.restlet.test/src/com/noelios/restlet/test/ChunkedEncodingPutTestCase.java index f4690ec515..19375ca3e0 100644 --- a/modules/com.noelios.restlet.test/src/com/noelios/restlet/test/ChunkedEncodingPutTestCase.java +++ b/modules/com.noelios.restlet.test/src/com/noelios/restlet/test/ChunkedEncodingPutTestCase.java @@ -54,7 +54,6 @@ public PutTestResource(Context ctx, Request request, Response response) { } @Override - @SuppressWarnings("unchecked") public void storeRepresentation(Representation entity) { getResponse().setEntity(entity); } diff --git a/modules/com.noelios.restlet.test/src/com/noelios/restlet/test/ChunkedEncodingTestCase.java b/modules/com.noelios.restlet.test/src/com/noelios/restlet/test/ChunkedEncodingTestCase.java index 97efe41682..7ab9f1f5bf 100644 --- a/modules/com.noelios.restlet.test/src/com/noelios/restlet/test/ChunkedEncodingTestCase.java +++ b/modules/com.noelios.restlet.test/src/com/noelios/restlet/test/ChunkedEncodingTestCase.java @@ -75,7 +75,6 @@ public Representation represent(Variant variant) { } @Override - @SuppressWarnings("unchecked") public void storeRepresentation(Representation entity) { checkForChunkedHeader(getRequest()); diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/authentication/AuthenticationHelper.java b/modules/com.noelios.restlet/src/com/noelios/restlet/authentication/AuthenticationHelper.java index 154bf33e3a..98eb09340b 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/authentication/AuthenticationHelper.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/authentication/AuthenticationHelper.java @@ -141,7 +141,6 @@ public String format(ChallengeRequest request) { * The current request HTTP headers. * @return The authorization header value. */ - @SuppressWarnings("deprecation") public String format(ChallengeResponse challenge, Request request, Series<Parameter> httpHeaders) { StringBuilder sb = new StringBuilder(); diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/authentication/AuthenticationUtils.java b/modules/com.noelios.restlet/src/com/noelios/restlet/authentication/AuthenticationUtils.java index 250c53a011..2c87ff5c1b 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/authentication/AuthenticationUtils.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/authentication/AuthenticationUtils.java @@ -175,7 +175,6 @@ public static String format(ChallengeRequest request) { * The current request HTTP headers. * @return The authorization header value. */ - @SuppressWarnings("deprecation") public static String format(ChallengeResponse challenge, Request request, Series<Parameter> httpHeaders) { String result = null; diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpCall.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpCall.java index 7d7535a5cb..6d33821d71 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpCall.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpCall.java @@ -315,7 +315,6 @@ public int getServerPort() { * @return The status code. * @throws IOException */ - @SuppressWarnings("unused") public int getStatusCode() throws IOException { return this.statusCode; } diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerCall.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerCall.java index f821adabca..11b484f455 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerCall.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerCall.java @@ -554,7 +554,6 @@ public void writeResponseBody(Representation entity, * The response. * @throws IOException */ - @SuppressWarnings("unused") public void writeResponseHead(Response response) throws IOException { // Do nothing by default } diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerConverter.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerConverter.java index 3fa08f0f17..38abdf2eb7 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerConverter.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerConverter.java @@ -213,7 +213,6 @@ public HttpServerConverter(Context context) { * @param response * The response returned. */ - @SuppressWarnings("unchecked") protected void addEntityHeaders(HttpResponse response) { Series<Parameter> responseHeaders = response.getHttpCall() .getResponseHeaders(); diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamServerHelper.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamServerHelper.java index b823c7c39f..b834576df4 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamServerHelper.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamServerHelper.java @@ -156,7 +156,6 @@ protected ServerSocketChannel createServerSocket() throws IOException { * @return The created socket address. * @throws IOException */ - @SuppressWarnings("unused") protected SocketAddress createSocketAddress() throws IOException { if (getHelped().getAddress() == null) { return new InetSocketAddress(getHelped().getPort()); diff --git a/modules/org.restlet.ext.jaxb_2.1/src/org/restlet/ext/jaxb/JaxbRepresentation.java b/modules/org.restlet.ext.jaxb_2.1/src/org/restlet/ext/jaxb/JaxbRepresentation.java index 1a62e3ce2e..6aa803e2a1 100644 --- a/modules/org.restlet.ext.jaxb_2.1/src/org/restlet/ext/jaxb/JaxbRepresentation.java +++ b/modules/org.restlet.ext.jaxb_2.1/src/org/restlet/ext/jaxb/JaxbRepresentation.java @@ -360,7 +360,6 @@ public JaxbRepresentation(MediaType mediaType, T object) { * @throws IOException * If unmarshalling XML fails. */ - @SuppressWarnings("unchecked") public JaxbRepresentation(Representation xmlRepresentation, Class<T> type) { this(xmlRepresentation, type.getPackage().getName(), null); } @@ -381,7 +380,6 @@ public JaxbRepresentation(Representation xmlRepresentation, Class<T> type) { * @throws IOException * If unmarshalling XML fails. */ - @SuppressWarnings("unchecked") public JaxbRepresentation(Representation xmlRepresentation, Class<T> type, ValidationEventHandler validationHandler) { this(xmlRepresentation, type.getPackage().getName(), validationHandler); @@ -401,7 +399,6 @@ public JaxbRepresentation(Representation xmlRepresentation, Class<T> type, * @throws IOException * If unmarshalling XML fails. */ - @SuppressWarnings("unchecked") public JaxbRepresentation(Representation xmlRepresentation, String contextPath) { this(xmlRepresentation, contextPath, null); @@ -423,7 +420,6 @@ public JaxbRepresentation(Representation xmlRepresentation, * @throws IOException * If unmarshalling XML fails. */ - @SuppressWarnings("unchecked") public JaxbRepresentation(Representation xmlRepresentation, String contextPath, ValidationEventHandler validationHandler) { super(xmlRepresentation.getMediaType()); diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/JaxRsRestlet.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/JaxRsRestlet.java index a1e5212ddf..2d82f16ef2 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/JaxRsRestlet.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/JaxRsRestlet.java @@ -173,7 +173,6 @@ public class JaxRsRestlet extends Restlet { /** * Contains the thread localized {@link CallContext}s. */ - @SuppressWarnings("unchecked") private final ThreadLocalizedContext tlContext = new ThreadLocalizedContext(); private volatile ObjectFactory objectFactory; @@ -420,7 +419,6 @@ private boolean addProvider(Class<?> jaxRsProviderClass, } @Override - @SuppressWarnings("unchecked") public void start() throws Exception { for (Provider<?> provider : allProviders) provider.init(tlContext, entityProviders, contextResolvers, diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/CallContext.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/CallContext.java index 59301678a7..6e7263abdf 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/CallContext.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/CallContext.java @@ -263,10 +263,7 @@ public CallContext(Request request, org.restlet.data.Response response, this.readOnly = false; this.request = request; this.response = response; - if (roleChecker != null) - this.roleChecker = roleChecker; - else - this.roleChecker = RoleChecker.REJECT_WITH_ERROR; + this.roleChecker = roleChecker; this.accMediaTypes = SortedMetadata.getForMediaTypes(request .getClientInfo().getAcceptedMediaTypes()); } diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java index 1d88582500..86e0494847 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java @@ -203,7 +203,6 @@ public URI build() throws UriBuilderException { * @see javax.ws.rs.core.UriBuilder#build(java.util.Map) */ @Override - @SuppressWarnings("unchecked") public URI build(final Map<String, Object> values) throws IllegalArgumentException, UriBuilderException { Template template = new Template(toStringWithCheck(false)); diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedContext.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedContext.java index 17ba2024b6..c7ec6df71b 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedContext.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/ThreadLocalizedContext.java @@ -140,7 +140,6 @@ public List<String> getAcceptableLanguages() { * @see CallContext#getAcceptableMediaTypes() * @see HttpHeaders#getAcceptableMediaTypes() */ - @SuppressWarnings("deprecation") public List<MediaType> getAcceptableMediaTypes() { return get().getAcceptableMediaTypes(); } diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/UnmodifiableMultivaluedMap.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/UnmodifiableMultivaluedMap.java index 56adbb37c7..1ef0290922 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/UnmodifiableMultivaluedMap.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/core/UnmodifiableMultivaluedMap.java @@ -69,13 +69,11 @@ private UnmodifiableMultivaluedMap(MultivaluedMapImpl<K, V> mmap, } @Deprecated - @SuppressWarnings("unused") public void add(K key, V value) { throw throwUnmodifiable(); } @Deprecated - @SuppressWarnings("unused") public void clear() throws UnsupportedOperationException { throw throwUnmodifiable(); } @@ -158,27 +156,23 @@ public Set<K> keySet() { } @Deprecated - @SuppressWarnings("unused") public List<V> put(K key, List<V> value) throws UnsupportedOperationException { throw throwUnmodifiable(); } @Deprecated - @SuppressWarnings("unused") public void putAll(Map<? extends K, ? extends List<V>> t) throws UnsupportedOperationException { throw throwUnmodifiable(); } @Deprecated - @SuppressWarnings("unused") public void putSingle(K key, V value) throws UnsupportedOperationException { throw throwUnmodifiable(); } @Deprecated - @SuppressWarnings("unused") public List<V> remove(Object key) throws UnsupportedOperationException { throw throwUnmodifiable(); } diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java index 79a4b0d3b6..7970765291 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java @@ -271,7 +271,6 @@ else if (c == '%') { * @throws IllegalArgumentException * if encode is false and at least one character is invalid. */ - @SuppressWarnings("unused") public static CharSequence fullMatrix(CharSequence matrix, boolean encode) throws IllegalArgumentException { return fullQueryOrMatrix(matrix, ';', "%20", encode); @@ -286,7 +285,6 @@ public static CharSequence fullMatrix(CharSequence matrix, boolean encode) * @param encode * @return */ - @SuppressWarnings("unused") public static CharSequence fullQuery(CharSequence query, boolean encode) { return fullQueryOrMatrix(query, '&', "+", encode); } diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceClass.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceClass.java index 4ce9227199..4b030e49fe 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceClass.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/ResourceClass.java @@ -150,7 +150,6 @@ protected ResourceClass(Class<?> jaxRsClass, ThreadLocalizedContext tlContext, EntityProviders entityProviders, Collection<ContextResolver<?>> allCtxResolvers, ExtensionBackwardMapping extensionBackwardMapping, Logger logger, - @SuppressWarnings("unused") Logger sameLogger) throws IllegalArgumentException, IllegalPathOnClassException, MissingAnnotationException { super(PathRegExp.createForClass(jaxRsClass)); diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ContextResolverCollection.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ContextResolverCollection.java index 3241a1ea8a..41a48969cf 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ContextResolverCollection.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/provider/ContextResolverCollection.java @@ -40,7 +40,6 @@ public ContextResolverCollection(Collection<ContextResolver<?>> resolvers) { /** * @see javax.ws.rs.ext.ContextResolver#getContext(java.lang.Class) */ - @SuppressWarnings("unchecked") public Object getContext(Class<?> type) { for (ContextResolver<?> cr : resolvers) { Object context = cr.getContext(type); diff --git a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.java b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.java index 5c5ba232af..3182189dde 100644 --- a/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.java +++ b/modules/org.restlet.ext.jaxrs_0.8/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.java @@ -28,7 +28,6 @@ * @param <T> * the java type to convert to. */ -@SuppressWarnings("unchecked") public interface MessageBodyReader<T> extends javax.ws.rs.ext.MessageBodyReader<T> { /** diff --git a/modules/org.restlet.ext.shell/src/org/restlet/ext/shell/connectors/Shell.java b/modules/org.restlet.ext.shell/src/org/restlet/ext/shell/connectors/Shell.java index 10f38387bf..5d3a777f0e 100644 --- a/modules/org.restlet.ext.shell/src/org/restlet/ext/shell/connectors/Shell.java +++ b/modules/org.restlet.ext.shell/src/org/restlet/ext/shell/connectors/Shell.java @@ -28,7 +28,7 @@ public Shell(ScriptEngine aScriptEngine, String aPrompt) { public void loop() { for (;;) { // update completor - console.setCandidates(new TreeSet(scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).keySet())); + console.setCandidates(new TreeSet<String>(scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).keySet())); String line = console.readLine(prompt); diff --git a/modules/org.restlet.ext.shell/src/org/restlet/ext/shell/helpers/ConsoleHelper.java b/modules/org.restlet.ext.shell/src/org/restlet/ext/shell/helpers/ConsoleHelper.java index 86bd941be3..b9930298d6 100644 --- a/modules/org.restlet.ext.shell/src/org/restlet/ext/shell/helpers/ConsoleHelper.java +++ b/modules/org.restlet.ext.shell/src/org/restlet/ext/shell/helpers/ConsoleHelper.java @@ -9,13 +9,18 @@ public class ConsoleHelper { - private static final File historyFile = new File(System.getProperty("user.home") + File.separator + ".RESTSHell_history"); + private static final File historyFile = new File(System + .getProperty("user.home") + + File.separator + ".RESTSHell_history"); + private ConsoleReader consoleReader; + private History history; + private SimpleCompletor completor; public ConsoleHelper() { - /// ConsoleHelper + // / ConsoleHelper try { consoleReader = new ConsoleReader(); } catch (IOException e) { @@ -26,14 +31,15 @@ public ConsoleHelper() { try { history = new History(historyFile); } catch (IOException e) { - throw new RuntimeException(String.format("cannot initialize history file %s", historyFile), e); + throw new RuntimeException(String.format( + "cannot initialize history file %s", historyFile), e); } consoleReader.setHistory(history); consoleReader.setUseHistory(true); // Completition - completor = new SimpleCompletor(new String[]{"help", "version"}); + completor = new SimpleCompletor(new String[] { "help", "version" }); consoleReader.addCompletor(completor); } @@ -44,9 +50,9 @@ public String readLine(String aPrompt) { line = consoleReader.readLine(aPrompt); } catch (IOException e) { // do nothing - } finally { - return line; } + + return line; } public String readPassword(String aPrompt) { @@ -56,9 +62,9 @@ public String readPassword(String aPrompt) { password = consoleReader.readLine(aPrompt); } catch (IOException e) { // do nothing - } finally { - return password; } + + return password; } public void writeLine(String line) { diff --git a/modules/org.restlet.gwt/src/org/restlet/gwt/resource/Representation.java b/modules/org.restlet.gwt/src/org/restlet/gwt/resource/Representation.java index 9e26554f17..bc7937e637 100644 --- a/modules/org.restlet.gwt/src/org/restlet/gwt/resource/Representation.java +++ b/modules/org.restlet.gwt/src/org/restlet/gwt/resource/Representation.java @@ -1,329 +1,328 @@ -/* - * Copyright 2005-2008 Noelios Consulting. - * - * The contents of this file are subject to the terms of the Common Development - * and Distribution License (the "License"). You may not use this file except in - * compliance with the License. - * - * You can obtain a copy of the license at - * http://www.opensource.org/licenses/cddl1.txt See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing Covered Code, include this CDDL HEADER in each file and - * include the License file at http://www.opensource.org/licenses/cddl1.txt If - * applicable, add the following below this CDDL HEADER, with the fields - * enclosed by brackets "[]" replaced with your own identifying information: - * Portions Copyright [yyyy] [name of copyright owner] - */ - -package org.restlet.gwt.resource; - -import java.util.Date; - -import org.restlet.gwt.data.MediaType; -import org.restlet.gwt.data.Tag; - -/** - * Current or intended state of a resource. The content of a representation can - * be retrieved several times if there is a stable and accessible source, like a - * local file or a string. When the representation is obtained via a temporary - * source like a network socket, its content can only be retrieved once. The - * "transient" and "available" properties are available to help you figure out - * those aspects at runtime.<br> - * <br> - * For performance purpose, it is essential that a minimal overhead occurs upon - * initialization. The main overhead must only occur during invocation of - * content processing methods (write, getStream, getChannel and toString).<br> - * <br> - * "REST components perform actions on a resource by using a representation to - * capture the current or intended state of that resource and transferring that - * representation between components. A representation is a sequence of bytes, - * plus representation metadata to describe those bytes. Other commonly used but - * less precise names for a representation include: document, file, and HTTP - * message entity, instance, or variant." Roy T. Fielding - * - * @see <a - * href="http://roy.gbiv.com/pubs/dissertation/rest_arch_style.htm#sec_5_2_1_2">Source - * dissertation</a> - * @author Jerome Louvel ([email protected]) - */ -public abstract class Representation extends Variant { - /** - * Empty representation with no content. - */ - private static class EmptyRepresentation extends Representation { - - /** - * Constructor. - */ - public EmptyRepresentation() { - setAvailable(false); - setTransient(true); - setSize(0); - } - - @Override - public String getText() { - return null; - } - } - - /** - * Indicates that the size of the representation can't be known in advance. - */ - @SuppressWarnings("hiding") - public static final long UNKNOWN_SIZE = -1L; - - /** - * Returns a new empty representation with no content. - * - * @return A new empty representation. - */ - public static Representation createEmpty() { - return new EmptyRepresentation(); - } - - /** Indicates if the representation's content is available. */ - private volatile boolean available; - - /** Indicates if the representation is downloadable. */ - private volatile boolean downloadable; - - /** - * Indicates the suggested download file name for the representation's - * content. - */ - private volatile String downloadName; - - /** The expiration date. */ - private volatile Date expirationDate; - - /** Indicates if the representation's content is transient. */ - private volatile boolean isTransient; - - /** The modification date. */ - private volatile Date modificationDate; - - /** - * The expected size. Dynamic representations can have any size, but - * sometimes we can know in advance the expected size. If this expected size - * is specified by the user, it has a higher priority than any size that can - * be guessed by the representation (like a file size). - */ - private volatile long size; - - /** The tag. */ - private volatile Tag tag; - - /** - * Default constructor. - */ - public Representation() { - this(null); - } - - /** - * Constructor. - * - * @param mediaType - * The media type. - */ - public Representation(MediaType mediaType) { - super(mediaType); - this.available = true; - this.isTransient = false; - this.size = UNKNOWN_SIZE; - this.expirationDate = null; - this.modificationDate = null; - this.tag = null; - } - - /** - * Returns the suggested download file name for this representation. This is - * mainly used to suggest to the client a local name for a downloaded - * representation. - * - * @return The suggested file name for this representation. - */ - public String getDownloadName() { - return this.downloadName; - } - - /** - * Returns the future date when this representation expire. If this - * information is not known, returns null. - * - * @return The expiration date. - */ - public Date getExpirationDate() { - return this.expirationDate; - } - - /** - * Returns the last date when this representation was modified. If this - * information is not known, returns null. - * - * @return The modification date. - */ - public Date getModificationDate() { - return this.modificationDate; - } - - /** - * Returns the size in bytes if known, UNKNOWN_SIZE (-1) otherwise. - * - * @return The size in bytes if known, UNKNOWN_SIZE (-1) otherwise. - */ - public long getSize() { - return this.size; - } - - /** - * Returns the tag. - * - * @return The tag. - */ - public Tag getTag() { - return this.tag; - } - - /** - * Converts the representation to a string value. Be careful when using this - * method as the conversion of large content to a string fully stored in - * memory can result in OutOfMemoryErrors being thrown. - * - * @return The representation as a string value. - */ - public abstract String getText(); - - /** - * Indicates if some fresh content is available, without having to actually - * call one of the content manipulation method like getStream() that would - * actually consume it. This is especially useful for transient - * representation whose content can only be accessed once and also when the - * size of the representation is not known in advance. - * - * @return True if some fresh content is available. - */ - public boolean isAvailable() { - return (getSize() != 0) && this.available; - } - - /** - * Indicates if the representation is downloadable which means that it can - * be obtained via a download dialog box. - * - * @return True if the representation's content is downloadable. - */ - public boolean isDownloadable() { - return downloadable; - } - - /** - * Indicates if the representation's content is transient, which means that - * it can be obtained only once. This is often the case with representations - * transmitted via network sockets for example. In such case, if you need to - * read the content several times, you need to cache it first, for example - * into memory or into a file. - * - * @return True if the representation's content is transient. - */ - public boolean isTransient() { - return this.isTransient; - } - - /** - * Releases the representation's content and all associated objects like - * sockets, channels or files. If the representation is transient and hasn't - * been read yet, all the remaining content will be discarded, any open - * socket, channel, file or similar source of content will be immediately - * closed. The representation is also no more available. - */ - public void release() { - this.available = false; - } - - /** - * Indicates if some fresh content is available. - * - * @param available - * True if some fresh content is available. - */ - public void setAvailable(boolean available) { - this.available = available; - } - - /** - * Indicates if the representation is downloadable which means that it can - * be obtained via a download dialog box. - * - * @param downloadable - * True if the representation's content is downloadable. - */ - public void setDownloadable(boolean downloadable) { - this.downloadable = downloadable; - } - - /** - * Set the suggested download file name for this representation. - * - * @param fileName - * The suggested file name. - */ - public void setDownloadName(String fileName) { - this.downloadName = fileName; - } - - /** - * Sets the future date when this representation expire. If this information - * is not known, pass null. - * - * @param expirationDate - * The expiration date. - */ - public void setExpirationDate(Date expirationDate) { - this.expirationDate = expirationDate; - } - - /** - * Sets the last date when this representation was modified. If this - * information is not known, pass null. - * - * @param modificationDate - * The modification date. - */ - public void setModificationDate(Date modificationDate) { - this.modificationDate = modificationDate; - } - - /** - * Sets the expected size in bytes if known, -1 otherwise. - * - * @param expectedSize - * The expected size in bytes if known, -1 otherwise. - */ - public void setSize(long expectedSize) { - this.size = expectedSize; - } - - /** - * Sets the tag. - * - * @param tag - * The tag. - */ - public void setTag(Tag tag) { - this.tag = tag; - } - - /** - * Indicates if the representation's content is transient. - * - * @param isTransient - * True if the representation's content is transient. - */ - public void setTransient(boolean isTransient) { - this.isTransient = isTransient; - } - -} +/* + * Copyright 2005-2008 Noelios Consulting. + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the "License"). You may not use this file except in + * compliance with the License. + * + * You can obtain a copy of the license at + * http://www.opensource.org/licenses/cddl1.txt See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at http://www.opensource.org/licenses/cddl1.txt If + * applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets "[]" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + */ + +package org.restlet.gwt.resource; + +import java.util.Date; + +import org.restlet.gwt.data.MediaType; +import org.restlet.gwt.data.Tag; + +/** + * Current or intended state of a resource. The content of a representation can + * be retrieved several times if there is a stable and accessible source, like a + * local file or a string. When the representation is obtained via a temporary + * source like a network socket, its content can only be retrieved once. The + * "transient" and "available" properties are available to help you figure out + * those aspects at runtime.<br> + * <br> + * For performance purpose, it is essential that a minimal overhead occurs upon + * initialization. The main overhead must only occur during invocation of + * content processing methods (write, getStream, getChannel and toString).<br> + * <br> + * "REST components perform actions on a resource by using a representation to + * capture the current or intended state of that resource and transferring that + * representation between components. A representation is a sequence of bytes, + * plus representation metadata to describe those bytes. Other commonly used but + * less precise names for a representation include: document, file, and HTTP + * message entity, instance, or variant." Roy T. Fielding + * + * @see <a + * href="http://roy.gbiv.com/pubs/dissertation/rest_arch_style.htm#sec_5_2_1_2">Source + * dissertation</a> + * @author Jerome Louvel ([email protected]) + */ +public abstract class Representation extends Variant { + /** + * Empty representation with no content. + */ + private static class EmptyRepresentation extends Representation { + + /** + * Constructor. + */ + public EmptyRepresentation() { + setAvailable(false); + setTransient(true); + setSize(0); + } + + @Override + public String getText() { + return null; + } + } + + /** + * Indicates that the size of the representation can't be known in advance. + */ + public static final long UNKNOWN_SIZE = -1L; + + /** + * Returns a new empty representation with no content. + * + * @return A new empty representation. + */ + public static Representation createEmpty() { + return new EmptyRepresentation(); + } + + /** Indicates if the representation's content is available. */ + private volatile boolean available; + + /** Indicates if the representation is downloadable. */ + private volatile boolean downloadable; + + /** + * Indicates the suggested download file name for the representation's + * content. + */ + private volatile String downloadName; + + /** The expiration date. */ + private volatile Date expirationDate; + + /** Indicates if the representation's content is transient. */ + private volatile boolean isTransient; + + /** The modification date. */ + private volatile Date modificationDate; + + /** + * The expected size. Dynamic representations can have any size, but + * sometimes we can know in advance the expected size. If this expected size + * is specified by the user, it has a higher priority than any size that can + * be guessed by the representation (like a file size). + */ + private volatile long size; + + /** The tag. */ + private volatile Tag tag; + + /** + * Default constructor. + */ + public Representation() { + this(null); + } + + /** + * Constructor. + * + * @param mediaType + * The media type. + */ + public Representation(MediaType mediaType) { + super(mediaType); + this.available = true; + this.isTransient = false; + this.size = UNKNOWN_SIZE; + this.expirationDate = null; + this.modificationDate = null; + this.tag = null; + } + + /** + * Returns the suggested download file name for this representation. This is + * mainly used to suggest to the client a local name for a downloaded + * representation. + * + * @return The suggested file name for this representation. + */ + public String getDownloadName() { + return this.downloadName; + } + + /** + * Returns the future date when this representation expire. If this + * information is not known, returns null. + * + * @return The expiration date. + */ + public Date getExpirationDate() { + return this.expirationDate; + } + + /** + * Returns the last date when this representation was modified. If this + * information is not known, returns null. + * + * @return The modification date. + */ + public Date getModificationDate() { + return this.modificationDate; + } + + /** + * Returns the size in bytes if known, UNKNOWN_SIZE (-1) otherwise. + * + * @return The size in bytes if known, UNKNOWN_SIZE (-1) otherwise. + */ + public long getSize() { + return this.size; + } + + /** + * Returns the tag. + * + * @return The tag. + */ + public Tag getTag() { + return this.tag; + } + + /** + * Converts the representation to a string value. Be careful when using this + * method as the conversion of large content to a string fully stored in + * memory can result in OutOfMemoryErrors being thrown. + * + * @return The representation as a string value. + */ + public abstract String getText(); + + /** + * Indicates if some fresh content is available, without having to actually + * call one of the content manipulation method like getStream() that would + * actually consume it. This is especially useful for transient + * representation whose content can only be accessed once and also when the + * size of the representation is not known in advance. + * + * @return True if some fresh content is available. + */ + public boolean isAvailable() { + return (getSize() != 0) && this.available; + } + + /** + * Indicates if the representation is downloadable which means that it can + * be obtained via a download dialog box. + * + * @return True if the representation's content is downloadable. + */ + public boolean isDownloadable() { + return downloadable; + } + + /** + * Indicates if the representation's content is transient, which means that + * it can be obtained only once. This is often the case with representations + * transmitted via network sockets for example. In such case, if you need to + * read the content several times, you need to cache it first, for example + * into memory or into a file. + * + * @return True if the representation's content is transient. + */ + public boolean isTransient() { + return this.isTransient; + } + + /** + * Releases the representation's content and all associated objects like + * sockets, channels or files. If the representation is transient and hasn't + * been read yet, all the remaining content will be discarded, any open + * socket, channel, file or similar source of content will be immediately + * closed. The representation is also no more available. + */ + public void release() { + this.available = false; + } + + /** + * Indicates if some fresh content is available. + * + * @param available + * True if some fresh content is available. + */ + public void setAvailable(boolean available) { + this.available = available; + } + + /** + * Indicates if the representation is downloadable which means that it can + * be obtained via a download dialog box. + * + * @param downloadable + * True if the representation's content is downloadable. + */ + public void setDownloadable(boolean downloadable) { + this.downloadable = downloadable; + } + + /** + * Set the suggested download file name for this representation. + * + * @param fileName + * The suggested file name. + */ + public void setDownloadName(String fileName) { + this.downloadName = fileName; + } + + /** + * Sets the future date when this representation expire. If this information + * is not known, pass null. + * + * @param expirationDate + * The expiration date. + */ + public void setExpirationDate(Date expirationDate) { + this.expirationDate = expirationDate; + } + + /** + * Sets the last date when this representation was modified. If this + * information is not known, pass null. + * + * @param modificationDate + * The modification date. + */ + public void setModificationDate(Date modificationDate) { + this.modificationDate = modificationDate; + } + + /** + * Sets the expected size in bytes if known, -1 otherwise. + * + * @param expectedSize + * The expected size in bytes if known, -1 otherwise. + */ + public void setSize(long expectedSize) { + this.size = expectedSize; + } + + /** + * Sets the tag. + * + * @param tag + * The tag. + */ + public void setTag(Tag tag) { + this.tag = tag; + } + + /** + * Indicates if the representation's content is transient. + * + * @param isTransient + * True if the representation's content is transient. + */ + public void setTransient(boolean isTransient) { + this.isTransient = isTransient; + } + +} diff --git a/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java b/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java index eef871275c..cef4a2f1a3 100644 --- a/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java +++ b/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java @@ -31,7 +31,6 @@ */ public class RestletTestSuite extends TestSuite { /** Constructor. */ - @SuppressWarnings("deprecation") public RestletTestSuite() { addTestSuite(AtomTestCase.class); addTestSuite(ByteUtilsTestCase.class); diff --git a/modules/org.restlet.test/src/org/restlet/test/RiapTestCase.java b/modules/org.restlet.test/src/org/restlet/test/RiapTestCase.java index ead17ad481..38bc72e8c9 100644 --- a/modules/org.restlet.test/src/org/restlet/test/RiapTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/RiapTestCase.java @@ -57,7 +57,6 @@ public void testRiap() throws Exception { @Override public Restlet createRoot() { return new Restlet(getContext()) { - @SuppressWarnings("unchecked") @Override public void handle(Request request, Response response) { final String selfBase = "riap://application"; diff --git a/modules/org.restlet.test/src/org/restlet/test/RouteListTestCase.java b/modules/org.restlet.test/src/org/restlet/test/RouteListTestCase.java index 1998e38156..da8218fcac 100644 --- a/modules/org.restlet.test/src/org/restlet/test/RouteListTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/RouteListTestCase.java @@ -67,7 +67,6 @@ public void testGetNext() { assertSame(first, list.getNext(null, null, 1f)); } - @SuppressWarnings("null") public void testGetRandom() { RouteList list = new RouteList(); diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/IllegalConstructorResource.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/IllegalConstructorResource.java index d862e56d2b..6e6fcf7ddc 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/IllegalConstructorResource.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/IllegalConstructorResource.java @@ -29,7 +29,6 @@ * @author Stephan Koops * @see IllegalConstructorTest */ -@SuppressWarnings("unused") @Path("IllegalConstructorResource") public class IllegalConstructorResource { diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PersonsResource.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PersonsResource.java index b719497ef7..fec245195f 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PersonsResource.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/resources/PersonsResource.java @@ -63,7 +63,6 @@ public Response addPerson(Person person) { * @param person * @return */ - @SuppressWarnings("unused") private int createPerson(Person person) { return 5; } diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/CarTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/CarTest.java index 872af6616c..e27e739dc0 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/CarTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/CarTest.java @@ -51,7 +51,6 @@ public void testDelete() throws Exception { .getStatus()); } - @SuppressWarnings("null") public void testGetCar() throws Exception { String carNumber = "57"; @@ -69,7 +68,6 @@ public void testGetHtmlText() throws Exception { assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); } - @SuppressWarnings("null") public void testGetOffers() throws Exception { Response response = get("offers"); Representation representation = response.getEntity(); diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/InjectionTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/InjectionTest.java index 319d1c9361..cb2462d1ab 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/InjectionTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/InjectionTest.java @@ -42,7 +42,6 @@ public class InjectionTest extends JaxRsTestCase { protected ApplicationConfig getAppConfig() { ApplicationConfig appConfig = new ApplicationConfig() { @Override - @SuppressWarnings("unchecked") public Set<Class<?>> getResourceClasses() { Set<Class<?>> rrcs = new HashSet<Class<?>>(); rrcs.add(getRootResourceClass()); diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JaxRsTestCase.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JaxRsTestCase.java index ff2ef335cd..c580efa189 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JaxRsTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JaxRsTestCase.java @@ -274,7 +274,6 @@ public Response accessServer(Method httpMethod, Class<?> klasse, return accessServer(request); } - @SuppressWarnings("unchecked") public Response accessServer(Method httpMethod, Class<?> klasse, String subPath, MediaType accMediaType) { Collection<MediaType> mediaTypes = null; diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JsonTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JsonTest.java index 49211d4437..f91775a2cd 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JsonTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/JsonTest.java @@ -50,7 +50,6 @@ */ public class JsonTest extends JaxRsTestCase { - @SuppressWarnings("unchecked") @Override protected Class<?> getRootResourceClass() { return JsonTestService.class; diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java index d3a4192281..8a61334383 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java @@ -85,7 +85,6 @@ private Response getAndExpectAlphabet(String subPath) throws IOException { return response; } - @SuppressWarnings("unchecked") @Override protected Class<?> getRootResourceClass() { return ProviderTestService.class; @@ -95,7 +94,6 @@ protected Class<?> getRootResourceClass() { * @param subPath * @throws IOException */ - @SuppressWarnings("unused") private void postAndCheckXml(String subPath) throws Exception { Representation send = new DomRepresentation( new StringRepresentation( diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java index 59576e07bd..7fa9b2adde 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java @@ -182,7 +182,6 @@ public void testDateAndEntityTag4Put() throws Exception { .contains("The entity does not match Entity Tag")); } - @SuppressWarnings("deprecation") public void testGetDateNotModified() throws Exception { Conditions conditions = new Conditions(); conditions.setModifiedSince(AFTER); diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ResponseBuilderTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ResponseBuilderTest.java index 4d13c640d1..2506ebb5e0 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ResponseBuilderTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ResponseBuilderTest.java @@ -33,7 +33,6 @@ public class ResponseBuilderTest extends JaxRsTestCase { @Override - @SuppressWarnings("unchecked") protected Class<?> getRootResourceClass() { return ResponseBuilderService.class; } diff --git a/modules/org.restlet.test/src/org/restlet/test/spring/BeanNameRouterTest.java b/modules/org.restlet.test/src/org/restlet/test/spring/BeanNameRouterTest.java index b59b306532..3c74b1137a 100644 --- a/modules/org.restlet.test/src/org/restlet/test/spring/BeanNameRouterTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/spring/BeanNameRouterTest.java @@ -63,7 +63,6 @@ public void testRoutesCreatedForUrlAliases() throws Exception { .contains(FISH_URI)); } - @SuppressWarnings("null") public void testRoutesPointToFindersForBeans() throws Exception { router.postProcessBeanFactory(factory); diff --git a/modules/org.restlet/src/org/restlet/Component.java b/modules/org.restlet/src/org/restlet/Component.java index 820fc1fd93..d807606b7b 100644 --- a/modules/org.restlet/src/org/restlet/Component.java +++ b/modules/org.restlet/src/org/restlet/Component.java @@ -492,7 +492,6 @@ private Route attach(Router router, String targetClassName, * Is this route the default one? * @return the created route, or null. */ - @SuppressWarnings("unchecked") private Route attachWithDescriptor(Router router, String targetDescriptor, String uriPattern, boolean defaultRoute) { Route route = null; diff --git a/modules/org.restlet/src/org/restlet/Guard.java b/modules/org.restlet/src/org/restlet/Guard.java index 447de4290f..00a9b05d9e 100644 --- a/modules/org.restlet/src/org/restlet/Guard.java +++ b/modules/org.restlet/src/org/restlet/Guard.java @@ -215,7 +215,6 @@ public int authenticate(Request request) { * The request to authorize. * @return True if the request is authorized. */ - @SuppressWarnings("unused") public boolean authorize(Request request) { // Authorize everything by default return true; @@ -261,7 +260,6 @@ public void challenge(Response response, boolean stale) { * the identifier's secret * @return true if the secret is valid for the given identifier */ - @SuppressWarnings("unused") public boolean checkSecret(Request request, String identifier, char[] secret) { return checkSecret(identifier, secret); } diff --git a/modules/org.restlet/src/org/restlet/data/ChallengeResponse.java b/modules/org.restlet/src/org/restlet/data/ChallengeResponse.java index 1058a5bc6b..e86c478b4b 100644 --- a/modules/org.restlet/src/org/restlet/data/ChallengeResponse.java +++ b/modules/org.restlet/src/org/restlet/data/ChallengeResponse.java @@ -42,7 +42,6 @@ private final class PrincipalImpl implements Principal, Serializable { /** * Constructor for deserialization. */ - @SuppressWarnings("unused") private PrincipalImpl() { } diff --git a/modules/org.restlet/src/org/restlet/resource/ObjectRepresentation.java b/modules/org.restlet/src/org/restlet/resource/ObjectRepresentation.java index 48f6ef0794..2440f340ec 100644 --- a/modules/org.restlet/src/org/restlet/resource/ObjectRepresentation.java +++ b/modules/org.restlet/src/org/restlet/resource/ObjectRepresentation.java @@ -84,7 +84,6 @@ public ObjectRepresentation(T object) { * @return The represented object. * @throws IOException */ - @SuppressWarnings("unused") public T getObject() throws IOException { return this.object; } diff --git a/modules/org.restlet/src/org/restlet/resource/SaxRepresentation.java b/modules/org.restlet/src/org/restlet/resource/SaxRepresentation.java index fd8a376ba9..ace86b0ecc 100644 --- a/modules/org.restlet/src/org/restlet/resource/SaxRepresentation.java +++ b/modules/org.restlet/src/org/restlet/resource/SaxRepresentation.java @@ -231,7 +231,6 @@ public void write(OutputStream outputStream) throws IOException { * The XML writer to write to. * @throws IOException */ - @SuppressWarnings("unused") public void write(XmlWriter writer) throws IOException { // Do nothing by default. } diff --git a/modules/org.restlet/src/org/restlet/service/TunnelService.java b/modules/org.restlet/src/org/restlet/service/TunnelService.java index d2ab9548c4..2b35b6c336 100644 --- a/modules/org.restlet/src/org/restlet/service/TunnelService.java +++ b/modules/org.restlet/src/org/restlet/service/TunnelService.java @@ -223,8 +223,7 @@ public TunnelService(boolean enabled, boolean methodTunnel, * The client to test. * @return True if the request from a given client can be tunnelled. */ - public boolean allowClient(@SuppressWarnings("unused") - ClientInfo client) { + public boolean allowClient(ClientInfo client) { return true; } diff --git a/modules/org.restlet/src/org/restlet/util/ByteUtils.java b/modules/org.restlet/src/org/restlet/util/ByteUtils.java index b427bea602..c55bc523b5 100644 --- a/modules/org.restlet/src/org/restlet/util/ByteUtils.java +++ b/modules/org.restlet/src/org/restlet/util/ByteUtils.java @@ -492,7 +492,6 @@ public static void exhaust(InputStream input) throws IOException { * The input stream to convert. * @return A readable byte channel. */ - @SuppressWarnings("unused") public static ReadableByteChannel getChannel(InputStream inputStream) { return (inputStream != null) ? Channels.newChannel(inputStream) : null; } @@ -504,7 +503,6 @@ public static ReadableByteChannel getChannel(InputStream inputStream) { * The output stream. * @return A writable byte channel. */ - @SuppressWarnings("unused") public static WritableByteChannel getChannel(OutputStream outputStream) { return (outputStream != null) ? Channels.newChannel(outputStream) : null; @@ -608,7 +606,6 @@ public void run() { * The readable byte channel. * @return An input stream based on a given readable byte channel. */ - @SuppressWarnings("unused") public static InputStream getStream(ReadableByteChannel readableChannel) { InputStream result = null; @@ -641,7 +638,6 @@ public static InputStream getStream(Reader reader, CharacterSet characterSet) { * the representation to get the {@link OutputStream} from. * @return A stream with the representation's content. */ - @SuppressWarnings("unused") public static InputStream getStream(final Representation representation) { if (representation == null) { return null; @@ -708,7 +704,6 @@ public static OutputStream getStream(WritableByteChannel writableChannel) { * The writer. * @return the output stream of the writer */ - @SuppressWarnings("unused") public static OutputStream getStream(Writer writer) { return new WriterOutputStream(writer); }
7bb429c9cde94494cde83b99715149c680c1dae9
intellij-community
external system: add clickable link to log- folder to the project import failure message--
a
https://github.com/JetBrains/intellij-community
diff --git a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties index a2d53c3cf6433..1112ae3ca6c40 100644 --- a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties +++ b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties @@ -28,7 +28,8 @@ error.project.undefined=No external project config file is defined error.project.already.registered=The project is already registered error.cannot.parse.project=Can not parse {0} project error.resolve.with.reason={0}\n\nConsult IDE log for more details (Help | Show Log) -error.resolve.generic=Resolve error +error.resolve.with.log_link=<html>{0}<br><br>Consult IDE log for more details (<a href="{1}">Show Log</a>)<html> +error.resolve.generic=Resolve Error error.resolve.already.running=Another 'refresh project' task is currently running for the project: {0} # Tool window diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java index 6a3bb5ae28f26..c1e04c1af8627 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java @@ -1,6 +1,7 @@ package com.intellij.openapi.externalSystem.service.project.wizard; import com.intellij.ide.util.projectWizard.WizardContext; +import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.externalSystem.model.DataNode; @@ -276,8 +277,9 @@ public void onFailure(@NotNull String errorMessage, @Nullable String errorDetail if (!StringUtil.isEmpty(errorDetails)) { LOG.warn(errorDetails); } - error.set(new ConfigurationException(ExternalSystemBundle.message("error.resolve.with.reason", errorMessage), - ExternalSystemBundle.message("error.resolve.generic"))); + error.set(new ConfigurationException( + ExternalSystemBundle.message("error.resolve.with.log_link", errorMessage, PathManager.getLogPath()), + ExternalSystemBundle.message("error.resolve.generic"))); } };
296212eab186b860fd9494db9ed238b341fc2975
kotlin
Merge two JetTypeMapper-mapToCallableMethod- methods--
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ExpressionCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/ExpressionCodegen.java index 2be9032ebddaa..896f430d59004 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ExpressionCodegen.java +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ExpressionCodegen.java @@ -1472,7 +1472,7 @@ public Unit invoke(InstructionAdapter v) { ConstructorDescriptor constructorToCall = SamCodegenUtil.resolveSamAdapter(superConstructor); List<ValueParameterDescriptor> superValueParameters = superConstructor.getValueParameters(); int params = superValueParameters.size(); - List<Type> superMappedTypes = typeMapper.mapToCallableMethod(constructorToCall).getValueParameterTypes(); + List<Type> superMappedTypes = typeMapper.mapToCallableMethod(constructorToCall, false).getValueParameterTypes(); assert superMappedTypes.size() >= params : String .format("Incorrect number of mapped parameters vs arguments: %d < %d for %s", superMappedTypes.size(), params, classDescriptor); @@ -3414,7 +3414,7 @@ public Unit invoke(InstructionAdapter v) { pushClosureOnStack(constructor.getContainingDeclaration(), dispatchReceiver == null, defaultCallGenerator); constructor = SamCodegenUtil.resolveSamAdapter(constructor); - CallableMethod method = typeMapper.mapToCallableMethod(constructor); + CallableMethod method = typeMapper.mapToCallableMethod(constructor, false); invokeMethodWithArguments(method, resolvedCall, StackValue.none()); return Unit.INSTANCE$; diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/FunctionCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/FunctionCodegen.java index 43c94286739ef..b1c257a942940 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/FunctionCodegen.java +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/FunctionCodegen.java @@ -664,13 +664,7 @@ public static void generateDefaultImplBody( generator.putValueIfNeeded(parameterDescriptor, type, StackValue.local(parameterIndex, type)); } - CallableMethod method; - if (functionDescriptor instanceof ConstructorDescriptor) { - method = state.getTypeMapper().mapToCallableMethod((ConstructorDescriptor) functionDescriptor); - } - else { - method = state.getTypeMapper().mapToCallableMethod(functionDescriptor, false); - } + CallableMethod method = state.getTypeMapper().mapToCallableMethod(functionDescriptor, false); generator.genCallWithoutAssertions(method, codegen); diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java index dbd04bd4121ca..da405f940ff91 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java @@ -937,17 +937,16 @@ private void generateMethodCallTo( @Nullable FunctionDescriptor accessorDescriptor, @NotNull InstructionAdapter iv ) { - boolean isConstructor = functionDescriptor instanceof ConstructorDescriptor; - boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor; - - boolean superCall = accessorDescriptor instanceof AccessorForCallableDescriptor && - ((AccessorForCallableDescriptor) accessorDescriptor).getSuperCallExpression() != null; - CallableMethod callableMethod = isConstructor ? - typeMapper.mapToCallableMethod((ConstructorDescriptor) functionDescriptor) : - typeMapper.mapToCallableMethod(functionDescriptor, superCall); + CallableMethod callableMethod = typeMapper.mapToCallableMethod( + functionDescriptor, + accessorDescriptor instanceof AccessorForCallableDescriptor && + ((AccessorForCallableDescriptor) accessorDescriptor).getSuperCallExpression() != null + ); int reg = 1; - if (isConstructor && !accessorIsConstructor) { + + boolean accessorIsConstructor = accessorDescriptor instanceof AccessorForConstructorDescriptor; + if (!accessorIsConstructor && functionDescriptor instanceof ConstructorDescriptor) { iv.anew(callableMethod.getOwner()); iv.dup(); reg = 0; @@ -1496,8 +1495,8 @@ private void generateDelegatorToConstructorCall( iv.load(0, OBJECT_TYPE); ConstructorDescriptor delegateConstructor = SamCodegenUtil.resolveSamAdapter(codegen.getConstructorDescriptor(delegationConstructorCall)); - CallableMethod delegateConstructorCallable = typeMapper.mapToCallableMethod(delegateConstructor); - CallableMethod callable = typeMapper.mapToCallableMethod(constructorDescriptor); + CallableMethod delegateConstructorCallable = typeMapper.mapToCallableMethod(delegateConstructor, false); + CallableMethod callable = typeMapper.mapToCallableMethod(constructorDescriptor, false); List<JvmMethodParameterSignature> delegatingParameters = delegateConstructorCallable.getValueParameters(); List<JvmMethodParameterSignature> parameters = callable.getValueParameters(); @@ -1711,7 +1710,7 @@ private void initializeEnumConstant(@NotNull List<JetEnumEntry> enumEntries, int if (delegationSpecifiers.size() == 1 && !enumEntryNeedSubclass(bindingContext, enumEntry)) { ResolvedCall<?> resolvedCall = CallUtilPackage.getResolvedCallWithAssert(delegationSpecifiers.get(0), bindingContext); - CallableMethod method = typeMapper.mapToCallableMethod((ConstructorDescriptor) resolvedCall.getResultingDescriptor()); + CallableMethod method = typeMapper.mapToCallableMethod((ConstructorDescriptor) resolvedCall.getResultingDescriptor(), false); codegen.invokeMethodWithArguments(method, resolvedCall, StackValue.none()); } diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/state/JetTypeMapper.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/state/JetTypeMapper.java index dc57b4ac65db6..bf1c4772a95d8 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/state/JetTypeMapper.java +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/state/JetTypeMapper.java @@ -593,6 +593,12 @@ private Type mapKnownAsmType( @NotNull public CallableMethod mapToCallableMethod(@NotNull FunctionDescriptor descriptor, boolean superCall) { + if (descriptor instanceof ConstructorDescriptor) { + JvmMethodSignature method = mapSignature(descriptor); + Type owner = mapClass(((ConstructorDescriptor) descriptor).getContainingDeclaration()); + return new CallableMethod(owner, owner, owner, method, INVOKESPECIAL, null, null, null); + } + DeclarationDescriptor functionParent = descriptor.getOriginal().getContainingDeclaration(); FunctionDescriptor functionDescriptor = unwrapFakeOverride(descriptor.getOriginal()); @@ -1113,17 +1119,6 @@ public JvmMethodSignature mapScriptSignature(@NotNull ScriptDescriptor script, @ return sw.makeJvmMethodSignature("<init>"); } - @NotNull - public CallableMethod mapToCallableMethod(@NotNull ConstructorDescriptor descriptor) { - JvmMethodSignature method = mapSignature(descriptor); - ClassDescriptor container = descriptor.getContainingDeclaration(); - Type owner = mapClass(container); - if (owner.getSort() != Type.OBJECT) { - throw new IllegalStateException("type must have been mapped to object: " + container.getDefaultType() + ", actual: " + owner); - } - return new CallableMethod(owner, owner, owner, method, INVOKESPECIAL, null, null, null); - } - public Type getSharedVarType(DeclarationDescriptor descriptor) { if (descriptor instanceof SimpleFunctionDescriptor && descriptor.getContainingDeclaration() instanceof FunctionDescriptor) { return asmTypeForAnonymousClass(bindingContext, (FunctionDescriptor) descriptor);
846a05c7d078a6ba05f6ab3643ce6f382de784bc
drools
JBRULES-2817 Make the KnowledgeAgent Tests more- robust and faster--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@36213 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
p
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/agent/BaseKnowledgeAgentTest.java b/drools-compiler/src/test/java/org/drools/agent/BaseKnowledgeAgentTest.java new file mode 100644 index 00000000000..6533b96e76a --- /dev/null +++ b/drools-compiler/src/test/java/org/drools/agent/BaseKnowledgeAgentTest.java @@ -0,0 +1,312 @@ +package org.drools.agent; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.drools.KnowledgeBase; +import org.drools.core.util.DroolsStreamUtils; +import org.drools.core.util.FileManager; +import org.drools.core.util.IoUtils; +import org.drools.core.util.StringUtils; +import org.drools.event.knowledgeagent.AfterChangeSetAppliedEvent; +import org.drools.event.knowledgeagent.AfterChangeSetProcessedEvent; +import org.drools.event.knowledgeagent.AfterResourceProcessedEvent; +import org.drools.event.knowledgeagent.BeforeChangeSetAppliedEvent; +import org.drools.event.knowledgeagent.BeforeChangeSetProcessedEvent; +import org.drools.event.knowledgeagent.BeforeResourceProcessedEvent; +import org.drools.event.knowledgeagent.KnowledgeAgentEventListener; +import org.drools.event.knowledgeagent.KnowledgeBaseUpdatedEvent; +import org.drools.event.knowledgeagent.ResourceCompilationFailedEvent; +import org.drools.io.Resource; +import org.drools.io.ResourceFactory; +import org.drools.io.impl.ResourceChangeNotifierImpl; +import org.drools.io.impl.ResourceChangeScannerImpl; +import org.mortbay.jetty.Server; +import org.mortbay.jetty.handler.ResourceHandler; + +import junit.framework.TestCase; + +public abstract class BaseKnowledgeAgentTest extends TestCase { + FileManager fileManager; + Server server; + ResourceChangeScannerImpl scanner; + + @Override + protected void setUp() throws Exception { + this.fileManager = new FileManager(); + this.fileManager.setUp(); + ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset(); + + ResourceFactory.getResourceChangeNotifierService().start(); + + // we don't start the scanner, as we call it manually; + this.scanner = (ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService(); + + this.server = new Server( IoUtils.findPort() ); + ResourceHandler resourceHandler = new ResourceHandler(); + resourceHandler.setResourceBase( fileManager.getRootDirectory().getPath() ); + + this.server.setHandler( resourceHandler ); + + this.server.start(); + } + + @Override + protected void tearDown() throws Exception { + fileManager.tearDown(); + ResourceFactory.getResourceChangeNotifierService().stop(); + ((ResourceChangeNotifierImpl) ResourceFactory.getResourceChangeNotifierService()).reset(); + ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset(); + + server.stop(); + } + + + + public int getPort() { + return this.server.getConnectors()[0].getLocalPort(); + } + + + public void scan(KnowledgeAgent kagent) { + // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers + final CountDownLatch latch = new CountDownLatch( 1 ); + + KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() { + + public void resourceCompilationFailed(ResourceCompilationFailedEvent event) { + } + + public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) { + } + + public void beforeResourceProcessed(BeforeResourceProcessedEvent event) { + } + + public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) { + } + + public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) { + } + + public void afterResourceProcessed(AfterResourceProcessedEvent event) { + } + + public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) { + } + + public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) { + latch.countDown(); + } + }; + + kagent.addEventListener( l ); + + this.scanner.scan(); + + try { + latch.await( 10, TimeUnit.SECONDS ); + } catch ( InterruptedException e ) { + throw new RuntimeException( "Unable to wait for latch countdown", e); + } + + if ( latch.getCount() > 0 ) { + throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" ); + } + + kagent.removeEventListener( l ); + } + + void applyChangeSet(KnowledgeAgent kagent, String xml) { + // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers + final CountDownLatch latch = new CountDownLatch( 1 ); + + KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() { + + public void resourceCompilationFailed(ResourceCompilationFailedEvent event) { + } + + public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) { + } + + public void beforeResourceProcessed(BeforeResourceProcessedEvent event) { + } + + public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) { + } + + public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) { + } + + public void afterResourceProcessed(AfterResourceProcessedEvent event) { + } + + public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) { + } + + public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) { + latch.countDown(); + } + }; + + kagent.addEventListener( l ); + + kagent.applyChangeSet( ResourceFactory.newByteArrayResource( xml.getBytes() ) ); + + try { + latch.await( 10, TimeUnit.SECONDS ); + } catch ( InterruptedException e ) { + throw new RuntimeException( "Unable to wait for latch countdown", e); + } + + if ( latch.getCount() > 0 ) { + throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" ); + } + + kagent.removeEventListener( l ); + } + + void applyChangeSet(KnowledgeAgent kagent, Resource r) { + // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers + final CountDownLatch latch = new CountDownLatch( 1 ); + + KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() { + + public void resourceCompilationFailed(ResourceCompilationFailedEvent event) { + } + + public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) { + } + + public void beforeResourceProcessed(BeforeResourceProcessedEvent event) { + } + + public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) { + } + + public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) { + } + + public void afterResourceProcessed(AfterResourceProcessedEvent event) { + } + + public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) { + } + + public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) { + latch.countDown(); + } + }; + + kagent.addEventListener( l ); + + kagent.applyChangeSet( r ); + + try { + latch.await( 10, TimeUnit.SECONDS ); + } catch ( InterruptedException e ) { + throw new RuntimeException( "Unable to wait for latch countdown", e); + } + + if ( latch.getCount() > 0 ) { + throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" ); + } + + kagent.removeEventListener( l ); + } + + + public static void writePackage(Object pkg, + File p1file )throws IOException, FileNotFoundException { + if ( p1file.exists() ) { + // we want to make sure there is a time difference for lastModified and lastRead checks as Linux and http often round to seconds + // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789 + try { + Thread.sleep( 1000 ); + } catch (Exception e) { + throw new RuntimeException( "Unable to sleep" ); + } + } + FileOutputStream out = new FileOutputStream( p1file ); + try { + DroolsStreamUtils.streamOut( out, + pkg ); + } finally { + out.close(); + } + } + + public KnowledgeAgent createKAgent(KnowledgeBase kbase) { + return createKAgent( kbase, true ); + } + public KnowledgeAgent createKAgent(KnowledgeBase kbase, boolean newInsatnce) { + KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); + aconf.setProperty( "drools.agent.scanDirectories", + "true" ); + aconf.setProperty( "drools.agent.scanResources", + "true" ); + aconf.setProperty( "drools.agent.newInstance", + Boolean.toString( newInsatnce ) ); + + KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("test agent", + kbase, + aconf ); + + assertEquals( "test agent", + kagent.getName() ); + + return kagent; + } + + + public String createVersionedRule(String packageName, String ruleName, String attribute, String version) { + StringBuilder rule = new StringBuilder(); + if ( StringUtils.isEmpty( packageName ) ) { + rule.append( "package org.drools.test\n" ); + } else { + rule.append( "package " ); + rule.append( packageName ); + rule.append( "\n" ); + } + rule.append( "global java.util.List list\n" ); + rule.append( "rule " ); + rule.append( ruleName ); + rule.append( "\n" ); + if ( !StringUtils.isEmpty( attribute ) ) { + rule.append( attribute +"\n" ); + } + rule.append( "when\n" ); + rule.append( "then\n" ); + if ( StringUtils.isEmpty( version ) ) { + rule.append( "list.add( drools.getRule().getName() );\n" ); + } else { + rule.append("list.add( drools.getRule().getName()+\"-V" + version + "\");\n"); + } + rule.append( "end\n" ); + + return rule.toString(); + } + + public String createVersionedRule(String ruleName, String version) { + return createVersionedRule( null, ruleName, null, version ); + } + + public String createDefaultRule(String name) { + return createDefaultRule( name, + null ); + } + + public String createDefaultRule(String ruleName, + String packageName) { + return createVersionedRule( null, ruleName, null, null ); + } + + public String createAttributeRule(String ruleName, + String attribute) { + return createVersionedRule( null, ruleName, attribute, null ); + } +} diff --git a/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentBinaryDiffTests.java b/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentBinaryDiffTests.java index 300214a0ffd..b82c18a3759 100644 --- a/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentBinaryDiffTests.java +++ b/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentBinaryDiffTests.java @@ -22,45 +22,7 @@ import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.ResourceHandler; -public class KnowledgeAgentBinaryDiffTests extends TestCase { - - FileManager fileManager; - private Server server; - - @Override - protected void setUp() throws Exception { - fileManager = new FileManager(); - fileManager.setUp(); - ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset(); - ResourceFactory.getResourceChangeNotifierService().start(); - ResourceFactory.getResourceChangeScannerService().start(); - - this.server = new Server(0); - ResourceHandler resourceHandler = new ResourceHandler(); - resourceHandler.setResourceBase(fileManager.getRootDirectory().getPath()); - System.out.println("root : " + fileManager.getRootDirectory().getPath()); - - server.setHandler(resourceHandler); - - server.start(); - - System.out.println("Server running on port "+this.getPort()); - } - - private int getPort(){ - return this.server.getConnectors()[0].getLocalPort(); - } - - @Override - protected void tearDown() throws Exception { - fileManager.tearDown(); - ResourceFactory.getResourceChangeNotifierService().stop(); - ResourceFactory.getResourceChangeScannerService().stop(); - ((ResourceChangeNotifierImpl) ResourceFactory.getResourceChangeNotifierService()).reset(); - ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset(); - - server.stop(); - } +public class KnowledgeAgentBinaryDiffTests extends BaseKnowledgeAgentTest { public void testDifferentDateExpires() throws Exception { @@ -293,19 +255,9 @@ public void assertRuleAttribute(String attribute, Rule rule) { } public void testDifferentLHS() throws Exception { + File f1 = fileManager.write( "rule1.drl", + createDefaultRule( "rule1" ) ); - String header1 = ""; - header1 += "package org.drools.test\n"; - header1 += "global java.util.List list\n\n"; - - String rule1 = this.createCommonRule("rule1"); - - - File f1 = fileManager.newFile("rule1.drl"); - Writer output = new BufferedWriter(new FileWriter(f1)); - output.write(header1); - output.write(rule1); - output.close(); String xml = ""; xml += "<change-set xmlns='http://drools.org/drools-5.0/change-set'"; @@ -315,15 +267,13 @@ public void testDifferentLHS() throws Exception { xml += " <resource source='http://localhost:"+this.getPort()+"/rule1.drl' type='DRL' />"; xml += " </add> "; xml += "</change-set>"; - File fxml = fileManager.newFile("changeset.xml"); - output = new BufferedWriter(new FileWriter(fxml)); - output.write(xml); - output.close(); + File fxml = fileManager.write( "changeset.xml", + xml ); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - KnowledgeAgent kagent = this.createKAgent(kbase); - - kagent.applyChangeSet(ResourceFactory.newUrlResource(fxml.toURI().toURL())); + KnowledgeAgent kagent = this.createKAgent(kbase, false); + + applyChangeSet( kagent, ResourceFactory.newUrlResource(fxml.toURI().toURL()) ); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); List<String> list = new ArrayList<String>(); @@ -335,25 +285,11 @@ public void testDifferentLHS() throws Exception { assertTrue(list.contains("rule1")); list.clear(); - - // have to sleep here as linux lastModified does not do milliseconds - // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789 - Thread.sleep(2000); - - //String rule1v3 = this.createCommonRule("rule1","3"); - String rule1v2 = ""; - rule1v2 += "rule rule1\n"; - rule1v2 += "when\n"; - rule1v2 += "\tString()\n"; - rule1v2 += "then\n"; - rule1v2 += "list.add( drools.getRule().getName()+\"-V2\");\n"; - rule1v2 += "end\n"; - - output = new BufferedWriter(new FileWriter(f1)); - output.write(header1); - output.write(rule1v2); - output.close(); - Thread.sleep(3000); + + File f2 = fileManager.write( "rule1.drl", + createVersionedRule( "rule1", "2" ) ); + + scan(kagent); // Use the same session for incremental build test ksession = kbase.newStatefulKnowledgeSession(); @@ -365,24 +301,14 @@ public void testDifferentLHS() throws Exception { assertEquals(1, list.size()); assertTrue(list.contains("rule1-V2")); - kagent.monitorResourceChangeEvents(false); + kagent.dispose(); } public void testDifferentConsequences() throws Exception { - String header1 = ""; - header1 += "package org.drools.test\n"; - header1 += "global java.util.List list\n\n"; - - String rule1 = this.createCommonRule("rule1"); - - - File f1 = fileManager.newFile("rule1.drl"); - Writer output = new BufferedWriter(new FileWriter(f1)); - output.write(header1); - output.write(rule1); - output.close(); + File f1 = fileManager.write( "rule1.drl", + createDefaultRule( "rule1" ) ); String xml = ""; xml += "<change-set xmlns='http://drools.org/drools-5.0/change-set'"; @@ -392,15 +318,13 @@ public void testDifferentConsequences() throws Exception { xml += " <resource source='http://localhost:"+this.getPort()+"/rule1.drl' type='DRL' />"; xml += " </add> "; xml += "</change-set>"; - File fxml = fileManager.newFile("changeset.xml"); - output = new BufferedWriter(new FileWriter(fxml)); - output.write(xml); - output.close(); + File fxml = fileManager.write( "changeset.xml", + xml ); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - KnowledgeAgent kagent = this.createKAgent(kbase); - - kagent.applyChangeSet(ResourceFactory.newUrlResource(fxml.toURI().toURL())); + KnowledgeAgent kagent = this.createKAgent(kbase, false); + + applyChangeSet( kagent, ResourceFactory.newUrlResource(fxml.toURI().toURL()) ); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); List<String> list = new ArrayList<String>(); @@ -413,17 +337,10 @@ public void testDifferentConsequences() throws Exception { list.clear(); - // have to sleep here as linux lastModified does not do milliseconds - // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789 - Thread.sleep(2000); - - String rule1v2 = this.createCommonRule("rule1", "2"); - - output = new BufferedWriter(new FileWriter(f1)); - output.write(header1); - output.write(rule1v2); - output.close(); - Thread.sleep(3000); + fileManager.write( "rule1.drl", + createVersionedRule( "rule1", "2" ) ); + + scan( kagent ); // Use the same session for incremental build test ksession = kbase.newStatefulKnowledgeSession(); @@ -435,37 +352,12 @@ public void testDifferentConsequences() throws Exception { assertEquals(1, list.size()); assertTrue(list.contains("rule1-V2")); - kagent.monitorResourceChangeEvents(false); + kagent.dispose(); } - - - - - -// - - private void differentRuleAttributeTest(String attribute1, String attribute2,RuleAttributeAsserter asserter) throws Exception { - - String header1 = ""; - header1 += "package org.drools.test\n"; - header1 += "global java.util.List list\n\n"; - - String rule1 = ""; - rule1 += "rule rule1\n"; - rule1 += attribute1+"\n"; - rule1 += "when\n"; - rule1 += "\tString()\n"; - rule1 += "then\n"; - rule1 += "list.add( drools.getRule().getName());\n"; - rule1 += "end\n"; - - - File f1 = fileManager.newFile("rule1.drl"); - Writer output = new BufferedWriter(new FileWriter(f1)); - output.write(header1); - output.write(rule1); - output.close(); + private void differentRuleAttributeTest(String attribute1, String attribute2,RuleAttributeAsserter asserter) throws Exception { + File f1 = fileManager.write( "rule1.drl", + createAttributeRule( "rule1", attribute1 ) ); String xml = ""; xml += "<change-set xmlns='http://drools.org/drools-5.0/change-set'"; @@ -475,97 +367,30 @@ private void differentRuleAttributeTest(String attribute1, String attribute2,Rul xml += " <resource source='http://localhost:"+this.getPort()+"/rule1.drl' type='DRL' />"; xml += " </add> "; xml += "</change-set>"; - File fxml = fileManager.newFile("changeset.xml"); - output = new BufferedWriter(new FileWriter(fxml)); - output.write(xml); - output.close(); + File fxml = fileManager.write( "changeset.xml", + xml ); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - KnowledgeAgent kagent = this.createKAgent(kbase); + KnowledgeAgent kagent = this.createKAgent(kbase, false); - kagent.applyChangeSet(ResourceFactory.newUrlResource(fxml.toURI().toURL())); + applyChangeSet( kagent, ResourceFactory.newUrlResource(fxml.toURI().toURL())); org.drools.rule.Rule rule = (org.drools.rule.Rule) kagent.getKnowledgeBase().getRule("org.drools.test", "rule1"); assertNotNull(rule); asserter.assertRuleAttribute(attribute1, rule); - - // have to sleep here as linux lastModified does not do milliseconds - // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789 - Thread.sleep(2000); - - String rule1v2 = ""; - rule1v2 += "rule rule1\n"; - rule1v2 += attribute2+"\n"; - rule1v2 += "when\n"; - rule1v2 += "\tString()\n"; - rule1v2 += "then\n"; - rule1v2 += "list.add( drools.getRule().getName());\n"; - rule1v2 += "end\n"; - - output = new BufferedWriter(new FileWriter(f1)); - output.write(header1); - output.write(rule1v2); - output.close(); - Thread.sleep(3000); - + File f2 = fileManager.write( "rule1.drl", + createAttributeRule( "rule1", attribute2 ) ); + + scan( kagent ); + rule = (org.drools.rule.Rule) kagent.getKnowledgeBase().getRule("org.drools.test", "rule1"); assertNotNull(rule); asserter.assertRuleAttribute(attribute2, rule); - kagent.monitorResourceChangeEvents(false); + kagent.dispose(); } - - private KnowledgeAgent createKAgent(KnowledgeBase kbase) { - ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration(); - sconf.setProperty("drools.resource.scanner.interval", "2"); - ResourceFactory.getResourceChangeScannerService().configure(sconf); - - //System.setProperty(KnowledgeAgentFactory.PROVIDER_CLASS_NAME_PROPERTY_NAME, "org.drools.agent.impl.KnowledgeAgentProviderImpl"); - - KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); - aconf.setProperty("drools.agent.scanDirectories", "true"); - aconf.setProperty("drools.agent.scanResources", "true"); - // Testing incremental build here - aconf.setProperty("drools.agent.newInstance", "false"); - - - - KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent( - "test agent", kbase, aconf); - - assertEquals("test agent", kagent.getName()); - - return kagent; - } - - private String createCommonRule(String ruleName) { - StringBuilder sb = new StringBuilder(); - sb.append("rule "); - sb.append(ruleName); - sb.append("\n"); - sb.append("when\n"); - sb.append("then\n"); - sb.append("list.add( drools.getRule().getName() );\n"); - sb.append("end\n"); - - return sb.toString(); - } - - private String createCommonRule(String ruleName, String version) { - StringBuilder sb = new StringBuilder(); - sb.append("rule "); - sb.append(ruleName); - sb.append("\n"); - sb.append("when\n"); - sb.append("then\n"); - sb.append("list.add( drools.getRule().getName()+\"-V" + version + "\");\n"); - sb.append("end\n"); - - return sb.toString(); - } - } diff --git a/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentTest.java b/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentTest.java index 785d746f045..53abceefc03 100644 --- a/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentTest.java +++ b/drools-compiler/src/test/java/org/drools/agent/KnowledgeAgentTest.java @@ -42,193 +42,9 @@ import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.ResourceHandler; -public class KnowledgeAgentTest extends TestCase { +public class KnowledgeAgentTest extends BaseKnowledgeAgentTest { - FileManager fileManager; - private Server server; - - private ResourceChangeScannerImpl scanner; - - @Override - protected void setUp() throws Exception { - this.fileManager = new FileManager(); - this.fileManager.setUp(); - ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset(); - - ResourceFactory.getResourceChangeNotifierService().start(); - - // we don't start the scanner, as we call it manually; - this.scanner = (ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService(); - - this.server = new Server( IoUtils.findPort() ); - ResourceHandler resourceHandler = new ResourceHandler(); - resourceHandler.setResourceBase( fileManager.getRootDirectory().getPath() ); - - this.server.setHandler( resourceHandler ); - - this.server.start(); - } - - @Override - protected void tearDown() throws Exception { - fileManager.tearDown(); - ResourceFactory.getResourceChangeNotifierService().stop(); - ((ResourceChangeNotifierImpl) ResourceFactory.getResourceChangeNotifierService()).reset(); - ((ResourceChangeScannerImpl) ResourceFactory.getResourceChangeScannerService()).reset(); - - server.stop(); - } - - private int getPort() { - return this.server.getConnectors()[0].getLocalPort(); - } - - private void scan(KnowledgeAgent kagent) { - // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers - final CountDownLatch latch = new CountDownLatch( 1 ); - - KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() { - - public void resourceCompilationFailed(ResourceCompilationFailedEvent event) { - } - - public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) { - } - - public void beforeResourceProcessed(BeforeResourceProcessedEvent event) { - } - - public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) { - } - - public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) { - } - - public void afterResourceProcessed(AfterResourceProcessedEvent event) { - } - - public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) { - } - - public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) { - latch.countDown(); - } - }; - - kagent.addEventListener( l ); - - this.scanner.scan(); - - try { - latch.await( 10, TimeUnit.SECONDS ); - } catch ( InterruptedException e ) { - throw new RuntimeException( "Unable to wait for latch countdown", e); - } - - if ( latch.getCount() > 0 ) { - throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" ); - } - - kagent.removeEventListener( l ); - } - - void applyChangeSet(KnowledgeAgent kagent, String xml) { - // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers - final CountDownLatch latch = new CountDownLatch( 1 ); - - KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() { - - public void resourceCompilationFailed(ResourceCompilationFailedEvent event) { - } - - public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) { - } - - public void beforeResourceProcessed(BeforeResourceProcessedEvent event) { - } - - public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) { - } - - public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) { - } - - public void afterResourceProcessed(AfterResourceProcessedEvent event) { - } - - public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) { - } - - public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) { - latch.countDown(); - } - }; - - kagent.addEventListener( l ); - - kagent.applyChangeSet( ResourceFactory.newByteArrayResource( xml.getBytes() ) ); - - try { - latch.await( 10, TimeUnit.SECONDS ); - } catch ( InterruptedException e ) { - throw new RuntimeException( "Unable to wait for latch countdown", e); - } - - if ( latch.getCount() > 0 ) { - throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" ); - } - - kagent.removeEventListener( l ); - } - - void applyChangeSet(KnowledgeAgent kagent, Resource r) { - // Calls the Resource Scanner and sets up a listener and a latch so we can wait until it's finished processing, instead of using timers - final CountDownLatch latch = new CountDownLatch( 1 ); - - KnowledgeAgentEventListener l = new KnowledgeAgentEventListener() { - - public void resourceCompilationFailed(ResourceCompilationFailedEvent event) { - } - - public void knowledgeBaseUpdated(KnowledgeBaseUpdatedEvent event) { - } - - public void beforeResourceProcessed(BeforeResourceProcessedEvent event) { - } - - public void beforeChangeSetProcessed(BeforeChangeSetProcessedEvent event) { - } - - public void beforeChangeSetApplied(BeforeChangeSetAppliedEvent event) { - } - - public void afterResourceProcessed(AfterResourceProcessedEvent event) { - } - - public void afterChangeSetProcessed(AfterChangeSetProcessedEvent event) { - } - - public void afterChangeSetApplied(AfterChangeSetAppliedEvent event) { - latch.countDown(); - } - }; - - kagent.addEventListener( l ); - - kagent.applyChangeSet( r ); - - try { - latch.await( 10, TimeUnit.SECONDS ); - } catch ( InterruptedException e ) { - throw new RuntimeException( "Unable to wait for latch countdown", e); - } - - if ( latch.getCount() > 0 ) { - throw new RuntimeException( "Event for KnowlegeBase update, due to scan, was never received" ); - } - - kagent.removeEventListener( l ); - } + public void testModifyFileUrl() throws Exception { @@ -861,70 +677,4 @@ public void testStatelessWithCommands() throws Exception { assertTrue( list.contains( "rule2" ) ); } - private static void writePackage(Object pkg, - File p1file )throws IOException, FileNotFoundException { - if ( p1file.exists() ) { - // we want to make sure there is a time difference for lastModified and lastRead checks as Linux and http often round to seconds - // http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=019789 - try { - Thread.sleep( 1000 ); - } catch (Exception e) { - throw new RuntimeException( "Unable to sleep" ); - } - } - FileOutputStream out = new FileOutputStream( p1file ); - try { - DroolsStreamUtils.streamOut( out, - pkg ); - } finally { - out.close(); - } - } - - private KnowledgeAgent createKAgent(KnowledgeBase kbase) { - KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); - aconf.setProperty( "drools.agent.scanDirectories", - "true" ); - aconf.setProperty( "drools.agent.scanResources", - "true" ); - aconf.setProperty( "drools.agent.newInstance", - "true" ); - - KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("test agent", - kbase, - aconf ); - - assertEquals( "test agent", - kagent.getName() ); - - return kagent; - } - - private String createDefaultRule(String name) { - return this.createDefaultRule( name, - null ); - } - - private String createDefaultRule(String name, - String packageName) { - StringBuilder rule = new StringBuilder(); - if ( packageName == null ) { - rule.append( "package org.drools.test\n" ); - } else { - rule.append( "package " ); - rule.append( packageName ); - rule.append( "\n" ); - } - rule.append( "global java.util.List list\n" ); - rule.append( "rule " ); - rule.append( name ); - rule.append( "\n" ); - rule.append( "when\n" ); - rule.append( "then\n" ); - rule.append( "list.add( drools.getRule().getName() );\n" ); - rule.append( "end\n" ); - - return rule.toString(); - } - } diff --git a/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java b/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java index ef830e29d09..1fb5c11c704 100644 --- a/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java +++ b/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java @@ -110,6 +110,10 @@ public void unsubscribeNotifier(ResourceChangeNotifier notifier, // exist } } + } + + public Map<Resource, Set<ResourceChangeNotifier>> getResources() { + return resources; } public void scan() { @@ -161,6 +165,7 @@ public void scan() { // detect if Resource has been removed long lastModified = ((InternalResource) resource).getLastModified(); long lastRead = ((InternalResource) resource).getLastRead(); + if ( lastModified == 0 ) { this.listener.debug( "ResourceChangeScanner removed resource=" + resource ); removed.add( resource );
733faeffbd68719ac837d1aab954f4287573ca85
orientdb
fixes -1980: permissions follow role's- inheritance--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java index 06300fcae35..be24ed4209b 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java +++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OSecurityShared.java @@ -132,6 +132,13 @@ public boolean isAllowed(final Set<OIdentifiable> iAllowAll, final Set<OIdentifi // CHECK AGAINST SPECIFIC _ALLOW OPERATION if (iAllowOperation != null && iAllowOperation.contains(r.getDocument().getIdentity())) return true; + // CHECK inherited permissions from parent roles, fixes #1980: Record Level Security: permissions don't follow role's inheritance + ORole parentRole = r.getParentRole(); + while (parentRole!=null){ + if (iAllowAll.contains(parentRole.getDocument().getIdentity())) return true; + if (iAllowOperation != null && iAllowOperation.contains(parentRole.getDocument().getIdentity())) return true; + parentRole=parentRole.getParentRole(); + } } return false; }
fa18d6c9584bc1bc8ce6d001162dac4ab72009ff
restlet-framework-java
Added warning message when no client connector- supports the request's protocol.--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ClientRouter.java b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ClientRouter.java index cdbb84b329..b921c6c9c2 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ClientRouter.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ClientRouter.java @@ -29,7 +29,10 @@ import org.restlet.Client; import org.restlet.Component; +import org.restlet.Restlet; import org.restlet.Router; +import org.restlet.data.Request; +import org.restlet.data.Response; /** * Router that collects calls from all applications and dispatches them to the @@ -57,6 +60,19 @@ public ClientRouter(Component component) { this.component = component; } + @Override + public Restlet getNext(Request request, Response response) { + Restlet result = super.getNext(request, response); + if (result == null) { + getLogger() + .warning( + "The protocol used by this request is not declared in the list of client connectors. (" + + request.getResourceRef().getSchemeProtocol() + + ")"); + } + return result; + } + /** * Returns the parent component. * diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java index 400b1129b2..fc66f6e836 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java @@ -125,7 +125,7 @@ protected void doHandle(Request request, Response response) { } } else { getLogger().warning( - "No compoent is available to route the RIAP request."); + "No component is available to route the RIAP request."); } } else { getComponentContext().getComponentHelper().getClientRouter()
2a52decbbc8391f97ae443bb63032048ce2ae6c3
spring-framework
Polishing (including removal of javadoc imports- that show as package cycles in IntelliJ)--
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-context/src/main/java/org/springframework/scheduling/config/CronTask.java b/spring-context/src/main/java/org/springframework/scheduling/config/CronTask.java index cf859ab42739..b00b48060e84 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/config/CronTask.java +++ b/spring-context/src/main/java/org/springframework/scheduling/config/CronTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,6 @@ package org.springframework.scheduling.config; -import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.support.CronTrigger; /** @@ -26,13 +25,13 @@ * * @author Chris Beams * @since 3.2 - * @see Scheduled#cron() + * @see org.springframework.scheduling.annotation.Scheduled#cron() * @see ScheduledTaskRegistrar#setCronTasksList(java.util.List) * @see org.springframework.scheduling.TaskScheduler */ public class CronTask extends TriggerTask { - private String expression; + private final String expression; /** @@ -54,7 +53,9 @@ public CronTask(Runnable runnable, CronTrigger cronTrigger) { this.expression = cronTrigger.getExpression(); } + public String getExpression() { - return expression; + return this.expression; } + } diff --git a/spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java b/spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java index 744a6cd2b9e6..44dccafe90fc 100644 --- a/spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java +++ b/spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,8 @@ package org.springframework.test.util; -import static org.springframework.test.util.MatcherAssertionErrors.assertThat; - import java.io.StringReader; import java.util.Map; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; @@ -29,11 +26,12 @@ import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLUnit; import org.hamcrest.Matcher; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; +import static org.springframework.test.util.MatcherAssertionErrors.*; + /** * A helper class for assertions on XML content. * @@ -73,15 +71,12 @@ public void assertSource(String content, Matcher<? super Source> matcher) throws * Parse the expected and actual content strings as XML and assert that the * two are "similar" -- i.e. they contain the same elements and attributes * regardless of order. - * * <p>Use of this method assumes the * <a href="http://xmlunit.sourceforge.net/">XMLUnit<a/> library is available. - * * @param expected the expected XML content * @param actual the actual XML content - * - * @see MockMvcResultMatchers#xpath(String, Object...) - * @see MockMvcResultMatchers#xpath(String, Map, Object...) + * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers#xpath(String, Object...) + * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers#xpath(String, Map, Object...) */ public void assertXmlEqual(String expected, String actual) throws Exception { diff --git a/spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java b/spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java index 744a57ebf025..c680c27f7e30 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java +++ b/spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,10 @@ package org.springframework.transaction.config; +/** + * @author Chris Beams + * @since 3.1 + */ public abstract class TransactionManagementConfigUtils { /** diff --git a/spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java index 438b88a4b6e8..ec1173d73fcb 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/support/AllEncompassingFormHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,9 @@ */ public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConverter { + private static final boolean jaxb2Present = + ClassUtils.isPresent("javax.xml.bind.Binder", AllEncompassingFormHttpMessageConverter.class.getClassLoader()); + private static final boolean jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader()) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", AllEncompassingFormHttpMessageConverter.class.getClassLoader()); @@ -40,9 +43,6 @@ public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConv ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader()) && ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", AllEncompassingFormHttpMessageConverter.class.getClassLoader()); - private static final boolean jaxb2Present = - ClassUtils.isPresent("javax.xml.bind.Binder", AllEncompassingFormHttpMessageConverter.class.getClassLoader()); - @SuppressWarnings("deprecation") public AllEncompassingFormHttpMessageConverter() { diff --git a/spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java index e534359a6cb8..5f0f6fc308f8 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/xml/XmlAwareFormHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import javax.xml.transform.Source; import org.springframework.http.converter.FormHttpMessageConverter; -import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; /** * Extension of {@link org.springframework.http.converter.FormHttpMessageConverter}, @@ -27,7 +26,8 @@ * * @author Juergen Hoeller * @since 3.0.3 - * @deprecated in favor of {@link AllEncompassingFormHttpMessageConverter} + * @deprecated in favor of + * {@link org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter} */ @Deprecated public class XmlAwareFormHttpMessageConverter extends FormHttpMessageConverter { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java index e0ec640619c0..7b67dc163a31 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java @@ -28,7 +28,6 @@ import org.springframework.web.HttpSessionRequiredException; import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.support.WebApplicationObjectSupport; -import org.springframework.web.servlet.mvc.LastModified; /** * Convenient superclass for any kind of web content generator, @@ -204,7 +203,7 @@ public final boolean isUseCacheControlNoStore() { * programmatically do a lastModified calculation as described in * {@link WebRequest#checkNotModified(long)}. Default is "false", * effectively relying on whether the handler implements - * {@link LastModified} or not. + * {@link org.springframework.web.servlet.mvc.LastModified} or not. */ public void setAlwaysMustRevalidate(boolean mustRevalidate) { this.alwaysMustRevalidate = mustRevalidate; diff --git a/spring-webmvc/src/main/resources/META-INF/spring.handlers b/spring-webmvc/src/main/resources/META-INF/spring.handlers index b92dfeebba72..565c2c2c7671 100644 --- a/spring-webmvc/src/main/resources/META-INF/spring.handlers +++ b/spring-webmvc/src/main/resources/META-INF/spring.handlers @@ -1 +1 @@ -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler \ No newline at end of file +http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler
0e9594e02dae2859b0b247f8d3c1242acbf0e63d
elasticsearch
Internal: use AtomicInteger instead of volatile- int for the current action filter position--Also improved filter chain tests to not rely on execution time, and made filter chain tests look more similar to what happens in reality by removing multiple threads creation in testTooManyContinueProcessing (something we don't support anyway, makes little sense to test it).--Closes -7021-
c
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/action/support/TransportAction.java b/src/main/java/org/elasticsearch/action/support/TransportAction.java index cfff3b8cef614..1e3b8a8eb53a3 100644 --- a/src/main/java/org/elasticsearch/action/support/TransportAction.java +++ b/src/main/java/org/elasticsearch/action/support/TransportAction.java @@ -27,6 +27,8 @@ import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.elasticsearch.threadpool.ThreadPool; +import java.util.concurrent.atomic.AtomicInteger; + import static org.elasticsearch.action.support.PlainActionFuture.newFuture; /** @@ -146,12 +148,12 @@ public void run() { private class TransportActionFilterChain implements ActionFilterChain { - private volatile int index = 0; + private final AtomicInteger index = new AtomicInteger(); @SuppressWarnings("unchecked") @Override public void continueProcessing(String action, ActionRequest actionRequest, ActionListener actionListener) { - int i = index++; + int i = index.getAndIncrement(); try { if (i < filters.length) { filters[i].process(action, actionRequest, actionListener, this); diff --git a/src/main/java/org/elasticsearch/rest/RestController.java b/src/main/java/org/elasticsearch/rest/RestController.java index 89753639c7fe0..de8c7c66647dd 100644 --- a/src/main/java/org/elasticsearch/rest/RestController.java +++ b/src/main/java/org/elasticsearch/rest/RestController.java @@ -33,10 +33,9 @@ import java.io.IOException; import java.util.Arrays; import java.util.Comparator; +import java.util.concurrent.atomic.AtomicInteger; -import static org.elasticsearch.rest.RestStatus.BAD_REQUEST; -import static org.elasticsearch.rest.RestStatus.OK; -import static org.elasticsearch.rest.RestStatus.FORBIDDEN; +import static org.elasticsearch.rest.RestStatus.*; /** * @@ -216,7 +215,7 @@ class ControllerFilterChain implements RestFilterChain { private final RestFilter executionFilter; - private volatile int index; + private final AtomicInteger index = new AtomicInteger(); ControllerFilterChain(RestFilter executionFilter) { this.executionFilter = executionFilter; @@ -225,8 +224,7 @@ class ControllerFilterChain implements RestFilterChain { @Override public void continueProcessing(RestRequest request, RestChannel channel) { try { - int loc = index; - index++; + int loc = index.getAndIncrement(); if (loc > filters.length) { throw new ElasticsearchIllegalStateException("filter continueProcessing was called more than expected"); } else if (loc == filters.length) { diff --git a/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java b/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java index f5fa0bac9364c..433165afb0626 100644 --- a/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java +++ b/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java @@ -100,7 +100,7 @@ public int compare(ActionFilter o1, ActionFilter o2) { Collections.sort(testFiltersByLastExecution, new Comparator<TestFilter>() { @Override public int compare(TestFilter o1, TestFilter o2) { - return Long.compare(o1.lastExecution, o2.lastExecution); + return Integer.compare(o1.executionToken, o2.executionToken); } }); @@ -131,12 +131,7 @@ public void testTooManyContinueProcessing() throws ExecutionException, Interrupt @Override public void execute(final String action, final ActionRequest actionRequest, final ActionListener actionListener, final ActionFilterChain actionFilterChain) { for (int i = 0; i <= additionalContinueCount; i++) { - new Thread() { - @Override - public void run() { - actionFilterChain.continueProcessing(action, actionRequest, actionListener); - } - }.start(); + actionFilterChain.continueProcessing(action, actionRequest, actionListener); } } }); @@ -185,13 +180,15 @@ public void onFailure(Throwable e) { } } - private static class TestFilter implements ActionFilter { + private final AtomicInteger counter = new AtomicInteger(); + + private class TestFilter implements ActionFilter { private final int order; private final Callback callback; AtomicInteger runs = new AtomicInteger(); volatile String lastActionName; - volatile long lastExecution = Long.MAX_VALUE; //the filters that don't run will go last in the sorted list + volatile int executionToken = Integer.MAX_VALUE; //the filters that don't run will go last in the sorted list TestFilter(int order, Callback callback) { this.order = order; @@ -203,7 +200,7 @@ private static class TestFilter implements ActionFilter { public void process(String action, ActionRequest actionRequest, ActionListener actionListener, ActionFilterChain actionFilterChain) { this.runs.incrementAndGet(); this.lastActionName = action; - this.lastExecution = System.nanoTime(); + this.executionToken = counter.incrementAndGet(); this.callback.execute(action, actionRequest, actionListener, actionFilterChain); } diff --git a/src/test/java/org/elasticsearch/rest/FakeRestRequest.java b/src/test/java/org/elasticsearch/rest/FakeRestRequest.java new file mode 100644 index 0000000000000..e9f6dafe5805e --- /dev/null +++ b/src/test/java/org/elasticsearch/rest/FakeRestRequest.java @@ -0,0 +1,98 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.elasticsearch.rest; + +import org.elasticsearch.common.bytes.BytesReference; + +import java.util.HashMap; +import java.util.Map; + +class FakeRestRequest extends RestRequest { + + private final Map<String, String> headers; + + FakeRestRequest() { + this(new HashMap<String, String>()); + } + + FakeRestRequest(Map<String, String> headers) { + this.headers = headers; + } + + @Override + public Method method() { + return Method.GET; + } + + @Override + public String uri() { + return "/"; + } + + @Override + public String rawPath() { + return "/"; + } + + @Override + public boolean hasContent() { + return false; + } + + @Override + public boolean contentUnsafe() { + return false; + } + + @Override + public BytesReference content() { + return null; + } + + @Override + public String header(String name) { + return headers.get(name); + } + + @Override + public Iterable<Map.Entry<String, String>> headers() { + return headers.entrySet(); + } + + @Override + public boolean hasParam(String key) { + return false; + } + + @Override + public String param(String key) { + return null; + } + + @Override + public String param(String key, String defaultValue) { + return null; + } + + @Override + public Map<String, String> params() { + return null; + } +} \ No newline at end of file diff --git a/src/test/java/org/elasticsearch/rest/HeadersCopyClientTests.java b/src/test/java/org/elasticsearch/rest/HeadersCopyClientTests.java index e7a868c32633b..5536a1c03a706 100644 --- a/src/test/java/org/elasticsearch/rest/HeadersCopyClientTests.java +++ b/src/test/java/org/elasticsearch/rest/HeadersCopyClientTests.java @@ -35,7 +35,6 @@ import org.elasticsearch.client.support.AbstractClient; import org.elasticsearch.client.support.AbstractClusterAdminClient; import org.elasticsearch.client.support.AbstractIndicesAdminClient; -import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.threadpool.ThreadPool; @@ -332,75 +331,6 @@ private static void assertHeaders(ActionRequest<?> request, Map<String, String> } } - private static class FakeRestRequest extends RestRequest { - - private final Map<String, String> headers; - - private FakeRestRequest(Map<String, String> headers) { - this.headers = headers; - } - - @Override - public Method method() { - return null; - } - - @Override - public String uri() { - return null; - } - - @Override - public String rawPath() { - return null; - } - - @Override - public boolean hasContent() { - return false; - } - - @Override - public boolean contentUnsafe() { - return false; - } - - @Override - public BytesReference content() { - return null; - } - - @Override - public String header(String name) { - return headers.get(name); - } - - @Override - public Iterable<Map.Entry<String, String>> headers() { - return headers.entrySet(); - } - - @Override - public boolean hasParam(String key) { - return false; - } - - @Override - public String param(String key) { - return null; - } - - @Override - public String param(String key, String defaultValue) { - return null; - } - - @Override - public Map<String, String> params() { - return null; - } - } - private static class NoOpClient extends AbstractClient implements AdminClient { @Override diff --git a/src/test/java/org/elasticsearch/rest/RestFilterChainTests.java b/src/test/java/org/elasticsearch/rest/RestFilterChainTests.java new file mode 100644 index 0000000000000..3e84600b0b763 --- /dev/null +++ b/src/test/java/org/elasticsearch/rest/RestFilterChainTests.java @@ -0,0 +1,270 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.elasticsearch.rest; + +import com.google.common.collect.Lists; +import org.elasticsearch.common.Nullable; +import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.io.stream.BytesStreamOutput; +import org.elasticsearch.common.settings.ImmutableSettings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.test.ElasticsearchTestCase; +import org.junit.Test; + +import java.io.IOException; +import java.util.*; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class RestFilterChainTests extends ElasticsearchTestCase { + + @Test + public void testRestFilters() throws InterruptedException { + + RestController restController = new RestController(ImmutableSettings.EMPTY); + + int numFilters = randomInt(10); + Set<Integer> orders = new HashSet<>(numFilters); + while (orders.size() < numFilters) { + orders.add(randomInt(10)); + } + + List<RestFilter> filters = new ArrayList<>(); + for (Integer order : orders) { + TestFilter testFilter = new TestFilter(order, randomFrom(Operation.values())); + filters.add(testFilter); + restController.registerFilter(testFilter); + } + + ArrayList<RestFilter> restFiltersByOrder = Lists.newArrayList(filters); + Collections.sort(restFiltersByOrder, new Comparator<RestFilter>() { + @Override + public int compare(RestFilter o1, RestFilter o2) { + return Integer.compare(o2.order(), o1.order()); + } + }); + + List<RestFilter> expectedRestFilters = Lists.newArrayList(); + for (RestFilter filter : restFiltersByOrder) { + TestFilter testFilter = (TestFilter) filter; + expectedRestFilters.add(testFilter); + if (!(testFilter.callback == Operation.CONTINUE_PROCESSING) ) { + break; + } + } + + restController.registerHandler(RestRequest.Method.GET, "/", new RestHandler() { + @Override + public void handleRequest(RestRequest request, RestChannel channel) throws Exception { + channel.sendResponse(new TestResponse()); + } + }); + + FakeRestRequest fakeRestRequest = new FakeRestRequest(); + FakeRestChannel fakeRestChannel = new FakeRestChannel(fakeRestRequest, 1); + restController.dispatchRequest(fakeRestRequest, fakeRestChannel); + assertThat(fakeRestChannel.await(), equalTo(true)); + + + List<TestFilter> testFiltersByLastExecution = Lists.newArrayList(); + for (RestFilter restFilter : filters) { + testFiltersByLastExecution.add((TestFilter)restFilter); + } + Collections.sort(testFiltersByLastExecution, new Comparator<TestFilter>() { + @Override + public int compare(TestFilter o1, TestFilter o2) { + return Long.compare(o1.executionToken, o2.executionToken); + } + }); + + ArrayList<TestFilter> finalTestFilters = Lists.newArrayList(); + for (RestFilter filter : testFiltersByLastExecution) { + TestFilter testFilter = (TestFilter) filter; + finalTestFilters.add(testFilter); + if (!(testFilter.callback == Operation.CONTINUE_PROCESSING) ) { + break; + } + } + + assertThat(finalTestFilters.size(), equalTo(expectedRestFilters.size())); + + for (int i = 0; i < finalTestFilters.size(); i++) { + TestFilter testFilter = finalTestFilters.get(i); + assertThat(testFilter, equalTo(expectedRestFilters.get(i))); + assertThat(testFilter.runs.get(), equalTo(1)); + } + } + + @Test + public void testTooManyContinueProcessing() throws InterruptedException { + + final int additionalContinueCount = randomInt(10); + + TestFilter testFilter = new TestFilter(randomInt(), new Callback() { + @Override + public void execute(final RestRequest request, final RestChannel channel, final RestFilterChain filterChain) throws Exception { + for (int i = 0; i <= additionalContinueCount; i++) { + filterChain.continueProcessing(request, channel); + } + } + }); + + RestController restController = new RestController(ImmutableSettings.EMPTY); + restController.registerFilter(testFilter); + + restController.registerHandler(RestRequest.Method.GET, "/", new RestHandler() { + @Override + public void handleRequest(RestRequest request, RestChannel channel) throws Exception { + channel.sendResponse(new TestResponse()); + } + }); + + FakeRestRequest fakeRestRequest = new FakeRestRequest(); + FakeRestChannel fakeRestChannel = new FakeRestChannel(fakeRestRequest, additionalContinueCount + 1); + restController.dispatchRequest(fakeRestRequest, fakeRestChannel); + fakeRestChannel.await(); + + assertThat(testFilter.runs.get(), equalTo(1)); + + assertThat(fakeRestChannel.responses.get(), equalTo(1)); + assertThat(fakeRestChannel.errors.get(), equalTo(additionalContinueCount)); + } + + private static class FakeRestChannel extends RestChannel { + + private final CountDownLatch latch; + AtomicInteger responses = new AtomicInteger(); + AtomicInteger errors = new AtomicInteger(); + + protected FakeRestChannel(RestRequest request, int responseCount) { + super(request); + this.latch = new CountDownLatch(responseCount); + } + + @Override + public XContentBuilder newBuilder() throws IOException { + return super.newBuilder(); + } + + @Override + public XContentBuilder newBuilder(@Nullable BytesReference autoDetectSource) throws IOException { + return super.newBuilder(autoDetectSource); + } + + @Override + protected BytesStreamOutput newBytesOutput() { + return super.newBytesOutput(); + } + + @Override + public RestRequest request() { + return super.request(); + } + + @Override + public void sendResponse(RestResponse response) { + if (response.status() == RestStatus.OK) { + responses.incrementAndGet(); + } else { + errors.incrementAndGet(); + } + latch.countDown(); + } + + public boolean await() throws InterruptedException { + return latch.await(10, TimeUnit.SECONDS); + } + } + + private static enum Operation implements Callback { + CONTINUE_PROCESSING { + @Override + public void execute(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception { + filterChain.continueProcessing(request, channel); + } + }, + CHANNEL_RESPONSE { + @Override + public void execute(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception { + channel.sendResponse(new TestResponse()); + } + } + } + + private static interface Callback { + void execute(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception; + } + + private final AtomicInteger counter = new AtomicInteger(); + + private class TestFilter extends RestFilter { + private final int order; + private final Callback callback; + AtomicInteger runs = new AtomicInteger(); + volatile int executionToken = Integer.MAX_VALUE; //the filters that don't run will go last in the sorted list + + TestFilter(int order, Callback callback) { + this.order = order; + this.callback = callback; + } + + @Override + public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception { + this.runs.incrementAndGet(); + this.executionToken = counter.incrementAndGet(); + this.callback.execute(request, channel, filterChain); + } + + @Override + public int order() { + return order; + } + + @Override + public String toString() { + return "[order:" + order + ", executionToken:" + executionToken + "]"; + } + } + + private static class TestResponse extends RestResponse { + @Override + public String contentType() { + return null; + } + + @Override + public boolean contentThreadSafe() { + return false; + } + + @Override + public BytesReference content() { + return null; + } + + @Override + public RestStatus status() { + return RestStatus.OK; + } + } +}
012afd9ecc4659a2a86a1cd13a4af629bdcbc34a
restlet-framework-java
Added support of Ranges.--
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/application/RangeFilter.java b/modules/com.noelios.restlet/src/com/noelios/restlet/application/RangeFilter.java index b6b167fb6d..834e2b9ad8 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/application/RangeFilter.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/application/RangeFilter.java @@ -29,12 +29,18 @@ import org.restlet.Context; import org.restlet.Filter; +import org.restlet.data.Method; import org.restlet.data.Range; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.service.RangeService; +/** + * Filter that is in charge to check the responses to requests for partial + * content. + * + */ public class RangeFilter extends Filter { /** @@ -54,9 +60,21 @@ protected void afterHandle(Request request, Response response) { // At this time, list of ranges are not supported. Range requestedRange = request.getRanges().get(0); if (!requestedRange.equals(response.getEntity().getRange())) { + getLogger() + .info( + "The range of the response entity is not equals to the requested one."); response.setEntity(new RangeRepresentation(response .getEntity(), requestedRange)); } + if (Method.GET.equals(request.getMethod()) + && response.getStatus().isSuccess() + && !Status.SUCCESS_PARTIAL_CONTENT.equals(response + .getStatus())) { + response.setStatus(Status.SUCCESS_PARTIAL_CONTENT); + getLogger() + .info( + "The status of a response to a partial GET must be \"206 Partial content\"."); + } } else if (request.getRanges().size() > 1) { // Return a server error as this isn't supported yet response diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpClientCall.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpClientCall.java index 91be8fefb3..b44a4bb9e6 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpClientCall.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpClientCall.java @@ -317,8 +317,7 @@ public Representation getResponseEntity(Response response) { && !response.getStatus() .equals(Status.REDIRECTION_NOT_MODIFIED) && !response.getStatus().equals(Status.SUCCESS_NO_CONTENT) - && !response.getStatus().equals(Status.SUCCESS_RESET_CONTENT) - && !response.getStatus().equals(Status.SUCCESS_PARTIAL_CONTENT)) { + && !response.getStatus().equals(Status.SUCCESS_RESET_CONTENT)) { // Make sure that an InputRepresentation will not be instantiated // while the stream is closed. final InputStream stream = getUnClosedResponseEntityStream(getResponseEntityStream(size)); diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpClientConverter.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpClientConverter.java index da99d022c6..9002783781 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpClientConverter.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpClientConverter.java @@ -441,10 +441,6 @@ public void commit(HttpClientCall httpCall, Request request, Status.SUCCESS_RESET_CONTENT)) { response.getEntity().release(); response.setEntity(null); - } else if (response.getStatus().equals( - Status.SUCCESS_PARTIAL_CONTENT)) { - response.getEntity().release(); - response.setEntity(null); } else if (response.getStatus().equals( Status.REDIRECTION_NOT_MODIFIED)) { response.getEntity().release(); diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerConverter.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerConverter.java index c9a055133c..b378062fd1 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerConverter.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpServerConverter.java @@ -152,7 +152,6 @@ public static void addEntityHeaders(Representation entity, HttpServerCall.formatContentDisposition(entity .getDownloadName())); } - // TODO manage comparison with the requested ranges if (entity.getRange() != null) { try { responseHeaders.add(HttpConstants.HEADER_CONTENT_RANGE, @@ -346,17 +345,6 @@ public void commit(HttpResponse response) { .getResourceRef() + "."); response.setEntity(null); } - } else if (response.getStatus().equals( - Status.SUCCESS_PARTIAL_CONTENT)) { - if (response.getEntity() != null) { - getLogger() - .warning( - "Responses with a 206 (Partial content) status aren't supported yet. Ignoring the entity for resource \"" - + response.getRequest() - .getResourceRef() + "."); - response.setEntity(null); - - } } else if (response.getStatus().equals( Status.REDIRECTION_NOT_MODIFIED)) { addEntityHeaders(response); diff --git a/modules/org.restlet.test/src/org/restlet/test/RangeTestCase.java b/modules/org.restlet.test/src/org/restlet/test/RangeTestCase.java index 65e05f3470..84d43ee342 100644 --- a/modules/org.restlet.test/src/org/restlet/test/RangeTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/RangeTestCase.java @@ -208,27 +208,27 @@ public void testGet() throws IOException { request = new Request(Method.GET, "http://localhost:8182/testGet"); request.setRanges(Arrays.asList(new Range(0, 10))); response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("1234567890", response.getEntity().getText()); request.setRanges(Arrays.asList(new Range(Range.INDEX_FIRST, 2))); response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("12", response.getEntity().getText()); request.setRanges(Arrays.asList(new Range(2, 2))); response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("34", response.getEntity().getText()); request.setRanges(Arrays.asList(new Range(2, 7))); response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("3456789", response.getEntity().getText()); request.setRanges(Arrays.asList(new Range(Range.INDEX_LAST, 7))); response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("4567890", response.getEntity().getText()); } @@ -276,7 +276,7 @@ public void testPut() throws IOException { assertEquals(Status.SUCCESS_OK, response.getStatus()); request.setMethod(Method.GET); response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("0000000000", response.getEntity().getText()); // Partial PUT on a file, simple range @@ -312,7 +312,7 @@ public void testPut() throws IOException { assertEquals(Status.SUCCESS_OK, response.getStatus()); request.setMethod(Method.GET); response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("888", response.getEntity().getText()); // Partial PUT on a file, the provided representation will be padded @@ -331,7 +331,7 @@ public void testPut() throws IOException { "http://localhost:8182/testPut/essai.txt"); request.setRanges(Arrays.asList(new Range(3, Range.SIZE_MAX))); response = client.handle(request); - assertEquals(Status.SUCCESS_OK, response.getStatus()); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); assertEquals("20000998", response.getEntity().getText()); deleteDir(testDir);
75b81dcbd26a11d5b370ea5bdf102c2d62ebd0c3
drools
Fix OutOfBoundException on- MemoryFileSystem.existsFile("")--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFileSystem.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFileSystem.java index 5be94a3ab0f..1f81319f79a 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFileSystem.java +++ b/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFileSystem.java @@ -168,13 +168,16 @@ public boolean existsFolder(MemoryFolder folder) { public boolean existsFolder(String path) { if (path == null) { - throw new NullPointerException("Path can not be null!"); + throw new NullPointerException("Folder path can not be null!"); } - return folders.get( path.length() > 0 ? MemoryFolder.trimLeadingAndTrailing( path ) : path ) != null; + return folders.get(MemoryFolder.trimLeadingAndTrailing(path)) != null; } public boolean existsFile(String path) { - return fileContents.containsKey( MemoryFolder.trimLeadingAndTrailing( path ) ); + if (path == null) { + throw new NullPointerException("File path can not be null!"); + } + return fileContents.containsKey(MemoryFolder.trimLeadingAndTrailing(path)); } public void createFolder(MemoryFolder folder) { diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFolder.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFolder.java index f22294b6868..e5f48df9295 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFolder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFolder.java @@ -98,13 +98,14 @@ public Folder getParent() { } } - - return pFolder; } public static String trimLeadingAndTrailing(String p) { + if (p.isEmpty()) { + return p; + } while ( p.charAt( 0 ) == '/') { p = p.substring( 1 ); } diff --git a/drools-compiler/src/test/java/org/drools/compiler/kproject/memory/MemoryFolderTest.java b/drools-compiler/src/test/java/org/drools/compiler/kproject/memory/MemoryFolderTest.java index 8ef26dfa06f..1da5a39e63a 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/kproject/memory/MemoryFolderTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/kproject/memory/MemoryFolderTest.java @@ -191,4 +191,12 @@ public void testFolderRemoval() throws IOException { assertFalse( fs.getFile( "src/main/resources/org/domain/MyClass4.java" ).exists() ); } + @Test + public void trimLeadingAndTrailing() { + assertEquals("", MemoryFolder.trimLeadingAndTrailing("")); + assertEquals("src/main", MemoryFolder.trimLeadingAndTrailing("/src/main")); + assertEquals("src/main", MemoryFolder.trimLeadingAndTrailing("src/main/")); + assertEquals("src/main", MemoryFolder.trimLeadingAndTrailing("/src/main/")); + } + }
4f0dca67c29eda2ef5894a7e39b8f340fb423889
orientdb
Fix by Andrey to get working test cases even on- Linux (Windows seems to eat anything)--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/test/java/com/orientechnologies/orient/core/index/OPropertyIndexDefinitionTest.java b/core/src/test/java/com/orientechnologies/orient/core/index/OPropertyIndexDefinitionTest.java index d31579a4cc6..aeec76304bc 100644 --- a/core/src/test/java/com/orientechnologies/orient/core/index/OPropertyIndexDefinitionTest.java +++ b/core/src/test/java/com/orientechnologies/orient/core/index/OPropertyIndexDefinitionTest.java @@ -89,7 +89,7 @@ public void testEmptyIndexReload() { propertyIndex = new OPropertyIndexDefinition("tesClass", "fOne", OType.INTEGER); final ODocument docToStore = propertyIndex.toStream(); - docToStore.save(); + database.save(docToStore); final ODocument docToLoad = database.load(docToStore.getIdentity());
2947b932624e4931333c08cfd9c111628bbd25e9
orientdb
Fixed some errors in remote calls.--
c
https://github.com/orientechnologies/orientdb
diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java index 2cd9c5df888..b75e598d20d 100644 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java +++ b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java @@ -49,7 +49,6 @@ import com.orientechnologies.orient.core.serialization.OSerializableStream; import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyRuntime; import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyStreamable; -import com.orientechnologies.orient.core.sql.query.OSQLQuery; import com.orientechnologies.orient.core.storage.OCluster; import com.orientechnologies.orient.core.storage.ORawBuffer; import com.orientechnologies.orient.core.storage.OStorage; @@ -359,7 +358,7 @@ public Object command(final OCommandRequestText iCommand) { OStorageRemoteThreadLocal.INSTANCE.set(Boolean.TRUE); try { - final OSQLQuery<?> aquery = (OSQLQuery<?>) iCommand; + final OCommandRequestText aquery = (OCommandRequestText) iCommand; final boolean asynch = iCommand instanceof OCommandRequestAsynch; @@ -514,10 +513,11 @@ public int addCluster(final String iClusterName, final String iClusterType, fina if (OClusterLocal.TYPE.equals(iClusterType)) { // FIEL PATH + START SIZE - network.writeString((String) iArguments[0]).writeInt((Integer) iArguments[1]); + network.writeString(iArguments.length > 0 ? (String) iArguments[0] : "").writeInt( + iArguments.length > 0 ? (Integer) iArguments[1] : -1); } else { // PHY CLUSTER ID - network.writeInt((Integer) iArguments[0]); + network.writeInt(iArguments.length > 0 ? (Integer) iArguments[0] : -1); } network.flush(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java index da68922264a..b7f1b7b6e31 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java @@ -30,5 +30,7 @@ public interface OCommandRequestInternal extends OCommandRequest, OSerializableS public OCommandRequestInternal setDatabase(final ODatabaseRecord<?> iDatabase); + public OCommandResultListener getResultListener(); + public void setResultListener(OCommandResultListener iListener); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java index 8dd54bcedbb..0c11593b387 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java @@ -101,22 +101,22 @@ public <DB extends ODatabase> DB open(final String iUserName, final String iUser recordFormat = DEF_RECORD_FORMAT; dictionary.load(); - if (getStorage() instanceof OStorageLocal) { - user = getMetadata().getSecurity().getUser(iUserName); - if (user == null) - throw new OSecurityAccessException(this.getName(), "User '" + iUserName + "' was not found in database: " + getName()); + user = getMetadata().getSecurity().getUser(iUserName); + if (user == null) + throw new OSecurityAccessException(this.getName(), "User '" + iUserName + "' was not found in database: " + getName()); - if (user.getAccountStatus() != STATUSES.ACTIVE) - throw new OSecurityAccessException(this.getName(), "User '" + iUserName + "' is not active"); + if (user.getAccountStatus() != STATUSES.ACTIVE) + throw new OSecurityAccessException(this.getName(), "User '" + iUserName + "' is not active"); + if (getStorage() instanceof OStorageLocal) { if (!user.checkPassword(iUserPassword)) { // WAIT A BIT TO AVOID BRUTE FORCE Thread.sleep(200); throw new OSecurityAccessException(this.getName(), "Password not valid for user: " + iUserName); } - - checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ); } + + checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ); } catch (Exception e) { close(); throw new ODatabaseException("Can't open database", e); diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java index 567b9385f88..30430000941 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java @@ -282,6 +282,8 @@ else if (((ODictionaryLocal<?>) connection.database.getDictionary()).getTree().g underlyingDatabase.delete(channel.readShort(), channel.readLong(), channel.readInt()); sendOk(); + + channel.writeByte((byte) '1'); break; case OChannelBinaryProtocol.COUNT: { diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLUpdateTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLUpdateTest.java index 90db9b1c381..e810cd4d256 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLUpdateTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLUpdateTest.java @@ -37,9 +37,10 @@ public void updateWithWhereOperator() { database.open("admin", "admin"); Integer records = (Integer) database.command( - new OCommandSQL("update Profile set salary = 120.30, location = -3:2, salary_cloned = salary where surname = 'Obama'")).execute(); + new OCommandSQL("update Profile set salary = 120.30, location = -3:2, salary_cloned = salary where surname = 'Obama'")) + .execute(); - Assert.assertTrue(records == 3); + Assert.assertEquals(records.intValue(), 3); database.close(); } diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml new file mode 100644 index 00000000000..fbc3ac6d052 --- /dev/null +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml @@ -0,0 +1,119 @@ +<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd"> +<suite name="Test Suite Example" verbose="1" parallel="false"> + <!-- <parameter name="url" value="remote:localhost/demo" /> --> + + <!-- --> + <parameter name="url" + value="local:../../releases/0.9.19/db/databases/demo/demo" /> + + + <test name="Setup"> + <parameter name="path" value="../../releases/0.9.19/db/databases/demo" /> + <classes> + <class + name="com.orientechnologies.orient.test.database.base.DeleteDirectory" /> + </classes> + </test> + + <test name="DbCreation"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.DbCreationTest" /> + </classes> + </test> + <test name="Schema"> + <classes> + <class name="com.orientechnologies.orient.test.database.auto.SchemaTest" /> + </classes> + </test> + <test name="Security"> + <classes> + <class name="com.orientechnologies.orient.test.database.auto.SecurityTest" /> + </classes> + </test> + <test name="Hook"> + <classes> + <class name="com.orientechnologies.orient.test.database.auto.HookTest" /> + </classes> + </test> + <test name="Population"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.CRUDFlatPhysicalTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.CRUDColumnPhysicalTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.CRUDDocumentLogicalTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.CRUDDocumentPhysicalTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.CRUDObjectPhysicalTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.CRUDObjectInheritanceTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.CRUDFlatPhysicalTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.CRUDDocumentValidationTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.ObjectTreeTest" /> + </classes> + </test> + <test name="Tx"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.TransactionAtomicTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.TransactionOptimisticTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.TransactionConsistencyTest" /> + </classes> + </test> + <test name="Index"> + <classes> + <class name="com.orientechnologies.orient.test.database.auto.IndexTest" /> + </classes> + </test> + <test name="Dictionary"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.DictionaryTest" /> + </classes> + </test> + <test name="Query"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.NativeQueryTest" /> + <class + name="com.orientechnologies.orient.test.database.auto.WrongQueryTest" /> + </classes> + </test> + <test name="sql-select"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.SQLSelectTest" /> + </classes> + </test> + <test name="sql-insert"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.SQLInsertTest" /> + </classes> + </test> + <test name="sql-update"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.SQLUpdateTest" /> + </classes> + </test> + <test name="sql-delete"> + <classes> + <class + name="com.orientechnologies.orient.test.database.auto.SQLDeleteTest" /> + </classes> + </test> + <test name="End"> + <classes> + <class name="com.orientechnologies.orient.test.database.auto.DbClosedTest" /> + </classes> + </test> +</suite> \ No newline at end of file diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/remote-test-db-from-scratch.xml b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/remote-test-db-from-scratch.xml index b57ffa92a58..71181d08560 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/remote-test-db-from-scratch.xml +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/remote-test-db-from-scratch.xml @@ -1,12 +1,13 @@ <!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd"> <suite name="Test Suite Example" verbose="1" parallel="false"> - <!-- + <!-- --> <parameter name="url" value="remote:localhost/demo" /> - --> - <!-- --> - <parameter name="url" value="local:../../releases/0.9.19/db/databases/demo/demo"/> + <!-- + <parameter name="url" value="local:../../releases/0.9.19/db/databases/demo/demo"/> + --> + <test name="Setup"> <parameter name="path" value="../../releases/0.9.19/db/databases/demo"/> <classes>
55ff4ae941e12c170a5e49801e599827e6461e27
kotlin
Abstract Lazy test for gianostics--
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java b/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java index 58a0b7bbe6ab8..77b940858ad37 100644 --- a/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java +++ b/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java @@ -17,7 +17,6 @@ package org.jetbrains.jet.checkers; import com.google.common.base.Predicates; -import com.google.common.collect.Lists; import com.intellij.psi.PsiFile; import org.jetbrains.jet.lang.BuiltinsScopeExtensionMode; import org.jetbrains.jet.lang.psi.JetFile; @@ -39,12 +38,7 @@ public abstract class AbstractDiagnosticsTestWithEagerResolve extends AbstractJetDiagnosticsTest { protected void analyzeAndCheck(String expectedText, List<TestFile> testFiles) { - List<JetFile> jetFiles = Lists.newArrayList(); - for (TestFile testFile : testFiles) { - if (testFile.getJetFile() != null) { - jetFiles.add(testFile.getJetFile()); - } - } + List<JetFile> jetFiles = getJetFiles(testFiles); BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( getProject(), jetFiles, Collections.<AnalyzerScriptParameter>emptyList(), diff --git a/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java b/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java index 4498b7883033a..224b863d6a397 100644 --- a/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java +++ b/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java @@ -91,6 +91,16 @@ public TestFile create(String fileName, String text) { protected abstract void analyzeAndCheck(String expectedText, List<TestFile> files); + protected static List<JetFile> getJetFiles(List<TestFile> testFiles) { + List<JetFile> jetFiles = Lists.newArrayList(); + for (TestFile testFile : testFiles) { + if (testFile.getJetFile() != null) { + jetFiles.add(testFile.getJetFile()); + } + } + return jetFiles; + } + protected class TestFile { private final List<CheckerTestUtil.DiagnosedRange> diagnosedRanges = Lists.newArrayList(); private final String expectedText; diff --git a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java index fec99cb68aaf7..72a492a53e876 100644 --- a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java +++ b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java @@ -16,10 +16,15 @@ package org.jetbrains.jet.lang.resolve.lazy; +import com.google.common.base.Predicates; import junit.framework.TestCase; import org.jetbrains.jet.ConfigurationKind; import org.jetbrains.jet.checkers.AbstractJetDiagnosticsTest; import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; +import org.jetbrains.jet.jvm.compiler.NamespaceComparator; +import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; +import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; +import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.test.generator.SimpleTestClassModel; import org.jetbrains.jet.test.generator.TestGenerator; @@ -39,7 +44,11 @@ protected JetCoreEnvironment createEnvironment() { @Override protected void analyzeAndCheck(String expectedText, List<TestFile> files) { + List<JetFile> jetFiles = getJetFiles(files); + ModuleDescriptor lazyModule = LazyResolveTestUtil.resolveLazily(jetFiles, getEnvironment()); + ModuleDescriptor eagerModule = LazyResolveTestUtil.resolveEagerly(jetFiles, getEnvironment()); + NamespaceComparator.assertNamespacesEqual(eagerModule.getRootNamespace(), lazyModule.getRootNamespace(), false, Predicates.<NamespaceDescriptor>alwaysTrue()); } public static void main(String[] args) throws IOException {
a1bf55c5541b45552708fa76b04e24419604825b
camel
Minor cleanup--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@712728 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java index f88b5bd99ee8c..120a7d63eba3e 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java @@ -38,7 +38,6 @@ public class DefaultUnitOfWork implements UnitOfWork, Service { private String id; private List<Synchronization> synchronizations; private List<AsyncCallback> asyncCallbacks; - private CountDownLatch latch; public DefaultUnitOfWork() { } diff --git a/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java b/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java index db5319995fc07..2d8d5760579af 100644 --- a/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java @@ -150,8 +150,15 @@ public ObjectName getObjectName(ManagedRoute mbean) throws MalformedObjectNameEx public ObjectName getObjectName(RouteContext routeContext, ProcessorType processor) throws MalformedObjectNameException { Endpoint<? extends Exchange> ep = routeContext.getEndpoint(); - String ctxid = ep != null ? getContextId(ep.getCamelContext()) : VALUE_UNKNOWN; - String cid = ObjectName.quote(ep.getEndpointUri()); + String ctxid; + String cid; + if (ep != null) { + ctxid = getContextId(ep.getCamelContext()); + cid = ObjectName.quote(ep.getEndpointUri()); + } else { + ctxid = VALUE_UNKNOWN; + cid = null; + } //String id = VALUE_UNKNOWN.equals(cid) ? ObjectName.quote(getEndpointId(ep) : "[" + cid + "]" + ObjectName.quote(getEndpointId(ep); String nodeId = processor.idOrCreate(); diff --git a/camel-core/src/main/java/org/apache/camel/model/RouteType.java b/camel-core/src/main/java/org/apache/camel/model/RouteType.java index 04307bb4712a1..ec3901c1e1469 100644 --- a/camel-core/src/main/java/org/apache/camel/model/RouteType.java +++ b/camel-core/src/main/java/org/apache/camel/model/RouteType.java @@ -78,11 +78,9 @@ public String toString() { public void addRoutes(CamelContext context, Collection<Route> routes) throws Exception { setCamelContext(context); - if (context instanceof CamelContext) { - ErrorHandlerBuilder handler = context.getErrorHandlerBuilder(); - if (handler != null) { - setErrorHandlerBuilderIfNull(handler); - } + ErrorHandlerBuilder handler = context.getErrorHandlerBuilder(); + if (handler != null) { + setErrorHandlerBuilderIfNull(handler); } for (FromType fromType : inputs) { diff --git a/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java b/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java index 83342f78bfe44..a076b572596e8 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java @@ -120,8 +120,7 @@ protected void logException(Exchange exchange, Throwable throwable) { * Returns true if the given exchange should be logged in the trace list */ protected boolean shouldLogExchange(Exchange exchange) { - return (tracer == null || tracer.isEnabled()) - && (tracer.getTraceFilter() == null || tracer.getTraceFilter().matches(exchange)); + return tracer.isEnabled() && (tracer.getTraceFilter() == null || tracer.getTraceFilter().matches(exchange)); } /**
c95eca10efeaa160791b351cd3786418b35f416c
kotlin
Avoid wrapping AssertionError over and over- again, see KT-7501--
c
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingVisitorDispatcher.java b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingVisitorDispatcher.java index 8501ab1904efe..31dc99541657e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingVisitorDispatcher.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingVisitorDispatcher.java @@ -182,18 +182,30 @@ private JetTypeInfo getTypeInfo(@NotNull JetExpression expression, ExpressionTyp } catch (Throwable e) { context.trace.report(Errors.EXCEPTION_FROM_ANALYZER.on(expression, e)); - LOG.error( - "Exception while analyzing expression at " + DiagnosticUtils.atLocation(expression) + ":\n" + expression.getText() + "\n", - e - ); + logOrThrowException(expression, e); return JetTypeInfo.create( ErrorUtils.createErrorType(e.getClass().getSimpleName() + " from analyzer"), context.dataFlowInfo ); } - } + } -////////////////////////////////////////////////////////////////////////////////////////////// + private static void logOrThrowException(@NotNull JetExpression expression, Throwable e) { + try { + // This trows AssertionError in CLI and reports the error in the IDE + LOG.error( + "Exception while analyzing expression at " + DiagnosticUtils.atLocation(expression) + ":\n" + expression.getText() + "\n", + e + ); + } + catch (AssertionError errorFromLogger) { + // If we ended up here, we are in CLI, and the initial exception needs to be rethrown, + // simply throwing AssertionError causes its being wrapped over and over again + throw new KotlinFrontEndException(errorFromLogger.getMessage(), e); + } + } + + ////////////////////////////////////////////////////////////////////////////////////////////// @Override public JetTypeInfo visitFunctionLiteralExpression(@NotNull JetFunctionLiteralExpression expression, ExpressionTypingContext data) {
6858749cfd27f2975ce560e84b29e95d16eb88d2
camel
MailConsumer and MailProducer now use the- endpoint reference from its super class and doesn'n manager its own instance- variable--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1054815 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java index 5bd3677d1f1d0..120dcf1a7634b 100644 --- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java +++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java @@ -18,6 +18,7 @@ import java.util.LinkedList; import java.util.Queue; + import javax.mail.Flags; import javax.mail.Folder; import javax.mail.FolderNotFoundException; @@ -49,7 +50,6 @@ public class MailConsumer extends ScheduledPollConsumer implements BatchConsumer public static final long DEFAULT_CONSUMER_DELAY = 60 * 1000L; private static final transient Log LOG = LogFactory.getLog(MailConsumer.class); - private final MailEndpoint endpoint; private final JavaMailSenderImpl sender; private Folder folder; private Store store; @@ -59,7 +59,6 @@ public class MailConsumer extends ScheduledPollConsumer implements BatchConsumer public MailConsumer(MailEndpoint endpoint, Processor processor, JavaMailSenderImpl sender) { super(endpoint, processor); - this.endpoint = endpoint; this.sender = sender; } @@ -89,14 +88,14 @@ protected void poll() throws Exception { if (store == null || folder == null) { throw new IllegalStateException("MailConsumer did not connect properly to the MailStore: " - + endpoint.getConfiguration().getMailStoreLogInformation()); + + getEndpoint().getConfiguration().getMailStoreLogInformation()); } if (LOG.isDebugEnabled()) { - LOG.debug("Polling mailfolder: " + endpoint.getConfiguration().getMailStoreLogInformation()); + LOG.debug("Polling mailfolder: " + getEndpoint().getConfiguration().getMailStoreLogInformation()); } - if (endpoint.getConfiguration().getFetchSize() == 0) { + if (getEndpoint().getConfiguration().getFetchSize() == 0) { LOG.warn("Fetch size is 0 meaning the configuration is set to poll no new messages at all. Camel will skip this poll."); return; } @@ -112,7 +111,7 @@ protected void poll() throws Exception { Message[] messages; // should we process all messages or only unseen messages - if (endpoint.getConfiguration().isUnseen()) { + if (getEndpoint().getConfiguration().isUnseen()) { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } else { messages = folder.getMessages(); @@ -226,7 +225,7 @@ public boolean isBatchAllowed() { protected Queue<Exchange> createExchanges(Message[] messages) throws MessagingException { Queue<Exchange> answer = new LinkedList<Exchange>(); - int fetchSize = endpoint.getConfiguration().getFetchSize(); + int fetchSize = getEndpoint().getConfiguration().getFetchSize(); int count = fetchSize == -1 ? messages.length : Math.min(fetchSize, messages.length); if (LOG.isDebugEnabled()) { @@ -236,7 +235,7 @@ protected Queue<Exchange> createExchanges(Message[] messages) throws MessagingEx for (int i = 0; i < count; i++) { Message message = messages[i]; if (!message.getFlags().contains(Flags.Flag.DELETED)) { - Exchange exchange = endpoint.createExchange(message); + Exchange exchange = getEndpoint().createExchange(message); answer.add(exchange); } else { if (LOG.isDebugEnabled()) { @@ -267,7 +266,7 @@ protected void processExchange(Exchange exchange) throws Exception { */ protected void processCommit(Message mail, Exchange exchange) { try { - if (endpoint.getConfiguration().isDelete()) { + if (getEndpoint().getConfiguration().isDelete()) { LOG.debug("Exchange processed, so flagging message as DELETED"); mail.setFlag(Flags.Flag.DELETED, true); } else { @@ -296,7 +295,7 @@ protected void processRollback(Message mail, Exchange exchange) { } private void ensureIsConnected() throws MessagingException { - MailConfiguration config = endpoint.getConfiguration(); + MailConfiguration config = getEndpoint().getConfiguration(); boolean connected = false; try { @@ -305,7 +304,7 @@ private void ensureIsConnected() throws MessagingException { } } catch (Exception e) { LOG.debug("Exception while testing for is connected to MailStore: " - + endpoint.getConfiguration().getMailStoreLogInformation() + + getEndpoint().getConfiguration().getMailStoreLogInformation() + ". Caused by: " + e.getMessage(), e); } @@ -315,7 +314,7 @@ private void ensureIsConnected() throws MessagingException { folder = null; if (LOG.isDebugEnabled()) { - LOG.debug("Connecting to MailStore: " + endpoint.getConfiguration().getMailStoreLogInformation()); + LOG.debug("Connecting to MailStore: " + getEndpoint().getConfiguration().getMailStoreLogInformation()); } store = sender.getSession().getStore(config.getProtocol()); store.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); @@ -332,4 +331,8 @@ private void ensureIsConnected() throws MessagingException { } } -} + @Override + public MailEndpoint getEndpoint() { + return (MailEndpoint) super.getEndpoint(); + } +} \ No newline at end of file diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java index 2a63ca97c7d3a..0be21d63e6237 100644 --- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java +++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java @@ -33,23 +33,26 @@ */ public class MailProducer extends DefaultProducer { private static final transient Log LOG = LogFactory.getLog(MailProducer.class); - private final MailEndpoint endpoint; private final JavaMailSender sender; public MailProducer(MailEndpoint endpoint, JavaMailSender sender) { super(endpoint); - this.endpoint = endpoint; this.sender = sender; } public void process(final Exchange exchange) { sender.send(new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { - endpoint.getBinding().populateMailMessage(endpoint, mimeMessage, exchange); + getEndpoint().getBinding().populateMailMessage(getEndpoint(), mimeMessage, exchange); if (LOG.isDebugEnabled()) { LOG.debug("Sending MimeMessage: " + MailUtils.dumpMessage(mimeMessage)); } } }); } -} + + @Override + public MailEndpoint getEndpoint() { + return (MailEndpoint) super.getEndpoint(); + } +} \ No newline at end of file
9ac8731539e821afca215b685203ef82115e36f5
orientdb
Working to fix corrupted data in sockets--
c
https://github.com/orientechnologies/orientdb
diff --git a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java index ef8646b8b48..8d060267d50 100644 --- a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java +++ b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java @@ -21,6 +21,7 @@ import java.util.concurrent.locks.ReentrantLock; import com.orientechnologies.common.concur.OTimeoutException; +import com.orientechnologies.common.io.OIOException; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OContextConfiguration; import com.orientechnologies.orient.core.config.OGlobalConfiguration; @@ -32,7 +33,7 @@ * */ public class OChannelBinaryAsynch extends OChannelBinary { - private final ReentrantLock lockRead = new ReentrantLock(); + private final ReentrantLock lockRead = new ReentrantLock(true); private final ReentrantLock lockWrite = new ReentrantLock(); private boolean channelRead = false; private byte currentStatus; @@ -105,7 +106,8 @@ else if (!lockRead.tryLock(iTimeout, TimeUnit.MILLISECONDS)) maxUnreadResponses); // CALL THE SUPER-METHOD TO AVOID LOCKING AGAIN - super.clearInput(); + //super.clearInput(); + throw new OIOException("Timeout on reading response"); } lockRead.unlock(); @@ -116,14 +118,14 @@ else if (!lockRead.tryLock(iTimeout, TimeUnit.MILLISECONDS)) synchronized (this) { try { if (debug) - OLogManager.instance().debug(this, "Session %d is going to sleep...", currentSessionId); + OLogManager.instance().debug(this, "Session %d is going to sleep...", iRequesterId); wait(1000); final long now = System.currentTimeMillis(); if (debug) OLogManager.instance().debug(this, "Waked up: slept %dms, checking again from %s for session %d", (now - start), - socket.getLocalAddress(), currentSessionId); + socket.getLocalAddress(), iRequesterId); if (now - start >= 1000) unreadResponse++;
7d6c8991403107e6cf9d967466ead87ef58f3fbf
drools
JBRULES-3170 Compiler erroneously resolves the- package of declared classes with the same name as basic classes--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java index 5a11f46abc0..12461d4c24b 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java @@ -1467,7 +1467,22 @@ private void processTypeDeclarations(final PackageDescr packageDescr) { PackageRegistry pkgRegistry = null; for ( TypeDeclarationDescr typeDescr : packageDescr.getTypeDeclarations() ) { - int dotPos = typeDescr.getTypeName().lastIndexOf( '.' ); + + if ( isEmpty( typeDescr.getNamespace() ) ) { + for ( ImportDescr id : packageDescr.getImports() ) { + String imp = id.getTarget(); + if ( imp.endsWith( typeDescr.getTypeName() ) ) { + typeDescr.setNamespace( imp.substring( 0, + imp.lastIndexOf( '.' ) ) ); + } + } + } + String qName = typeDescr.getTypeName(); + if ( typeDescr.getNamespace() != null ) { + qName = typeDescr.getNamespace() + "." + qName; + } + + int dotPos = qName.lastIndexOf( '.' ); if ( dotPos >= 0 ) { // see if this overwrites an existing bean, which also could be a nested class. Class cls = null; @@ -1478,7 +1493,7 @@ private void processTypeDeclarations(final PackageDescr packageDescr) { } catch ( ClassNotFoundException e ) { } - String qualifiedClass = typeDescr.getTypeName(); + String qualifiedClass = qName; int lastIndex; while ( cls == null && (lastIndex = qualifiedClass.lastIndexOf( '.' )) != -1 ) { try { @@ -1499,34 +1514,15 @@ private void processTypeDeclarations(final PackageDescr packageDescr) { dotPos = cls.getName().lastIndexOf( '.' ); // reget dotPos, incase there were nested classes typeDescr.setTypeName( cls.getName().substring( dotPos + 1 ) ); } else { - typeDescr.setNamespace( typeDescr.getTypeName().substring( 0, + typeDescr.setNamespace( qName.substring( 0, dotPos ) ); - typeDescr.setTypeName( typeDescr.getTypeName().substring( dotPos + 1 ) ); + typeDescr.setTypeName( qName.substring( dotPos + 1 ) ); } } - if ( isEmpty( typeDescr.getNamespace() ) ) { - // check imports - try { - Class< ? > cls = defaultRegistry.getTypeResolver().resolveType( typeDescr.getTypeName() ); - typeDescr.setNamespace( ClassUtils.getPackage( cls ) ); - String name = cls.getName(); - dotPos = name.lastIndexOf( '.' ); - typeDescr.setTypeName( name.substring( dotPos + 1 ) ); - } catch ( ClassNotFoundException e ) { - // swallow, as this isn't a mistake, it just means the type declaration is intended for the default namespace - typeDescr.setNamespace( packageDescr.getNamespace() ); // set the default namespace - } - } if ( isEmpty( typeDescr.getNamespace() ) ) { - for ( ImportDescr id : packageDescr.getImports() ) { - String imp = id.getTarget(); - if ( imp.endsWith( typeDescr.getTypeName() ) ) { - typeDescr.setNamespace( imp.substring( 0, - imp.lastIndexOf( '.' ) ) ); - } - } + typeDescr.setNamespace( packageDescr.getNamespace() ); // set the default namespace } //identify superclass type and namespace @@ -1708,7 +1704,10 @@ private boolean isNovelClass(TypeDeclarationDescr typeDescr) { try { PackageRegistry reg = this.pkgRegistryMap.get( typeDescr.getNamespace() ); if ( reg != null ) { - Class< ? > resolvedType = reg.getTypeResolver().resolveType( typeDescr.getTypeName() ); + String availableName = typeDescr.getNamespace() != null + ? typeDescr.getNamespace() + "." + typeDescr.getTypeName() + : typeDescr.getTypeName(); + Class< ? > resolvedType = reg.getTypeResolver().resolveType( availableName ); if ( resolvedType != null && typeDescr.getFields().size() > 1 ) { this.results.add( new TypeDeclarationError( "Duplicate type definition. A class with the name '" + resolvedType.getName() + "' was found in the classpath while trying to " + "redefine the fields in the declare statement. Fields can only be defined for non-existing classes.", diff --git a/drools-compiler/src/test/java/org/drools/compiler/TypeDeclarationTest.java b/drools-compiler/src/test/java/org/drools/compiler/TypeDeclarationTest.java new file mode 100644 index 00000000000..7791953334d --- /dev/null +++ b/drools-compiler/src/test/java/org/drools/compiler/TypeDeclarationTest.java @@ -0,0 +1,31 @@ +package org.drools.compiler; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; + +import org.drools.builder.KnowledgeBuilder; +import org.drools.builder.KnowledgeBuilderFactory; +import org.drools.builder.ResourceType; +import org.drools.io.ResourceFactory; +import org.junit.Test; + +public class TypeDeclarationTest { + + @Test + public void testClassNameClashing() { + String str = ""; + str += "package org.drools \n" + + "declare Character \n" + + " name : String \n" + + "end \n"; + + KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); + + kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), + ResourceType.DRL ); + + if ( kbuilder.hasErrors() ) { + fail( kbuilder.getErrors().toString() ); + } + } +}
1a880076880a794016e2eeadea4f7f67c38e68ce
spring-framework
Improve documentation of SpringFactoriesLoader--
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java b/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java index d6eeabf7e90e..d47724994c7e 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java @@ -36,15 +36,17 @@ /** * General purpose factory loading mechanism for internal use within the framework. * - * <p>The {@code SpringFactoriesLoader} loads and instantiates factories of a given type - * from "META-INF/spring.factories" files. The file should be in {@link Properties} format, - * where the key is the fully qualified interface or abstract class name, and the value - * is a comma-separated list of implementation class names. For instance: + * <p>{@code SpringFactoriesLoader} {@linkplain #loadFactories loads} and instantiates + * factories of a given type from {@value #FACTORIES_RESOURCE_LOCATION} files which + * may be present in multiple JAR files in the classpath. The {@code spring.factories} + * file must be in {@link Properties} format, where the key is the fully qualified + * name of the interface or abstract class, and the value is a comma-separated list of + * implementation class names. For example: * * <pre class="code">example.MyService=example.MyServiceImpl1,example.MyServiceImpl2</pre> * - * where {@code MyService} is the name of the interface, and {@code MyServiceImpl1} and - * {@code MyServiceImpl2} are the two implementations. + * where {@code example.MyService} is the name of the interface, and {@code MyServiceImpl1} + * and {@code MyServiceImpl2} are two implementations. * * @author Arjen Poutsma * @author Juergen Hoeller @@ -53,18 +55,26 @@ */ public abstract class SpringFactoriesLoader { - /** The location to look for the factories. Can be present in multiple JAR files. */ - public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"; - private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class); + /** + * The location to look for factories. + * <p>Can be present in multiple JAR files. + */ + public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"; + /** - * Load the factory implementations of the given type from the default location, - * using the given class loader. - * <p>The returned factories are ordered in accordance with the {@link AnnotationAwareOrderComparator}. + * Load and instantiate the factory implementations of the given type from + * {@value #FACTORIES_RESOURCE_LOCATION}, using the given class loader. + * <p>The returned factories are sorted in accordance with the {@link AnnotationAwareOrderComparator}. + * <p>If a custom instantiation strategy is required, use {@link #loadFactoryNames} + * to obtain all registered factory names. * @param factoryClass the interface or abstract class representing the factory * @param classLoader the ClassLoader to use for loading (can be {@code null} to use the default) + * @see #loadFactoryNames + * @throws IllegalArgumentException if any factory implementation class cannot + * be loaded or if an error occurs while instantiating any factory */ public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) { Assert.notNull(factoryClass, "'factoryClass' must not be null"); @@ -84,6 +94,16 @@ public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader class return result; } + /** + * Load the fully qualified class names of factory implementations of the + * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given + * class loader. + * @param factoryClass the interface or abstract class representing the factory + * @param classLoader the ClassLoader to use for loading resources; can be + * {@code null} to use the default + * @see #loadFactories + * @throws IllegalArgumentException if an error occurs while loading factory names + */ public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) { String factoryClassName = factoryClass.getName(); try {
24d4d933f72c4c3c3f2f34b1de73575c65913bd2
hadoop
YARN-3100. Made YARN authorization pluggable.- Contributed by Jian He.--(cherry picked from commit 23bf6c72071782e3fd5a628e21495d6b974c7a9e)-
a
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 773184034f2a1..a5dfe24ff26bf 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -224,6 +224,8 @@ Release 2.7.0 - UNRELEASED YARN-3155. Refactor the exception handling code for TimelineClientImpl's retryOn method (Li Lu via wangda) + YARN-3100. Made YARN authorization pluggable. (Jian He via zjshen) + OPTIMIZATIONS YARN-2990. FairScheduler's delay-scheduling always waits for node-local and diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java index a2a252983544f..d50a7009f1e90 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java @@ -435,6 +435,8 @@ private static void addDeprecatedKeys() { public static final String DEFAULT_RM_CONFIGURATION_PROVIDER_CLASS = "org.apache.hadoop.yarn.LocalConfigurationProvider"; + public static final String YARN_AUTHORIZATION_PROVIDER = YARN_PREFIX + + "authorization-provider"; private static final List<String> RM_SERVICES_ADDRESS_CONF_KEYS_HTTP = Collections.unmodifiableList(Arrays.asList( RM_ADDRESS, diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/AccessType.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/AccessType.java new file mode 100644 index 0000000000000..32459b9688bd5 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/AccessType.java @@ -0,0 +1,33 @@ +/** +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.apache.hadoop.yarn.security; + +import org.apache.hadoop.classification.InterfaceAudience.Private; +import org.apache.hadoop.classification.InterfaceStability.Unstable; + +/** + * Access types for a queue or an application. + */ +@Private +@Unstable +public enum AccessType { + // queue + SUBMIT_APP, + ADMINISTER_QUEUE, +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/AdminACLsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/AdminACLsManager.java index 70c1a6e10c5e6..a386123e6a272 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/AdminACLsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/AdminACLsManager.java @@ -98,15 +98,6 @@ public boolean areACLsEnabled() { return aclsEnabled; } - /** - * Returns the internal structure used to maintain administrator ACLs - * - * @return Structure used to maintain administrator access - */ - public AccessControlList getAdminAcl() { - return adminAcl; - } - /** * Returns whether the specified user/group is an administrator * @@ -117,26 +108,4 @@ public AccessControlList getAdminAcl() { public boolean isAdmin(UserGroupInformation callerUGI) { return adminAcl.isUserAllowed(callerUGI); } - - /** - * Returns whether the specified user/group has administrator access - * - * @param callerUGI user/group to to check - * @return <tt>true</tt> if the UserGroupInformation specified - * is a member of the access control list for administrators - * and ACLs are enabled for this cluster - * - * @see #getAdminAcl - * @see #areACLsEnabled - */ - public boolean checkAccess(UserGroupInformation callerUGI) { - - // Any user may perform this operation if authorization is not enabled - if (!areACLsEnabled()) { - return true; - } - - // Administrators may perform any operation - return isAdmin(callerUGI); - } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/ConfiguredYarnAuthorizer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/ConfiguredYarnAuthorizer.java new file mode 100644 index 0000000000000..90ba77a2bbdbe --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/ConfiguredYarnAuthorizer.java @@ -0,0 +1,97 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.security; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.hadoop.classification.InterfaceAudience.Private; +import org.apache.hadoop.classification.InterfaceStability.Unstable; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.security.authorize.AccessControlList; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.security.PrivilegedEntity.EntityType; + +/** + * A YarnAuthorizationProvider implementation based on configuration files. + * + */ +@Private +@Unstable +public class ConfiguredYarnAuthorizer extends YarnAuthorizationProvider { + + private final ConcurrentMap<PrivilegedEntity, Map<AccessType, AccessControlList>> allAcls = + new ConcurrentHashMap<>(); + private volatile AccessControlList adminAcl = null; + + + @Override + public void init(Configuration conf) { + adminAcl = + new AccessControlList(conf.get(YarnConfiguration.YARN_ADMIN_ACL, + YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)); + } + + @Override + public void setPermission(PrivilegedEntity target, + Map<AccessType, AccessControlList> acls, UserGroupInformation ugi) { + allAcls.put(target, acls); + } + + @Override + public boolean checkPermission(AccessType accessType, + PrivilegedEntity target, UserGroupInformation user) { + boolean ret = false; + Map<AccessType, AccessControlList> acls = allAcls.get(target); + if (acls != null) { + AccessControlList list = acls.get(accessType); + if (list != null) { + ret = list.isUserAllowed(user); + } + } + + // recursively look up the queue to see if parent queue has the permission. + if (target.getType() == EntityType.QUEUE && !ret) { + String queueName = target.getName(); + if (!queueName.contains(".")) { + return ret; + } + String parentQueueName = queueName.substring(0, queueName.lastIndexOf(".")); + return checkPermission(accessType, new PrivilegedEntity(target.getType(), + parentQueueName), user); + } + return ret; + } + + @Override + public void setAdmins(AccessControlList acls, UserGroupInformation ugi) { + adminAcl = acls; + } + + @Override + public boolean isAdmin(UserGroupInformation ugi) { + return adminAcl.isUserAllowed(ugi); + } + + public AccessControlList getAdminAcls() { + return this.adminAcl; + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/PrivilegedEntity.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/PrivilegedEntity.java new file mode 100644 index 0000000000000..580bdf490a3f2 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/PrivilegedEntity.java @@ -0,0 +1,83 @@ +/** +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.apache.hadoop.yarn.security; + +import org.apache.hadoop.classification.InterfaceAudience.Private; +import org.apache.hadoop.classification.InterfaceStability.Unstable; +import org.apache.hadoop.yarn.api.records.ApplicationAccessType; +import org.apache.hadoop.yarn.api.records.QueueACL; + +/** + * An entity in YARN that can be guarded with ACLs. The entity could be an + * application or a queue etc. An application entity has access types defined in + * {@link ApplicationAccessType}, a queue entity has access types defined in + * {@link QueueACL}. + */ +@Private +@Unstable +public class PrivilegedEntity { + + public enum EntityType { + QUEUE + } + + EntityType type; + String name; + + public PrivilegedEntity(EntityType type, String name) { + this.type = type; + this.name = name; + } + + public EntityType getType() { + return type; + } + + public String getName() { + return name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PrivilegedEntity other = (PrivilegedEntity) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (type != other.type) + return false; + return true; + } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/YarnAuthorizationProvider.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/YarnAuthorizationProvider.java new file mode 100644 index 0000000000000..7b2c35cafdb1d --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/YarnAuthorizationProvider.java @@ -0,0 +1,112 @@ +/** +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.apache.hadoop.yarn.security; + +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.classification.InterfaceAudience.Private; +import org.apache.hadoop.classification.InterfaceStability.Unstable; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.security.authorize.AccessControlList; +import org.apache.hadoop.util.ReflectionUtils; +import org.apache.hadoop.yarn.conf.YarnConfiguration; + +/** + * An implementation of the interface will provide authorization related + * information and enforce permission check. It is excepted that any of the + * methods defined in this interface should be non-blocking call and should not + * involve expensive computation as these method could be invoked in RPC. + */ +@Private +@Unstable +public abstract class YarnAuthorizationProvider { + + private static final Log LOG = LogFactory.getLog(YarnAuthorizationProvider.class); + + private static YarnAuthorizationProvider authorizer = null; + + public static YarnAuthorizationProvider getInstance(Configuration conf) { + synchronized (YarnAuthorizationProvider.class) { + if (authorizer == null) { + Class<?> authorizerClass = + conf.getClass(YarnConfiguration.YARN_AUTHORIZATION_PROVIDER, + ConfiguredYarnAuthorizer.class); + authorizer = + (YarnAuthorizationProvider) ReflectionUtils.newInstance( + authorizerClass, conf); + authorizer.init(conf); + LOG.info(authorizerClass.getName() + " is instiantiated."); + } + } + return authorizer; + } + + /** + * Initialize the provider. Invoked on daemon startup. DefaultYarnAuthorizer is + * initialized based on configurations. + */ + public abstract void init(Configuration conf); + + /** + * Check if user has the permission to access the target object. + * + * @param accessType + * The type of accessing method. + * @param target + * The target object being accessed, e.g. app/queue + * @param user + * User who access the target + * @return true if user can access the object, otherwise false. + */ + public abstract boolean checkPermission(AccessType accessType, + PrivilegedEntity target, UserGroupInformation user); + + /** + * Set ACLs for the target object. AccessControlList class encapsulate the + * users and groups who can access the target. + * + * @param target + * The target object. + * @param acls + * A map from access method to a list of users and/or groups who has + * permission to do the access. + * @param ugi User who sets the permissions. + */ + public abstract void setPermission(PrivilegedEntity target, + Map<AccessType, AccessControlList> acls, UserGroupInformation ugi); + + /** + * Set a list of users/groups who have admin access + * + * @param acls users/groups who have admin access + * @param ugi User who sets the admin acls. + */ + public abstract void setAdmins(AccessControlList acls, UserGroupInformation ugi); + + /** + * Check if the user is an admin. + * + * @param ugi the user to be determined if it is an admin + * @return true if the given user is an admin + */ + public abstract boolean isAdmin(UserGroupInformation ugi); +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/WebApps.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/WebApps.java index f8c6f55c243d4..1b5840f5db42b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/WebApps.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/WebApps.java @@ -36,11 +36,10 @@ import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.http.HttpConfig.Policy; -import org.apache.hadoop.http.HttpConfig; import org.apache.hadoop.http.HttpServer2; import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.yarn.conf.YarnConfiguration; -import org.apache.hadoop.yarn.security.AdminACLsManager; import org.apache.hadoop.yarn.webapp.util.WebAppUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -240,7 +239,9 @@ public void setup() { .addEndpoint( URI.create(httpScheme + bindAddress + ":" + port)).setConf(conf).setFindPort(findPort) - .setACL(new AdminACLsManager(conf).getAdminAcl()) + .setACL(new AccessControlList(conf.get( + YarnConfiguration.YARN_ADMIN_ACL, + YarnConfiguration.DEFAULT_YARN_ADMIN_ACL))) .setPathSpec(pathList.toArray(new String[0])); boolean hasSpnegoConf = spnegoPrincipalKey != null diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java index d79de58b535be..618099546da6e 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java @@ -56,6 +56,8 @@ import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.ipc.RPCUtil; import org.apache.hadoop.yarn.ipc.YarnRPC; +import org.apache.hadoop.yarn.security.ConfiguredYarnAuthorizer; +import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol; import org.apache.hadoop.yarn.server.api.protocolrecords.AddToClusterNodeLabelsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.AddToClusterNodeLabelsResponse; @@ -101,7 +103,8 @@ public class AdminService extends CompositeService implements // Address to use for binding. May be a wildcard address. private InetSocketAddress masterServiceBindAddress; - private AccessControlList adminAcl; + + private YarnAuthorizationProvider authorizer; private final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); @@ -129,10 +132,11 @@ public void serviceInit(Configuration conf) throws Exception { YarnConfiguration.RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_PORT); - - adminAcl = new AccessControlList(conf.get( - YarnConfiguration.YARN_ADMIN_ACL, - YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)); + authorizer = YarnAuthorizationProvider.getInstance(conf); + authorizer.setAdmins(new AccessControlList(conf.get( + YarnConfiguration.YARN_ADMIN_ACL, + YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)), UserGroupInformation + .getCurrentUser()); rmId = conf.get(YarnConfiguration.RM_HA_ID); super.serviceInit(conf); } @@ -206,7 +210,7 @@ void resetLeaderElection() { } private UserGroupInformation checkAccess(String method) throws IOException { - return RMServerUtils.verifyAccess(adminAcl, method, LOG); + return RMServerUtils.verifyAdminAccess(authorizer, method, LOG); } private UserGroupInformation checkAcls(String method) throws YarnException { @@ -293,7 +297,7 @@ public synchronized void transitionToActive( "transitionToActive", "RMHAProtocolService"); } catch (Exception e) { RMAuditLogger.logFailure(user.getShortUserName(), "transitionToActive", - adminAcl.toString(), "RMHAProtocolService", + "", "RMHAProtocolService", "Exception transitioning to active"); throw new ServiceFailedException( "Error when transitioning to Active mode", e); @@ -318,7 +322,7 @@ public synchronized void transitionToStandby( "transitionToStandby", "RMHAProtocolService"); } catch (Exception e) { RMAuditLogger.logFailure(user.getShortUserName(), "transitionToStandby", - adminAcl.toString(), "RMHAProtocolService", + "", "RMHAProtocolService", "Exception transitioning to standby"); throw new ServiceFailedException( "Error when transitioning to Standby mode", e); @@ -446,9 +450,10 @@ private RefreshAdminAclsResponse refreshAdminAcls(boolean checkRMHAState) Configuration conf = getConfiguration(new Configuration(false), YarnConfiguration.YARN_SITE_CONFIGURATION_FILE); - adminAcl = new AccessControlList(conf.get( - YarnConfiguration.YARN_ADMIN_ACL, - YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)); + authorizer.setAdmins(new AccessControlList(conf.get( + YarnConfiguration.YARN_ADMIN_ACL, + YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)), UserGroupInformation + .getCurrentUser()); RMAuditLogger.logSuccess(user.getShortUserName(), argName, "AdminService"); @@ -584,9 +589,10 @@ private void refreshAll() throws ServiceFailedException { } } + // only for testing @VisibleForTesting public AccessControlList getAccessControlList() { - return this.adminAcl; + return ((ConfiguredYarnAuthorizer)authorizer).getAdminAcls(); } @VisibleForTesting @@ -661,7 +667,7 @@ public ReplaceLabelsOnNodeResponse replaceLabelsOnNode( private void checkRMStatus(String user, String argName, String msg) throws StandbyException { if (!isRMActive()) { - RMAuditLogger.logFailure(user, argName, adminAcl.toString(), + RMAuditLogger.logFailure(user, argName, "", "AdminService", "ResourceManager is not active. Can not " + msg); throwStandbyException(); } @@ -670,7 +676,7 @@ private void checkRMStatus(String user, String argName, String msg) private YarnException logAndWrapException(IOException ioe, String user, String argName, String msg) throws YarnException { LOG.info("Exception " + msg, ioe); - RMAuditLogger.logFailure(user, argName, adminAcl.toString(), + RMAuditLogger.logFailure(user, argName, "", "AdminService", "Exception " + msg); return RPCUtil.getRemoteException(ioe); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMServerUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMServerUtils.java index c80778cf0a2c7..3d28bb72547f6 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMServerUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMServerUtils.java @@ -45,6 +45,7 @@ import org.apache.hadoop.yarn.exceptions.InvalidResourceBlacklistRequestException; import org.apache.hadoop.yarn.exceptions.InvalidResourceRequestException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; +import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; @@ -140,43 +141,43 @@ public static void validateBlacklistRequest( } } - public static UserGroupInformation verifyAccess( - AccessControlList acl, String method, final Log LOG) + public static UserGroupInformation verifyAdminAccess( + YarnAuthorizationProvider authorizer, String method, final Log LOG) throws IOException { // by default, this method will use AdminService as module name - return verifyAccess(acl, method, "AdminService", LOG); + return verifyAdminAccess(authorizer, method, "AdminService", LOG); } /** * Utility method to verify if the current user has access based on the * passed {@link AccessControlList} - * @param acl the {@link AccessControlList} to check against + * @param authorizer the {@link AccessControlList} to check against * @param method the method name to be logged - * @param module, like AdminService or NodeLabelManager + * @param module like AdminService or NodeLabelManager * @param LOG the logger to use * @return {@link UserGroupInformation} of the current user * @throws IOException */ - public static UserGroupInformation verifyAccess( - AccessControlList acl, String method, String module, final Log LOG) + public static UserGroupInformation verifyAdminAccess( + YarnAuthorizationProvider authorizer, String method, String module, + final Log LOG) throws IOException { UserGroupInformation user; try { user = UserGroupInformation.getCurrentUser(); } catch (IOException ioe) { LOG.warn("Couldn't get current user", ioe); - RMAuditLogger.logFailure("UNKNOWN", method, acl.toString(), + RMAuditLogger.logFailure("UNKNOWN", method, "", "AdminService", "Couldn't get current user"); throw ioe; } - if (!acl.isUserAllowed(user)) { + if (!authorizer.isAdmin(user)) { LOG.warn("User " + user.getShortUserName() + " doesn't have permission" + " to call '" + method + "'"); - RMAuditLogger.logFailure(user.getShortUserName(), method, - acl.toString(), module, - RMAuditLogger.AuditConstants.UNAUTHORIZED_USER); + RMAuditLogger.logFailure(user.getShortUserName(), method, "", module, + RMAuditLogger.AuditConstants.UNAUTHORIZED_USER); throw new AccessControlException("User " + user.getShortUserName() + " doesn't have permission" + diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java index 1555291cf1909..9942d80406f4e 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java @@ -33,12 +33,11 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; -import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; -import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.nodelabels.NodeLabel; +import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeLabelsUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; @@ -60,16 +59,13 @@ protected Queue() { ConcurrentMap<String, Queue> queueCollections = new ConcurrentHashMap<String, Queue>(); - protected AccessControlList adminAcl; - + private YarnAuthorizationProvider authorizer; private RMContext rmContext = null; @Override protected void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); - adminAcl = - new AccessControlList(conf.get(YarnConfiguration.YARN_ADMIN_ACL, - YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)); + authorizer = YarnAuthorizationProvider.getInstance(conf); } @Override @@ -479,7 +475,7 @@ private Map<String, Host> cloneNodeMap() { public boolean checkAccess(UserGroupInformation user) { // make sure only admin can invoke // this method - if (adminAcl.isUserAllowed(user)) { + if (authorizer.isAdmin(user)) { return true; } return false; diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java index c4900c3976f91..65d68598aead0 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java @@ -28,12 +28,14 @@ import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; +import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.exceptions.InvalidResourceRequestException; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +import org.apache.hadoop.yarn.security.AccessType; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; @@ -348,4 +350,15 @@ public static boolean checkQueueLabelExpression(Set<String> queueLabels, } return true; } + + + public static AccessType toAccessType(QueueACL acl) { + switch (acl) { + case ADMINISTER_QUEUE: + return AccessType.ADMINISTER_QUEUE; + case SUBMIT_APPLICATIONS: + return AccessType.SUBMIT_APP; + } + return null; + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/AbstractCSQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/AbstractCSQueue.java index e4c26658b0bf5..753fb14bf13c3 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/AbstractCSQueue.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/AbstractCSQueue.java @@ -34,12 +34,16 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +import org.apache.hadoop.yarn.security.AccessType; +import org.apache.hadoop.yarn.security.PrivilegedEntity; +import org.apache.hadoop.yarn.security.PrivilegedEntity.EntityType; +import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceUsage; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; -import org.apache.hadoop.yarn.util.resource.Resources; + import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Sets; @@ -60,7 +64,8 @@ public abstract class AbstractCSQueue implements CSQueue { Resource maximumAllocation; QueueState state; final QueueMetrics metrics; - + protected final PrivilegedEntity queueEntity; + final ResourceCalculator resourceCalculator; Set<String> accessibleLabels; RMNodeLabelsManager labelManager; @@ -70,8 +75,8 @@ public abstract class AbstractCSQueue implements CSQueue { Map<String, Float> absoluteMaxCapacityByNodeLabels; Map<String, Float> maxCapacityByNodeLabels; - Map<QueueACL, AccessControlList> acls = - new HashMap<QueueACL, AccessControlList>(); + Map<AccessType, AccessControlList> acls = + new HashMap<AccessType, AccessControlList>(); boolean reservationsContinueLooking; private boolean preemptionDisabled; @@ -81,6 +86,7 @@ public abstract class AbstractCSQueue implements CSQueue { private final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); private CapacitySchedulerContext csContext; + protected YarnAuthorizationProvider authorizer = null; public AbstractCSQueue(CapacitySchedulerContext cs, String queueName, CSQueue parent, CSQueue old) throws IOException { @@ -126,6 +132,8 @@ public AbstractCSQueue(CapacitySchedulerContext cs, accessibleLabels, labelManager); this.csContext = cs; queueUsage = new ResourceUsage(); + queueEntity = new PrivilegedEntity(EntityType.QUEUE, getQueuePath()); + authorizer = YarnAuthorizationProvider.getInstance(cs.getConf()); } @Override @@ -181,7 +189,11 @@ public QueueMetrics getMetrics() { public String getQueueName() { return queueName; } - + + public PrivilegedEntity getPrivilegedEntity() { + return queueEntity; + } + @Override public synchronized CSQueue getParent() { return parent; @@ -195,22 +207,13 @@ public synchronized void setParent(CSQueue newParentQueue) { public Set<String> getAccessibleNodeLabels() { return accessibleLabels; } - + @Override public boolean hasAccess(QueueACL acl, UserGroupInformation user) { - synchronized (this) { - if (acls.get(acl).isUserAllowed(user)) { - return true; - } - } - - if (parent != null) { - return parent.hasAccess(acl, user); - } - - return false; + return authorizer.checkPermission(SchedulerUtils.toAccessType(acl), + queueEntity, user); } - + @Override public synchronized void setUsedCapacity(float usedCapacity) { this.usedCapacity = usedCapacity; @@ -251,7 +254,7 @@ public String getDefaultNodeLabelExpression() { synchronized void setupQueueConfigs(Resource clusterResource, float capacity, float absoluteCapacity, float maximumCapacity, float absoluteMaxCapacity, - QueueState state, Map<QueueACL, AccessControlList> acls, + QueueState state, Map<AccessType, AccessControlList> acls, Set<String> labels, String defaultLabelExpression, Map<String, Float> nodeLabelCapacities, Map<String, Float> maximumNodeLabelCapacities, @@ -436,7 +439,7 @@ public boolean getReservationContinueLooking() { } @Private - public Map<QueueACL, AccessControlList> getACLs() { + public Map<AccessType, AccessControlList> getACLs() { return acls; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java index 916a4db9101a0..6b9d8460b23b8 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java @@ -63,6 +63,7 @@ import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.proto.YarnServiceProtos.SchedulerResourceTypes; +import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; @@ -124,7 +125,8 @@ public class CapacityScheduler extends PreemptableResourceScheduler, CapacitySchedulerContext, Configurable { private static final Log LOG = LogFactory.getLog(CapacityScheduler.class); - + private YarnAuthorizationProvider authorizer; + private CSQueue root; // timeout to join when we stop this service protected final long THREAD_JOIN_TIMEOUT_MS = 1000; @@ -297,7 +299,7 @@ private synchronized void initScheduler(Configuration configuration) throws new ConcurrentHashMap<ApplicationId, SchedulerApplication<FiCaSchedulerApp>>(); this.labelManager = rmContext.getNodeLabelManager(); - + authorizer = YarnAuthorizationProvider.getInstance(yarnConf); initializeQueues(this.conf); scheduleAsynchronously = this.conf.getScheduleAynschronously(); @@ -474,6 +476,7 @@ private void initializeQueues(CapacitySchedulerConfiguration conf) labelManager.reinitializeQueueLabels(getQueueToLabels()); LOG.info("Initialized root queue " + root); initializeQueueMappings(); + setQueueAcls(authorizer, queues); } @Lock(CapacityScheduler.class) @@ -499,8 +502,19 @@ private void reinitializeQueues(CapacitySchedulerConfiguration conf) root.updateClusterResource(clusterResource); labelManager.reinitializeQueueLabels(getQueueToLabels()); + setQueueAcls(authorizer, queues); } - + + @VisibleForTesting + public static void setQueueAcls(YarnAuthorizationProvider authorizer, + Map<String, CSQueue> queues) throws IOException { + for (CSQueue queue : queues.values()) { + AbstractCSQueue csQueue = (AbstractCSQueue) queue; + authorizer.setPermission(csQueue.getPrivilegedEntity(), + csQueue.getACLs(), UserGroupInformation.getCurrentUser()); + } + } + private Map<String, Set<String>> getQueueToLabels() { Map<String, Set<String>> queueToLabels = new HashMap<String, Set<String>>(); for (CSQueue queue : queues.values()) { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java index 268cc6cb20a03..b49a60a6b94ee 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java @@ -40,8 +40,10 @@ import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; +import org.apache.hadoop.yarn.security.AccessType; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSchedulerConfiguration; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; @@ -530,11 +532,11 @@ public void setAcl(String queue, QueueACL acl, String aclString) { set(queuePrefix + getAclKey(acl), aclString); } - public Map<QueueACL, AccessControlList> getAcls(String queue) { - Map<QueueACL, AccessControlList> acls = - new HashMap<QueueACL, AccessControlList>(); + public Map<AccessType, AccessControlList> getAcls(String queue) { + Map<AccessType, AccessControlList> acls = + new HashMap<AccessType, AccessControlList>(); for (QueueACL acl : QueueACL.values()) { - acls.put(acl, getAcl(queue, acl)); + acls.put(SchedulerUtils.toAccessType(acl), getAcl(queue, acl)); } return acls; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java index c1432101510b3..525822302f788 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java @@ -55,6 +55,7 @@ import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; +import org.apache.hadoop.yarn.security.AccessType; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; @@ -153,7 +154,7 @@ public LeafQueue(CapacitySchedulerContext cs, QueueState state = cs.getConfiguration().getState(getQueuePath()); - Map<QueueACL, AccessControlList> acls = + Map<AccessType, AccessControlList> acls = cs.getConfiguration().getAcls(getQueuePath()); setupQueueConfigs(cs.getClusterResource(), capacity, absoluteCapacity, @@ -189,7 +190,7 @@ protected synchronized void setupQueueConfigs( int userLimit, float userLimitFactor, int maxApplications, float maxAMResourcePerQueuePercent, int maxApplicationsPerUser, QueueState state, - Map<QueueACL, AccessControlList> acls, int nodeLocalityDelay, + Map<AccessType, AccessControlList> acls, int nodeLocalityDelay, Set<String> labels, String defaultLabelExpression, Map<String, Float> capacitieByLabel, Map<String, Float> maximumCapacitiesByLabel, @@ -247,7 +248,7 @@ protected synchronized void setupQueueConfigs( maximumAllocation); StringBuilder aclsString = new StringBuilder(); - for (Map.Entry<QueueACL, AccessControlList> e : acls.entrySet()) { + for (Map.Entry<AccessType, AccessControlList> e : acls.entrySet()) { aclsString.append(e.getKey() + ":" + e.getValue().getAclString()); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java index 5a2e234436382..29a8ba3e20a9c 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java @@ -49,6 +49,7 @@ import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; +import org.apache.hadoop.yarn.security.AccessType; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; @@ -107,7 +108,7 @@ public ParentQueue(CapacitySchedulerContext cs, QueueState state = cs.getConfiguration().getState(getQueuePath()); - Map<QueueACL, AccessControlList> acls = + Map<AccessType, AccessControlList> acls = cs.getConfiguration().getAcls(getQueuePath()); setupQueueConfigs(cs.getClusterResource(), capacity, absoluteCapacity, @@ -124,7 +125,7 @@ public ParentQueue(CapacitySchedulerContext cs, synchronized void setupQueueConfigs(Resource clusterResource, float capacity, float absoluteCapacity, float maximumCapacity, float absoluteMaxCapacity, - QueueState state, Map<QueueACL, AccessControlList> acls, + QueueState state, Map<AccessType, AccessControlList> acls, Set<String> accessibleLabels, String defaultLabelExpression, Map<String, Float> nodeLabelCapacities, Map<String, Float> maximumCapacitiesByLabel, @@ -134,7 +135,7 @@ synchronized void setupQueueConfigs(Resource clusterResource, float capacity, defaultLabelExpression, nodeLabelCapacities, maximumCapacitiesByLabel, reservationContinueLooking, maximumAllocation); StringBuilder aclsString = new StringBuilder(); - for (Map.Entry<QueueACL, AccessControlList> e : acls.entrySet()) { + for (Map.Entry<AccessType, AccessControlList> e : acls.entrySet()) { aclsString.append(e.getKey() + ":" + e.getValue().getAclString()); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.java index 72983cac530a1..696ad7a119953 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.java @@ -37,7 +37,6 @@ import java.util.Map; import org.junit.Assert; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.security.UserGroupInformation; @@ -45,6 +44,7 @@ import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; @@ -726,6 +726,9 @@ public void testQueueAcl() throws Exception { CapacityScheduler.parseQueue(csContext, csConf, null, CapacitySchedulerConfiguration.ROOT, queues, queues, TestUtils.spyHook); + YarnAuthorizationProvider authorizer = + YarnAuthorizationProvider.getInstance(conf); + CapacityScheduler.setQueueAcls(authorizer, queues); UserGroupInformation user = UserGroupInformation.getCurrentUser(); // Setup queue configs diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/SCMAdminProtocolService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/SCMAdminProtocolService.java index 3ecca02e732ac..6f2baf649c025 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/SCMAdminProtocolService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/SCMAdminProtocolService.java @@ -31,6 +31,7 @@ import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.service.AbstractService; +import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; import org.apache.hadoop.yarn.server.api.SCMAdminProtocol; import org.apache.hadoop.yarn.server.api.protocolrecords.RunSharedCacheCleanerTaskRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RunSharedCacheCleanerTaskResponse; @@ -58,8 +59,7 @@ public class SCMAdminProtocolService extends AbstractService implements private Server server; InetSocketAddress clientBindAddress; private final CleanerService cleanerService; - private AccessControlList adminAcl; - + private YarnAuthorizationProvider authorizer; public SCMAdminProtocolService(CleanerService cleanerService) { super(SCMAdminProtocolService.class.getName()); this.cleanerService = cleanerService; @@ -68,9 +68,7 @@ public SCMAdminProtocolService(CleanerService cleanerService) { @Override protected void serviceInit(Configuration conf) throws Exception { this.clientBindAddress = getBindAddress(conf); - adminAcl = new AccessControlList(conf.get( - YarnConfiguration.YARN_ADMIN_ACL, - YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)); + authorizer = YarnAuthorizationProvider.getInstance(conf); super.serviceInit(conf); } @@ -119,7 +117,7 @@ private void checkAcls(String method) throws YarnException { throw RPCUtil.getRemoteException(ioe); } - if (!adminAcl.isUserAllowed(user)) { + if (!authorizer.isAdmin(user)) { LOG.warn("User " + user.getShortUserName() + " doesn't have permission" + " to call '" + method + "'");
de3cde3e1eb1984b86ba9320e6662b8bf63e1fcb
elasticsearch
Rename Engine-seacher() into- Engine-acquireSearcher()--The name should reflect that the caller is responsible for-releaseing the searcher again.-
p
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/index/engine/Engine.java b/src/main/java/org/elasticsearch/index/engine/Engine.java index d15f9aaae87fd..e0c5f2e518afc 100644 --- a/src/main/java/org/elasticsearch/index/engine/Engine.java +++ b/src/main/java/org/elasticsearch/index/engine/Engine.java @@ -81,7 +81,14 @@ public interface Engine extends IndexShardComponent, CloseableComponent { GetResult get(Get get) throws EngineException; - Searcher searcher() throws EngineException; + /** + * Retruns a new searcher instance. The consumer of this + * API is responsible for releasing the returned seacher in a + * safe manner, preferrablly in a try/finally block. + * + * @see Searcher#release() + */ + Searcher acquireSearcher() throws EngineException; List<Segment> segments(); diff --git a/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java b/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java index 3c80d4f2ef0a0..28bc620b15251 100644 --- a/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java +++ b/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java @@ -337,7 +337,7 @@ public GetResult get(Get get) throws EngineException { } // no version, get the version from the index, we know that we refresh on flush - Searcher searcher = searcher(); + Searcher searcher = acquireSearcher(); final Versions.DocIdAndVersion docIdAndVersion; try { docIdAndVersion = Versions.loadDocIdAndVersion(searcher.reader(), get.uid()); @@ -676,7 +676,7 @@ public void delete(DeleteByQuery delete) throws EngineException { } @Override - public final Searcher searcher() throws EngineException { + public final Searcher acquireSearcher() throws EngineException { SearcherManager manager = this.searcherManager; try { IndexSearcher searcher = manager.acquire(); @@ -1128,7 +1128,7 @@ public List<Segment> segments() { Map<String, Segment> segments = new HashMap<String, Segment>(); // first, go over and compute the search ones... - Searcher searcher = searcher(); + Searcher searcher = acquireSearcher(); try { for (AtomicReaderContext reader : searcher.reader().leaves()) { assert reader.reader() instanceof SegmentReader; @@ -1279,7 +1279,7 @@ private Object dirtyLock(Term uid) { } private long loadCurrentVersionFromIndex(Term uid) throws IOException { - Searcher searcher = searcher(); + Searcher searcher = acquireSearcher(); try { return Versions.loadVersion(searcher.reader(), uid); } finally { @@ -1478,7 +1478,7 @@ public IndexSearcher newSearcher(IndexReader reader) throws IOException { // fresh index writer, just do on all of it newSearcher = searcher; } else { - currentSearcher = searcher(); + currentSearcher = acquireSearcher(); // figure out the newSearcher, with only the new readers that are relevant for us List<IndexReader> readers = Lists.newArrayList(); for (AtomicReaderContext newReaderContext : searcher.getIndexReader().leaves()) { diff --git a/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java b/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java index 5fb057cc89fdd..de1ad3efa5c96 100644 --- a/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java +++ b/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java @@ -593,7 +593,7 @@ public void recover(Engine.RecoveryHandler recoveryHandler) throws EngineExcepti @Override public Engine.Searcher acquireSearcher() { readAllowed(); - return engine.searcher(); + return engine.acquireSearcher(); } public void close(String reason) { diff --git a/src/test/java/org/elasticsearch/index/engine/robin/RobinEngineTests.java b/src/test/java/org/elasticsearch/index/engine/robin/RobinEngineTests.java index 4cdb05be30372..6d6028e7ae000 100644 --- a/src/test/java/org/elasticsearch/index/engine/robin/RobinEngineTests.java +++ b/src/test/java/org/elasticsearch/index/engine/robin/RobinEngineTests.java @@ -299,7 +299,7 @@ public void testSegments() throws Exception { @Test public void testSimpleOperations() throws Exception { - Engine.Searcher searchResult = engine.searcher(); + Engine.Searcher searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0)); searchResult.release(); @@ -310,7 +310,7 @@ public void testSimpleOperations() throws Exception { engine.create(new Engine.Create(null, newUid("1"), doc)); // its not there... - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0)); searchResult.release(); @@ -330,7 +330,7 @@ public void testSimpleOperations() throws Exception { engine.refresh(new Engine.Refresh().force(false)); // now its there... - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1)); searchResult.release(); @@ -349,7 +349,7 @@ public void testSimpleOperations() throws Exception { engine.index(new Engine.Index(null, newUid("1"), doc)); // its not updated yet... - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0)); @@ -365,7 +365,7 @@ public void testSimpleOperations() throws Exception { // refresh and it should be updated engine.refresh(new Engine.Refresh().force(false)); - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 1)); @@ -375,7 +375,7 @@ public void testSimpleOperations() throws Exception { engine.delete(new Engine.Delete("test", "1", newUid("1"))); // its not deleted yet - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 1)); @@ -389,7 +389,7 @@ public void testSimpleOperations() throws Exception { // refresh and it should be deleted engine.refresh(new Engine.Refresh().force(false)); - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0)); @@ -402,7 +402,7 @@ public void testSimpleOperations() throws Exception { engine.create(new Engine.Create(null, newUid("1"), doc)); // its not there... - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0)); @@ -412,7 +412,7 @@ public void testSimpleOperations() throws Exception { engine.refresh(new Engine.Refresh().force(false)); // now its there... - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0)); @@ -436,7 +436,7 @@ public void testSimpleOperations() throws Exception { engine.index(new Engine.Index(null, newUid("1"), doc)); // its not updated yet... - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 0)); @@ -445,7 +445,7 @@ public void testSimpleOperations() throws Exception { // refresh and it should be updated engine.refresh(new Engine.Refresh().force(false)); - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test1")), 1)); @@ -456,7 +456,7 @@ public void testSimpleOperations() throws Exception { @Test public void testSearchResultRelease() throws Exception { - Engine.Searcher searchResult = engine.searcher(); + Engine.Searcher searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0)); searchResult.release(); @@ -465,7 +465,7 @@ public void testSearchResultRelease() throws Exception { engine.create(new Engine.Create(null, newUid("1"), doc)); // its not there... - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 0)); searchResult.release(); @@ -474,7 +474,7 @@ public void testSearchResultRelease() throws Exception { engine.refresh(new Engine.Refresh().force(false)); // now its there... - searchResult = engine.searcher(); + searchResult = engine.acquireSearcher(); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(1)); MatcherAssert.assertThat(searchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(new TermQuery(new Term("value", "test")), 1)); // don't release the search result yet... @@ -482,7 +482,7 @@ public void testSearchResultRelease() throws Exception { // delete, refresh and do a new search, it should not be there engine.delete(new Engine.Delete("test", "1", newUid("1"))); engine.refresh(new Engine.Refresh().force(false)); - Engine.Searcher updateSearchResult = engine.searcher(); + Engine.Searcher updateSearchResult = engine.acquireSearcher(); MatcherAssert.assertThat(updateSearchResult, EngineSearcherTotalHitsMatcher.engineSearcherTotalHits(0)); updateSearchResult.release();
ceb0d5e68bc6cbf8015be6d5dd785991fbc81455
hbase
fix spurious 400s produced by test--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@790486 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/src/contrib/stargate/src/test/org/apache/hadoop/hbase/stargate/TestRowResource.java b/src/contrib/stargate/src/test/org/apache/hadoop/hbase/stargate/TestRowResource.java index 0a8b9b702a51..fa760181a402 100644 --- a/src/contrib/stargate/src/test/org/apache/hadoop/hbase/stargate/TestRowResource.java +++ b/src/contrib/stargate/src/test/org/apache/hadoop/hbase/stargate/TestRowResource.java @@ -317,7 +317,7 @@ public void testMultiCellGetPutXML() throws IOException, JAXBException { Thread.yield(); // make sure the fake row was not actually created - response = client.get(path); + response = client.get(path, MIMETYPE_XML); assertEquals(response.getCode(), 404); // check that all of the values were created @@ -349,7 +349,7 @@ public void testMultiCellGetPutPB() throws IOException { Thread.yield(); // make sure the fake row was not actually created - response = client.get(path); + response = client.get(path, MIMETYPE_PROTOBUF); assertEquals(response.getCode(), 404); // check that all of the values were created
d2cf18983b635c3c47ca6bfcadc06bb2e15a547e
camel
CAMEL-1198: Ant path matcher now also possible- with camel-ftp.--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@730753 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java b/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java index df3fe20eb3d3a..c180e4318c6f5 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java @@ -23,9 +23,9 @@ import org.apache.camel.AsyncCallback; import org.apache.camel.Processor; -import org.apache.camel.util.ObjectHelper; import org.apache.camel.impl.ScheduledPollConsumer; import org.apache.camel.processor.DeadLetterChannel; +import org.apache.camel.util.ObjectHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -103,8 +103,8 @@ protected void pollDirectory(File fileOrDirectory, List<File> fileList) { } File[] files = fileOrDirectory.listFiles(); for (File file : files) { - if (endpoint.isRecursive() && file.isDirectory()) { - if (isValidFile(file)) { + if (file.isDirectory()) { + if (endpoint.isRecursive() && isValidFile(file)) { // recursive scan and add the sub files and folders pollDirectory(file, fileList); } diff --git a/camel-core/src/main/java/org/apache/camel/util/CollectionHelper.java b/camel-core/src/main/java/org/apache/camel/util/CollectionHelper.java index 4a1a397d5747d..9b4acf5951630 100644 --- a/camel-core/src/main/java/org/apache/camel/util/CollectionHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/CollectionHelper.java @@ -18,7 +18,9 @@ import java.lang.reflect.Array; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; +import java.util.Iterator; import java.util.List; import java.util.Map; @@ -107,4 +109,29 @@ public static List filterList(List list, Object... filters) { } return answer; } + + public static String collectionAsCommaDelimitedString(String[] col) { + if (col == null || col.length == 0) { + return ""; + } + return collectionAsCommaDelimitedString(Arrays.asList(col)); + } + + public static String collectionAsCommaDelimitedString(Collection col) { + if (col == null || col.isEmpty()) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + Iterator it = col.iterator(); + while (it.hasNext()) { + sb.append(it.next()); + if (it.hasNext()) { + sb.append(","); + } + } + + return sb.toString(); + } + } diff --git a/camel-core/src/test/java/org/apache/camel/util/CollectionHelperTest.java b/camel-core/src/test/java/org/apache/camel/util/CollectionHelperTest.java new file mode 100644 index 0000000000000..95b8cfb47444e --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/util/CollectionHelperTest.java @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.util; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import junit.framework.TestCase; + +/** + * @version $Revision$ + */ +public class CollectionHelperTest extends TestCase { + + private String[] names = new String[]{"Claus", "Willem", "Jonathan"}; + private List list = Arrays.asList(names); + + public void testCollectionAsCommaDelimitedString() { + assertEquals("Claus,Willem,Jonathan", CollectionHelper.collectionAsCommaDelimitedString(names)); + assertEquals("Claus,Willem,Jonathan", CollectionHelper.collectionAsCommaDelimitedString(list)); + + assertEquals("", CollectionHelper.collectionAsCommaDelimitedString((String[]) null)); + assertEquals("", CollectionHelper.collectionAsCommaDelimitedString((Collection) null)); + + assertEquals("Claus", CollectionHelper.collectionAsCommaDelimitedString(new String[]{"Claus"})); + } + +} \ No newline at end of file diff --git a/components/camel-ftp/pom.xml b/components/camel-ftp/pom.xml index cfa31de1b9466..91b28692b0ec7 100644 --- a/components/camel-ftp/pom.xml +++ b/components/camel-ftp/pom.xml @@ -81,6 +81,13 @@ <scope>test</scope> </dependency> + <!-- for unit testing AntPathMatcher --> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-spring</artifactId> + <scope>test</scope> + </dependency> + <dependency> <groupId>org.apache.ftpserver</groupId> <artifactId>ftpserver-core</artifactId> diff --git a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/AntPathMatcherRemoteFileFilter.java b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/AntPathMatcherRemoteFileFilter.java new file mode 100644 index 0000000000000..c51b46e524fe4 --- /dev/null +++ b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/AntPathMatcherRemoteFileFilter.java @@ -0,0 +1,89 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.file.remote; + +import org.apache.camel.util.ObjectHelper; +import static org.apache.camel.util.CollectionHelper.collectionAsCommaDelimitedString; + +/** + * File filter using Spring's AntPathMatcher. + * <p/> + * Exclude take precedence over includes. If a file match both exclude and include it will be regarded as excluded. + */ +public class AntPathMatcherRemoteFileFilter implements RemoteFileFilter { + private static final String ANTPATHMATCHER_CLASSNAME = "org.apache.camel.component.file.AntPathMatcherFileFilter"; + private String[] excludes; + private String[] includes; + + public boolean accept(RemoteFile file) { + // we must use reflection to invoke the AntPathMatcherFileFilter that reside in camel-spring.jar + // and we don't want camel-ftp to have runtime dependency on camel-spring.jar + Class clazz = ObjectHelper.loadClass(ANTPATHMATCHER_CLASSNAME); + ObjectHelper.notNull(clazz, ANTPATHMATCHER_CLASSNAME + " not found in classpath. camel-spring.jar is required in the classpath."); + + try { + Object filter = ObjectHelper.newInstance(clazz); + + // invoke setIncludes(String), must using string type as invoking with string[] does not work + ObjectHelper.invokeMethod(filter.getClass().getMethod("setIncludes", String.class), filter, collectionAsCommaDelimitedString(includes)); + + // invoke setExcludes(String), must using string type as invoking with string[] does not work + ObjectHelper.invokeMethod(filter.getClass().getMethod("setExcludes", String.class), filter, collectionAsCommaDelimitedString(excludes)); + + // invoke acceptPathName(String) + String path = file.getRelativeFileName(); + Boolean result = (Boolean) ObjectHelper.invokeMethod(filter.getClass().getMethod("acceptPathName", String.class), filter, path); + return result; + + } catch (NoSuchMethodException e) { + throw new TypeNotPresentException(ANTPATHMATCHER_CLASSNAME, e); + } + } + + public String[] getExcludes() { + return excludes; + } + + public void setExcludes(String[] excludes) { + this.excludes = excludes; + } + + public String[] getIncludes() { + return includes; + } + + public void setIncludes(String[] includes) { + this.includes = includes; + } + + /** + * Sets excludes using a single string where each element can be separated with comma + */ + public void setExcludes(String excludes) { + setExcludes(excludes.split(",")); + } + + /** + * Sets includes using a single string where each element can be separated with comma + */ + public void setIncludes(String includes) { + setIncludes(includes.split(",")); + } + + + +} diff --git a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java index 75adaf4e13430..0872b8ce81675 100644 --- a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java +++ b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpConsumer.java @@ -30,7 +30,7 @@ public FtpConsumer(RemoteFileEndpoint endpoint, Processor processor, RemoteFileO super(endpoint, processor, ftp); } - protected void pollDirectory(String fileName, boolean processDir, List<RemoteFile> fileList) { + protected void pollDirectory(String fileName, List<RemoteFile> fileList) { if (fileName == null) { return; } @@ -45,11 +45,11 @@ protected void pollDirectory(String fileName, boolean processDir, List<RemoteFil List<FTPFile> files = operations.listFiles(fileName); for (FTPFile file : files) { RemoteFile<FTPFile> remote = asRemoteFile(fileName, file); - if (processDir && file.isDirectory()) { - if (isValidFile(remote, true)) { + if (file.isDirectory()) { + if (endpoint.isRecursive() && isValidFile(remote, true)) { // recursive scan and add the sub files and folders String directory = fileName + "/" + file.getName(); - pollDirectory(directory, endpoint.isRecursive(), fileList); + pollDirectory(directory, fileList); } } else if (file.isFile()) { if (isValidFile(remote, false)) { diff --git a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/RemoteFileConsumer.java b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/RemoteFileConsumer.java index bbcc5c7ea93bb..aa712d6e60d11 100644 --- a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/RemoteFileConsumer.java +++ b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/RemoteFileConsumer.java @@ -62,7 +62,7 @@ protected void poll() throws Exception { String name = endpoint.getConfiguration().getFile(); boolean isDirectory = endpoint.getConfiguration().isDirectory(); if (isDirectory) { - pollDirectory(name, endpoint.isRecursive(), files); + pollDirectory(name, files); } else { pollFile(name, files); } @@ -103,10 +103,9 @@ protected void poll() throws Exception { * Polls the given directory for files to process * * @param fileName current directory or file - * @param processDir recursive * @param fileList current list of files gathered */ - protected abstract void pollDirectory(String fileName, boolean processDir, List<RemoteFile> fileList); + protected abstract void pollDirectory(String fileName, List<RemoteFile> fileList); /** * Polls the given file diff --git a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpConsumer.java b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpConsumer.java index 15d22987d7abf..32c6d37b4291b 100644 --- a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpConsumer.java +++ b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpConsumer.java @@ -30,7 +30,7 @@ public SftpConsumer(RemoteFileEndpoint endpoint, Processor processor, RemoteFile super(endpoint, processor, operations); } - protected void pollDirectory(String fileName, boolean processDir, List<RemoteFile> fileList) { + protected void pollDirectory(String fileName, List<RemoteFile> fileList) { if (fileName == null) { return; } @@ -45,10 +45,10 @@ protected void pollDirectory(String fileName, boolean processDir, List<RemoteFil List<ChannelSftp.LsEntry> files = operations.listFiles(fileName); for (ChannelSftp.LsEntry file : files) { RemoteFile<ChannelSftp.LsEntry> remote = asRemoteFile(fileName, file); - if (processDir && file.getAttrs().isDir()) { - if (isValidFile(remote, true)) { + if (file.getAttrs().isDir()) { + if (endpoint.isRecursive() && isValidFile(remote, true)) { // recursive scan and add the sub files and folders - pollDirectory(file.getFilename(), endpoint.isRecursive(), fileList); + pollDirectory(file.getFilename(), fileList); } } else if (!file.getAttrs().isLink()) { if (isValidFile(remote, false)) { diff --git a/components/camel-spring/pom.xml b/components/camel-spring/pom.xml index 3cce464b949e1..278723597057e 100644 --- a/components/camel-spring/pom.xml +++ b/components/camel-spring/pom.xml @@ -43,6 +43,7 @@ org.apache.camel.spring.*;${camel.osgi.version}, org.apache.camel.component;${camel.osgi.split.pkg};${camel.osgi.version}, org.apache.camel.component.event;${camel.osgi.split.pkg};${camel.osgi.version}, + org.apache.camel.component.file;${camel.osgi.split.pkg};${camel.osgi.version}, org.apache.camel.component.test;${camel.osgi.split.pkg};${camel.osgi.version}, org.apache.camel.component.validator;${camel.osgi.split.pkg};${camel.osgi.version}, org.apache.camel.component.xslt;${camel.osgi.split.pkg};${camel.osgi.version} diff --git a/components/camel-spring/src/main/java/org/apache/camel/component/file/AntPathMatcherFileFilter.java b/components/camel-spring/src/main/java/org/apache/camel/component/file/AntPathMatcherFileFilter.java index 0ffcdbe7346a5..578a3801e3d9f 100644 --- a/components/camel-spring/src/main/java/org/apache/camel/component/file/AntPathMatcherFileFilter.java +++ b/components/camel-spring/src/main/java/org/apache/camel/component/file/AntPathMatcherFileFilter.java @@ -37,7 +37,16 @@ public class AntPathMatcherFileFilter implements FileFilter { private String[] includes; public boolean accept(File pathname) { - String path = pathname.getPath(); + return acceptPathName(pathname.getPath()); + } + + /** + * Accepts the given file by the path name + * + * @param path the path + * @return <tt>true</tt> if accepted, <tt>false</tt> if not + */ + public boolean acceptPathName(String path) { // must use single / as path seperators path = StringUtils.replace(path, File.separator, "/"); diff --git a/tests/camel-itest/pom.xml b/tests/camel-itest/pom.xml index 1264c16780231..381bbc0afb60f 100644 --- a/tests/camel-itest/pom.xml +++ b/tests/camel-itest/pom.xml @@ -20,136 +20,170 @@ <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"> - <modelVersion>4.0.0</modelVersion> + <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.apache.camel</groupId> - <artifactId>camel-parent</artifactId> - <version>2.0-SNAPSHOT</version> - </parent> + <parent> + <groupId>org.apache.camel</groupId> + <artifactId>camel-parent</artifactId> + <version>2.0-SNAPSHOT</version> + </parent> - <artifactId>camel-itest</artifactId> - <name>Camel :: Integration Tests</name> - <description>Performs cross component integration tests</description> + <artifactId>camel-itest</artifactId> + <name>Camel :: Integration Tests</name> + <description>Performs cross component integration tests</description> - <dependencies> - <dependency> - <groupId>org.apache.camel</groupId> - <artifactId>camel-jms</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.camel</groupId> - <artifactId>camel-spring</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.camel</groupId> - <artifactId>camel-cxf</artifactId> - </dependency> - <dependency> - <groupId>org.apache.camel</groupId> - <artifactId>camel-jetty</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.camel</groupId> - <artifactId>camel-http</artifactId> - <scope>test</scope> - </dependency> + <dependencies> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-jms</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-spring</artifactId> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-cxf</artifactId> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-jetty</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-http</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-ftp</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.ftpserver</groupId> + <artifactId>ftpserver-core</artifactId> + <version>1.0.0-M3</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.ftpserver</groupId> + <artifactId>ftplet-api</artifactId> + <version>1.0.0-M3</version> + <scope>test</scope> + </dependency> + <!-- ftpserver using mina 2.0.0-M2 --> + <dependency> + <groupId>org.apache.mina</groupId> + <artifactId>mina-core</artifactId> + <version>2.0.0-M2</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + <scope>test</scope> + </dependency> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.camel</groupId> - <artifactId>camel-core</artifactId> - <type>test-jar</type> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.activemq</groupId> - <artifactId>activemq-core</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.activemq</groupId> - <artifactId>activemq-camel</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.xbean</groupId> - <artifactId>xbean-spring</artifactId> - <exclusions> - <exclusion> - <groupId>org.springframework</groupId> - <artifactId>spring</artifactId> - </exclusion> - </exclusions> - <scope>test</scope> - </dependency> - <dependency> - <groupId>commons-logging</groupId> - <artifactId>commons-logging</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>commons-collections</groupId> - <artifactId>commons-collections</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.springframework</groupId> - <artifactId>spring-test</artifactId> - <scope>test</scope> - </dependency> - </dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-core</artifactId> + <type>test-jar</type> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-core</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.activemq</groupId> + <artifactId>activemq-camel</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.xbean</groupId> + <artifactId>xbean-spring</artifactId> + <exclusions> + <exclusion> + <groupId>org.springframework</groupId> + <artifactId>spring</artifactId> + </exclusion> + </exclusions> + <scope>test</scope> + </dependency> + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>commons-collections</groupId> + <artifactId>commons-collections</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> + <scope>test</scope> + </dependency> + </dependencies> - <build> - <plugins> - <plugin> - <artifactId>maven-surefire-plugin</artifactId> - <configuration> - <forkMode>pertest</forkMode> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.cxf</groupId> - <artifactId>cxf-codegen-plugin</artifactId> - <version>${cxf-version}</version> - <executions> - <execution> - <id>generate-test-sources</id> - <phase>generate-sources</phase> - <configuration> - <testSourceRoot>${basedir}/target/generated/src/test/java</testSourceRoot> - <wsdlOptions> - <wsdlOption> - <wsdl> - ${basedir}/src/test/resources/wsdl/CustomerService-1.0.0.wsdl - </wsdl> - </wsdlOption> - <wsdlOption> - <wsdl> - ${basedir}/src/test/resources/wsdl/hello_world.wsdl - </wsdl> - </wsdlOption> - </wsdlOptions> - </configuration> - <goals> - <goal>wsdl2java</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - </build> + <build> + <plugins> + <plugin> + <artifactId>maven-surefire-plugin</artifactId> + <configuration> + <forkMode>pertest</forkMode> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-codegen-plugin</artifactId> + <version>${cxf-version}</version> + <executions> + <execution> + <id>generate-test-sources</id> + <phase>generate-sources</phase> + <configuration> + <testSourceRoot>${basedir}/target/generated/src/test/java</testSourceRoot> + <wsdlOptions> + <wsdlOption> + <wsdl> + ${basedir}/src/test/resources/wsdl/CustomerService-1.0.0.wsdl + </wsdl> + </wsdlOption> + <wsdlOption> + <wsdl> + ${basedir}/src/test/resources/wsdl/hello_world.wsdl + </wsdl> + </wsdlOption> + </wsdlOptions> + </configuration> + <goals> + <goal>wsdl2java</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> </project> diff --git a/tests/camel-itest/src/test/java/org/apache/camel/itest/ftp/SpringFileAntPathMatcherRemoteFileFilterTest.java b/tests/camel-itest/src/test/java/org/apache/camel/itest/ftp/SpringFileAntPathMatcherRemoteFileFilterTest.java new file mode 100644 index 0000000000000..bbd10b3085474 --- /dev/null +++ b/tests/camel-itest/src/test/java/org/apache/camel/itest/ftp/SpringFileAntPathMatcherRemoteFileFilterTest.java @@ -0,0 +1,87 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.itest.ftp; + +import java.io.File; + +import org.apache.camel.Endpoint; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.file.FileComponent; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.ftpserver.FtpServer; +import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor; +import org.apache.ftpserver.usermanager.PropertiesUserManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests; + +/** + * Unit testing FTP ant path matcher + */ +@ContextConfiguration +public class SpringFileAntPathMatcherRemoteFileFilterTest extends AbstractJUnit38SpringContextTests { + protected FtpServer ftpServer; + + protected String expectedBody = "Godday World"; + @Autowired + protected ProducerTemplate template; + @EndpointInject(name = "myFTPEndpoint") + protected Endpoint inputFTP; + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + public void testAntPatchMatherFilter() throws Exception { + result.expectedBodiesReceived(expectedBody); + + template.sendBodyAndHeader(inputFTP, "Hello World", FileComponent.HEADER_FILE_NAME, "hello.txt"); + template.sendBodyAndHeader(inputFTP, "Bye World", FileComponent.HEADER_FILE_NAME, "bye.xml"); + template.sendBodyAndHeader(inputFTP, "Bad world", FileComponent.HEADER_FILE_NAME, "subfolder/badday.txt"); + template.sendBodyAndHeader(inputFTP, "Day world", FileComponent.HEADER_FILE_NAME, "day.xml"); + template.sendBodyAndHeader(inputFTP, expectedBody, FileComponent.HEADER_FILE_NAME, "subfolder/foo/godday.txt"); + + result.assertIsSatisfied(); + } + + protected void setUp() throws Exception { + super.setUp(); + initFtpServer(); + ftpServer.start(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + ftpServer.stop(); + ftpServer = null; + } + + protected void initFtpServer() throws Exception { + ftpServer = new FtpServer(); + + // setup user management to read our users.properties and use clear text passwords + PropertiesUserManager uman = new PropertiesUserManager(); + uman.setFile(new File("./src/test/resources/users.properties").getAbsoluteFile()); + uman.setPasswordEncryptor(new ClearTextPasswordEncryptor()); + uman.setAdminName("admin"); + uman.configure(); + ftpServer.setUserManager(uman); + + ftpServer.getListener("default").setPort(20123); + } + +} + diff --git a/tests/camel-itest/src/test/resources/log4j.properties b/tests/camel-itest/src/test/resources/log4j.properties index 1c9dcf7ef08b3..bcfdb12735907 100644 --- a/tests/camel-itest/src/test/resources/log4j.properties +++ b/tests/camel-itest/src/test/resources/log4j.properties @@ -22,7 +22,9 @@ log4j.rootLogger=WARN, out log4j.logger.org.springframework=WARN log4j.logger.org.apache.activemq=WARN +#log4j.logger.org.apache.camel=TRACE #log4j.logger.org.apache.camel=DEBUG +#log4j.logger.org.apache.camel.component.file=TRACE # CONSOLE appender not used by default log4j.appender.stdout=org.apache.log4j.ConsoleAppender diff --git a/tests/camel-itest/src/test/resources/org/apache/camel/itest/ftp/SpringFileAntPathMatcherRemoteFileFilterTest-context.xml b/tests/camel-itest/src/test/resources/org/apache/camel/itest/ftp/SpringFileAntPathMatcherRemoteFileFilterTest-context.xml new file mode 100644 index 0000000000000..04299ccf62379 --- /dev/null +++ b/tests/camel-itest/src/test/resources/org/apache/camel/itest/ftp/SpringFileAntPathMatcherRemoteFileFilterTest-context.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd + http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring.xsd + "> + + <!-- START SNIPPET: example --> + <camelContext xmlns="http://activemq.apache.org/camel/schema/spring"> + <template id="camelTemplate"/> + + <!-- use myFilter as filter to allow setting ANT paths for which files to scan for --> + <endpoint id="myFTPEndpoint" uri="ftp://admin@localhost:20123/antpath?password=admin&amp;recursive=true&amp;delay=10000&amp;initialDelay=2000&amp;filter=#myAntFilter"/> + + <route> + <from ref="myFTPEndpoint"/> + <to uri="mock:result"/> + </route> + </camelContext> + + <!-- we use the AntPathMatcherRemoteFileFilter to use ant paths for includes and exlucde --> + <bean id="myAntFilter" class="org.apache.camel.component.file.remote.AntPathMatcherRemoteFileFilter"> + <!-- include and file in the subfolder that has day in the name --> + <property name="includes" value="**/subfolder/**/*day*"/> + <!-- exclude all files with bad in name or .xml files. Use comma to seperate multiple excludes --> + <property name="excludes" value="**/*bad*,**/*.xml"/> + </bean> + <!-- END SNIPPET: example --> + +</beans> diff --git a/tests/camel-itest/src/test/resources/users.properties b/tests/camel-itest/src/test/resources/users.properties new file mode 100644 index 0000000000000..b4f2e17164ed0 --- /dev/null +++ b/tests/camel-itest/src/test/resources/users.properties @@ -0,0 +1,12 @@ +ftpserver.user.admin +ftpserver.user.admin.userpassword=admin +ftpserver.user.admin.homedirectory=./res/home +ftpserver.user.admin.writepermission=true +ftpserver.user.scott +ftpserver.user.scott.userpassword=tiger +ftpserver.user.scott.homedirectory=./res/home +ftpserver.user.scott.writepermission=true +ftpserver.user.dummy +ftpserver.user.dummy.userpassword=foo +ftpserver.user.dummy.homedirectory=./res/home +ftpserver.user.dummy.writepermission=false
ad735cd7885d978288e2800b47fa7fdc3bca5f71
kotlin
Split ProtoBuf.Callable to three messages:- constructor, function, property--Serialize both at the moment, will drop the old one after bootstrap-
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/serialization/src/org/jetbrains/kotlin/serialization/DescriptorSerializer.java b/compiler/serialization/src/org/jetbrains/kotlin/serialization/DescriptorSerializer.java index 04737697ae59d..c3b0764874674 100644 --- a/compiler/serialization/src/org/jetbrains/kotlin/serialization/DescriptorSerializer.java +++ b/compiler/serialization/src/org/jetbrains/kotlin/serialization/DescriptorSerializer.java @@ -129,6 +129,10 @@ public ProtoBuf.Class.Builder classProto(@NotNull ClassDescriptor classDescripto } } + for (ConstructorDescriptor descriptor : classDescriptor.getConstructors()) { + builder.addConstructor(constructorProto(descriptor)); + } + for (ConstructorDescriptor constructorDescriptor : getSecondaryConstructors(classDescriptor)) { builder.addSecondaryConstructor(callableProto(constructorDescriptor)); } @@ -138,6 +142,13 @@ public ProtoBuf.Class.Builder classProto(@NotNull ClassDescriptor classDescripto CallableMemberDescriptor member = (CallableMemberDescriptor) descriptor; if (member.getKind() == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) continue; builder.addMember(callableProto(member)); + + if (descriptor instanceof PropertyDescriptor) { + builder.addProperty(propertyProto((PropertyDescriptor) descriptor)); + } + else if (descriptor instanceof FunctionDescriptor) { + builder.addFunction(functionProto((FunctionDescriptor) descriptor)); + } } } @@ -161,6 +172,143 @@ public ProtoBuf.Class.Builder classProto(@NotNull ClassDescriptor classDescripto return builder; } + @NotNull + public ProtoBuf.Property.Builder propertyProto(@NotNull PropertyDescriptor descriptor) { + ProtoBuf.Property.Builder builder = ProtoBuf.Property.newBuilder(); + + DescriptorSerializer local = createChildSerializer(); + + boolean hasGetter = false; + boolean hasSetter = false; + boolean lateInit = descriptor.isLateInit(); + boolean isConst = descriptor.isConst(); + + ConstantValue<?> compileTimeConstant = descriptor.getCompileTimeInitializer(); + boolean hasConstant = !(compileTimeConstant == null || compileTimeConstant instanceof NullValue); + + boolean hasAnnotations = !descriptor.getAnnotations().getAllAnnotations().isEmpty(); + + int propertyFlags = Flags.getAccessorFlags( + hasAnnotations, + descriptor.getVisibility(), + descriptor.getModality(), + false + ); + + PropertyGetterDescriptor getter = descriptor.getGetter(); + if (getter != null) { + hasGetter = true; + int accessorFlags = getAccessorFlags(getter); + if (accessorFlags != propertyFlags) { + builder.setGetterFlags(accessorFlags); + } + } + + PropertySetterDescriptor setter = descriptor.getSetter(); + if (setter != null) { + hasSetter = true; + int accessorFlags = getAccessorFlags(setter); + if (accessorFlags != propertyFlags) { + builder.setSetterFlags(accessorFlags); + } + + if (!setter.isDefault()) { + for (ValueParameterDescriptor valueParameterDescriptor : setter.getValueParameters()) { + builder.setSetterValueParameter(local.valueParameter(valueParameterDescriptor)); + } + } + } + + builder.setFlags(Flags.getPropertyFlags( + hasAnnotations, + descriptor.getVisibility(), + descriptor.getModality(), + descriptor.getKind(), + descriptor.isVar(), + hasGetter, + hasSetter, + hasConstant, + isConst, + lateInit + )); + + builder.setName(getSimpleNameIndex(descriptor.getName())); + + builder.setReturnType(local.type(descriptor.getType())); + + for (TypeParameterDescriptor typeParameterDescriptor : descriptor.getTypeParameters()) { + builder.addTypeParameter(local.typeParameter(typeParameterDescriptor)); + } + + ReceiverParameterDescriptor receiverParameter = descriptor.getExtensionReceiverParameter(); + if (receiverParameter != null) { + builder.setReceiverType(local.type(receiverParameter.getType())); + } + + extension.serializeProperty(descriptor, builder); + + return builder; + } + + @NotNull + public ProtoBuf.Function.Builder functionProto(@NotNull FunctionDescriptor descriptor) { + ProtoBuf.Function.Builder builder = ProtoBuf.Function.newBuilder(); + + DescriptorSerializer local = createChildSerializer(); + + builder.setFlags(Flags.getFunctionFlags( + hasAnnotations(descriptor), + descriptor.getVisibility(), + descriptor.getModality(), + descriptor.getKind(), + descriptor.isOperator(), + descriptor.isInfix() + )); + + builder.setName(getSimpleNameIndex(descriptor.getName())); + + //noinspection ConstantConditions + builder.setReturnType(local.type(descriptor.getReturnType())); + + for (TypeParameterDescriptor typeParameterDescriptor : descriptor.getTypeParameters()) { + builder.addTypeParameter(local.typeParameter(typeParameterDescriptor)); + } + + ReceiverParameterDescriptor receiverParameter = descriptor.getExtensionReceiverParameter(); + if (receiverParameter != null) { + builder.setReceiverType(local.type(receiverParameter.getType())); + } + + for (ValueParameterDescriptor valueParameterDescriptor : descriptor.getValueParameters()) { + builder.addValueParameter(local.valueParameter(valueParameterDescriptor)); + } + + extension.serializeFunction(descriptor, builder); + + return builder; + } + + @NotNull + public ProtoBuf.Constructor.Builder constructorProto(@NotNull ConstructorDescriptor descriptor) { + ProtoBuf.Constructor.Builder builder = ProtoBuf.Constructor.newBuilder(); + + DescriptorSerializer local = createChildSerializer(); + + builder.setFlags(Flags.getConstructorFlags( + hasAnnotations(descriptor), + descriptor.getVisibility(), + !descriptor.isPrimary() + )); + + for (ValueParameterDescriptor valueParameterDescriptor : descriptor.getValueParameters()) { + builder.addValueParameter(local.valueParameter(valueParameterDescriptor)); + } + + extension.serializeConstructor(descriptor, builder); + + return builder; + } + @NotNull public ProtoBuf.Callable.Builder callableProto(@NotNull CallableMemberDescriptor descriptor) { ProtoBuf.Callable.Builder builder = ProtoBuf.Callable.newBuilder(); diff --git a/compiler/serialization/src/org/jetbrains/kotlin/serialization/SerializerExtension.java b/compiler/serialization/src/org/jetbrains/kotlin/serialization/SerializerExtension.java index bd39ef66a9b92..239cebcf914dc 100644 --- a/compiler/serialization/src/org/jetbrains/kotlin/serialization/SerializerExtension.java +++ b/compiler/serialization/src/org/jetbrains/kotlin/serialization/SerializerExtension.java @@ -17,10 +17,7 @@ package org.jetbrains.kotlin.serialization; import org.jetbrains.annotations.NotNull; -import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor; -import org.jetbrains.kotlin.descriptors.ClassDescriptor; -import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor; -import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor; +import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.types.JetType; import java.util.Collection; @@ -35,6 +32,15 @@ public void serializeClass(@NotNull ClassDescriptor descriptor, @NotNull ProtoBu public void serializePackage(@NotNull Collection<PackageFragmentDescriptor> packageFragments, @NotNull ProtoBuf.Package.Builder proto) { } + public void serializeConstructor(@NotNull ConstructorDescriptor descriptor, @NotNull ProtoBuf.Constructor.Builder proto) { + } + + public void serializeFunction(@NotNull FunctionDescriptor descriptor, @NotNull ProtoBuf.Function.Builder proto) { + } + + public void serializeProperty(@NotNull PropertyDescriptor descriptor, @NotNull ProtoBuf.Property.Builder proto) { + } + public void serializeCallable(@NotNull CallableMemberDescriptor callable, @NotNull ProtoBuf.Callable.Builder proto) { } diff --git a/compiler/tests/org/jetbrains/kotlin/serialization/DebugProtoBuf.java b/compiler/tests/org/jetbrains/kotlin/serialization/DebugProtoBuf.java index de77c853f48f9..7ed0294b96ff3 100644 --- a/compiler/tests/org/jetbrains/kotlin/serialization/DebugProtoBuf.java +++ b/compiler/tests/org/jetbrains/kotlin/serialization/DebugProtoBuf.java @@ -8777,6 +8777,81 @@ org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getSupertypeOrBui */ int getNestedClassName(int index); + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> + getConstructorList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor getConstructor(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + int getConstructorCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> + getConstructorOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder getConstructorOrBuilder( + int index); + + // repeated .org.jetbrains.kotlin.serialization.Function function = 9; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> + getFunctionList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function getFunction(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + int getFunctionCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> + getFunctionOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder getFunctionOrBuilder( + int index); + + // repeated .org.jetbrains.kotlin.serialization.Property property = 10; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> + getPropertyList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property getProperty(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + int getPropertyCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> + getPropertyOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder getPropertyOrBuilder( + int index); + // repeated .org.jetbrains.kotlin.serialization.Callable member = 11; /** * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> @@ -8970,18 +9045,42 @@ private Class( input.popLimit(limit); break; } - case 90: { + case 66: { if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) { - member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(); + constructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor>(); mutable_bitField0_ |= 0x00000040; } + constructor_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.PARSER, extensionRegistry)); + break; + } + case 74: { + if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { + function_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function>(); + mutable_bitField0_ |= 0x00000080; + } + function_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.PARSER, extensionRegistry)); + break; + } + case 82: { + if (!((mutable_bitField0_ & 0x00000100) == 0x00000100)) { + property_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property>(); + mutable_bitField0_ |= 0x00000100; + } + property_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.PARSER, extensionRegistry)); + break; + } + case 90: { + if (!((mutable_bitField0_ & 0x00000200) == 0x00000200)) { + member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(); + mutable_bitField0_ |= 0x00000200; + } member_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.PARSER, extensionRegistry)); break; } case 96: { - if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { + if (!((mutable_bitField0_ & 0x00000400) == 0x00000400)) { enumEntry_ = new java.util.ArrayList<java.lang.Integer>(); - mutable_bitField0_ |= 0x00000080; + mutable_bitField0_ |= 0x00000400; } enumEntry_.add(input.readInt32()); break; @@ -8989,9 +9088,9 @@ private Class( case 98: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); - if (!((mutable_bitField0_ & 0x00000080) == 0x00000080) && input.getBytesUntilLimit() > 0) { + if (!((mutable_bitField0_ & 0x00000400) == 0x00000400) && input.getBytesUntilLimit() > 0) { enumEntry_ = new java.util.ArrayList<java.lang.Integer>(); - mutable_bitField0_ |= 0x00000080; + mutable_bitField0_ |= 0x00000400; } while (input.getBytesUntilLimit() > 0) { enumEntry_.add(input.readInt32()); @@ -9013,9 +9112,9 @@ private Class( break; } case 114: { - if (!((mutable_bitField0_ & 0x00000200) == 0x00000200)) { + if (!((mutable_bitField0_ & 0x00001000) == 0x00001000)) { secondaryConstructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(); - mutable_bitField0_ |= 0x00000200; + mutable_bitField0_ |= 0x00001000; } secondaryConstructor_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.PARSER, extensionRegistry)); break; @@ -9038,12 +9137,21 @@ private Class( nestedClassName_ = java.util.Collections.unmodifiableList(nestedClassName_); } if (((mutable_bitField0_ & 0x00000040) == 0x00000040)) { - member_ = java.util.Collections.unmodifiableList(member_); + constructor_ = java.util.Collections.unmodifiableList(constructor_); } if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) { - enumEntry_ = java.util.Collections.unmodifiableList(enumEntry_); + function_ = java.util.Collections.unmodifiableList(function_); + } + if (((mutable_bitField0_ & 0x00000100) == 0x00000100)) { + property_ = java.util.Collections.unmodifiableList(property_); } if (((mutable_bitField0_ & 0x00000200) == 0x00000200)) { + member_ = java.util.Collections.unmodifiableList(member_); + } + if (((mutable_bitField0_ & 0x00000400) == 0x00000400)) { + enumEntry_ = java.util.Collections.unmodifiableList(enumEntry_); + } + if (((mutable_bitField0_ & 0x00001000) == 0x00001000)) { secondaryConstructor_ = java.util.Collections.unmodifiableList(secondaryConstructor_); } this.unknownFields = unknownFields.build(); @@ -9984,6 +10092,114 @@ public int getNestedClassName(int index) { } private int nestedClassNameMemoizedSerializedSize = -1; + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8; + public static final int CONSTRUCTOR_FIELD_NUMBER = 8; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> constructor_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> getConstructorList() { + return constructor_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> + getConstructorOrBuilderList() { + return constructor_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public int getConstructorCount() { + return constructor_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor getConstructor(int index) { + return constructor_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder getConstructorOrBuilder( + int index) { + return constructor_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Function function = 9; + public static final int FUNCTION_FIELD_NUMBER = 9; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> function_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> getFunctionList() { + return function_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> + getFunctionOrBuilderList() { + return function_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public int getFunctionCount() { + return function_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function getFunction(int index) { + return function_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder getFunctionOrBuilder( + int index) { + return function_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Property property = 10; + public static final int PROPERTY_FIELD_NUMBER = 10; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> property_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> getPropertyList() { + return property_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> + getPropertyOrBuilderList() { + return property_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public int getPropertyCount() { + return property_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property getProperty(int index) { + return property_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder getPropertyOrBuilder( + int index) { + return property_.get(index); + } + // repeated .org.jetbrains.kotlin.serialization.Callable member = 11; public static final int MEMBER_FIELD_NUMBER = 11; private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> member_; @@ -10121,6 +10337,9 @@ private void initFields() { typeParameter_ = java.util.Collections.emptyList(); supertype_ = java.util.Collections.emptyList(); nestedClassName_ = java.util.Collections.emptyList(); + constructor_ = java.util.Collections.emptyList(); + function_ = java.util.Collections.emptyList(); + property_ = java.util.Collections.emptyList(); member_ = java.util.Collections.emptyList(); enumEntry_ = java.util.Collections.emptyList(); primaryConstructor_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); @@ -10147,6 +10366,24 @@ public final boolean isInitialized() { return false; } } + for (int i = 0; i < getConstructorCount(); i++) { + if (!getConstructor(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getFunctionCount(); i++) { + if (!getFunction(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getPropertyCount(); i++) { + if (!getProperty(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } for (int i = 0; i < getMemberCount(); i++) { if (!getMember(i).isInitialized()) { memoizedIsInitialized = 0; @@ -10201,6 +10438,15 @@ public void writeTo(com.google.protobuf.CodedOutputStream output) for (int i = 0; i < nestedClassName_.size(); i++) { output.writeInt32NoTag(nestedClassName_.get(i)); } + for (int i = 0; i < constructor_.size(); i++) { + output.writeMessage(8, constructor_.get(i)); + } + for (int i = 0; i < function_.size(); i++) { + output.writeMessage(9, function_.get(i)); + } + for (int i = 0; i < property_.size(); i++) { + output.writeMessage(10, property_.get(i)); + } for (int i = 0; i < member_.size(); i++) { output.writeMessage(11, member_.get(i)); } @@ -10261,6 +10507,18 @@ public int getSerializedSize() { } nestedClassNameMemoizedSerializedSize = dataSize; } + for (int i = 0; i < constructor_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(8, constructor_.get(i)); + } + for (int i = 0; i < function_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(9, function_.get(i)); + } + for (int i = 0; i < property_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(10, property_.get(i)); + } for (int i = 0; i < member_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(11, member_.get(i)); @@ -10398,6 +10656,9 @@ private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getTypeParameterFieldBuilder(); getSupertypeFieldBuilder(); + getConstructorFieldBuilder(); + getFunctionFieldBuilder(); + getPropertyFieldBuilder(); getMemberFieldBuilder(); getPrimaryConstructorFieldBuilder(); getSecondaryConstructorFieldBuilder(); @@ -10429,23 +10690,41 @@ public Builder clear() { } nestedClassName_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); + if (constructorBuilder_ == null) { + constructor_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000040); + } else { + constructorBuilder_.clear(); + } + if (functionBuilder_ == null) { + function_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000080); + } else { + functionBuilder_.clear(); + } + if (propertyBuilder_ == null) { + property_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000100); + } else { + propertyBuilder_.clear(); + } if (memberBuilder_ == null) { member_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000040); + bitField0_ = (bitField0_ & ~0x00000200); } else { memberBuilder_.clear(); } enumEntry_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000080); + bitField0_ = (bitField0_ & ~0x00000400); if (primaryConstructorBuilder_ == null) { primaryConstructor_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); } else { primaryConstructorBuilder_.clear(); } - bitField0_ = (bitField0_ & ~0x00000100); + bitField0_ = (bitField0_ & ~0x00000800); if (secondaryConstructorBuilder_ == null) { secondaryConstructor_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000200); + bitField0_ = (bitField0_ & ~0x00001000); } else { secondaryConstructorBuilder_.clear(); } @@ -10512,21 +10791,48 @@ public org.jetbrains.kotlin.serialization.DebugProtoBuf.Class buildPartial() { bitField0_ = (bitField0_ & ~0x00000020); } result.nestedClassName_ = nestedClassName_; - if (memberBuilder_ == null) { + if (constructorBuilder_ == null) { if (((bitField0_ & 0x00000040) == 0x00000040)) { - member_ = java.util.Collections.unmodifiableList(member_); + constructor_ = java.util.Collections.unmodifiableList(constructor_); bitField0_ = (bitField0_ & ~0x00000040); } + result.constructor_ = constructor_; + } else { + result.constructor_ = constructorBuilder_.build(); + } + if (functionBuilder_ == null) { + if (((bitField0_ & 0x00000080) == 0x00000080)) { + function_ = java.util.Collections.unmodifiableList(function_); + bitField0_ = (bitField0_ & ~0x00000080); + } + result.function_ = function_; + } else { + result.function_ = functionBuilder_.build(); + } + if (propertyBuilder_ == null) { + if (((bitField0_ & 0x00000100) == 0x00000100)) { + property_ = java.util.Collections.unmodifiableList(property_); + bitField0_ = (bitField0_ & ~0x00000100); + } + result.property_ = property_; + } else { + result.property_ = propertyBuilder_.build(); + } + if (memberBuilder_ == null) { + if (((bitField0_ & 0x00000200) == 0x00000200)) { + member_ = java.util.Collections.unmodifiableList(member_); + bitField0_ = (bitField0_ & ~0x00000200); + } result.member_ = member_; } else { result.member_ = memberBuilder_.build(); } - if (((bitField0_ & 0x00000080) == 0x00000080)) { + if (((bitField0_ & 0x00000400) == 0x00000400)) { enumEntry_ = java.util.Collections.unmodifiableList(enumEntry_); - bitField0_ = (bitField0_ & ~0x00000080); + bitField0_ = (bitField0_ & ~0x00000400); } result.enumEntry_ = enumEntry_; - if (((from_bitField0_ & 0x00000100) == 0x00000100)) { + if (((from_bitField0_ & 0x00000800) == 0x00000800)) { to_bitField0_ |= 0x00000008; } if (primaryConstructorBuilder_ == null) { @@ -10535,9 +10841,9 @@ public org.jetbrains.kotlin.serialization.DebugProtoBuf.Class buildPartial() { result.primaryConstructor_ = primaryConstructorBuilder_.build(); } if (secondaryConstructorBuilder_ == null) { - if (((bitField0_ & 0x00000200) == 0x00000200)) { + if (((bitField0_ & 0x00001000) == 0x00001000)) { secondaryConstructor_ = java.util.Collections.unmodifiableList(secondaryConstructor_); - bitField0_ = (bitField0_ & ~0x00000200); + bitField0_ = (bitField0_ & ~0x00001000); } result.secondaryConstructor_ = secondaryConstructor_; } else { @@ -10630,11 +10936,89 @@ public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class } onChanged(); } + if (constructorBuilder_ == null) { + if (!other.constructor_.isEmpty()) { + if (constructor_.isEmpty()) { + constructor_ = other.constructor_; + bitField0_ = (bitField0_ & ~0x00000040); + } else { + ensureConstructorIsMutable(); + constructor_.addAll(other.constructor_); + } + onChanged(); + } + } else { + if (!other.constructor_.isEmpty()) { + if (constructorBuilder_.isEmpty()) { + constructorBuilder_.dispose(); + constructorBuilder_ = null; + constructor_ = other.constructor_; + bitField0_ = (bitField0_ & ~0x00000040); + constructorBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getConstructorFieldBuilder() : null; + } else { + constructorBuilder_.addAllMessages(other.constructor_); + } + } + } + if (functionBuilder_ == null) { + if (!other.function_.isEmpty()) { + if (function_.isEmpty()) { + function_ = other.function_; + bitField0_ = (bitField0_ & ~0x00000080); + } else { + ensureFunctionIsMutable(); + function_.addAll(other.function_); + } + onChanged(); + } + } else { + if (!other.function_.isEmpty()) { + if (functionBuilder_.isEmpty()) { + functionBuilder_.dispose(); + functionBuilder_ = null; + function_ = other.function_; + bitField0_ = (bitField0_ & ~0x00000080); + functionBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getFunctionFieldBuilder() : null; + } else { + functionBuilder_.addAllMessages(other.function_); + } + } + } + if (propertyBuilder_ == null) { + if (!other.property_.isEmpty()) { + if (property_.isEmpty()) { + property_ = other.property_; + bitField0_ = (bitField0_ & ~0x00000100); + } else { + ensurePropertyIsMutable(); + property_.addAll(other.property_); + } + onChanged(); + } + } else { + if (!other.property_.isEmpty()) { + if (propertyBuilder_.isEmpty()) { + propertyBuilder_.dispose(); + propertyBuilder_ = null; + property_ = other.property_; + bitField0_ = (bitField0_ & ~0x00000100); + propertyBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getPropertyFieldBuilder() : null; + } else { + propertyBuilder_.addAllMessages(other.property_); + } + } + } if (memberBuilder_ == null) { if (!other.member_.isEmpty()) { if (member_.isEmpty()) { member_ = other.member_; - bitField0_ = (bitField0_ & ~0x00000040); + bitField0_ = (bitField0_ & ~0x00000200); } else { ensureMemberIsMutable(); member_.addAll(other.member_); @@ -10647,7 +11031,7 @@ public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class memberBuilder_.dispose(); memberBuilder_ = null; member_ = other.member_; - bitField0_ = (bitField0_ & ~0x00000040); + bitField0_ = (bitField0_ & ~0x00000200); memberBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getMemberFieldBuilder() : null; @@ -10659,7 +11043,7 @@ public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class if (!other.enumEntry_.isEmpty()) { if (enumEntry_.isEmpty()) { enumEntry_ = other.enumEntry_; - bitField0_ = (bitField0_ & ~0x00000080); + bitField0_ = (bitField0_ & ~0x00000400); } else { ensureEnumEntryIsMutable(); enumEntry_.addAll(other.enumEntry_); @@ -10673,7 +11057,7 @@ public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class if (!other.secondaryConstructor_.isEmpty()) { if (secondaryConstructor_.isEmpty()) { secondaryConstructor_ = other.secondaryConstructor_; - bitField0_ = (bitField0_ & ~0x00000200); + bitField0_ = (bitField0_ & ~0x00001000); } else { ensureSecondaryConstructorIsMutable(); secondaryConstructor_.addAll(other.secondaryConstructor_); @@ -10686,7 +11070,7 @@ public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class secondaryConstructorBuilder_.dispose(); secondaryConstructorBuilder_ = null; secondaryConstructor_ = other.secondaryConstructor_; - bitField0_ = (bitField0_ & ~0x00000200); + bitField0_ = (bitField0_ & ~0x00001000); secondaryConstructorBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getSecondaryConstructorFieldBuilder() : null; @@ -10717,6 +11101,24 @@ public final boolean isInitialized() { return false; } } + for (int i = 0; i < getConstructorCount(); i++) { + if (!getConstructor(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getFunctionCount(); i++) { + if (!getFunction(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getPropertyCount(); i++) { + if (!getProperty(i).isInitialized()) { + + return false; + } + } for (int i = 0; i < getMemberCount(); i++) { if (!getMember(i).isInitialized()) { @@ -11442,1415 +11844,7666 @@ public Builder clearNestedClassName() { return this; } - // repeated .org.jetbrains.kotlin.serialization.Callable member = 11; - private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> member_ = + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> constructor_ = java.util.Collections.emptyList(); - private void ensureMemberIsMutable() { + private void ensureConstructorIsMutable() { if (!((bitField0_ & 0x00000040) == 0x00000040)) { - member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(member_); + constructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor>(constructor_); bitField0_ |= 0x00000040; } } private com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> memberBuilder_; + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> constructorBuilder_; /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> getMemberList() { - if (memberBuilder_ == null) { - return java.util.Collections.unmodifiableList(member_); + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> getConstructorList() { + if (constructorBuilder_ == null) { + return java.util.Collections.unmodifiableList(constructor_); } else { - return memberBuilder_.getMessageList(); + return constructorBuilder_.getMessageList(); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public int getMemberCount() { - if (memberBuilder_ == null) { - return member_.size(); + public int getConstructorCount() { + if (constructorBuilder_ == null) { + return constructor_.size(); } else { - return memberBuilder_.getCount(); + return constructorBuilder_.getCount(); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getMember(int index) { - if (memberBuilder_ == null) { - return member_.get(index); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor getConstructor(int index) { + if (constructorBuilder_ == null) { + return constructor_.get(index); } else { - return memberBuilder_.getMessage(index); + return constructorBuilder_.getMessage(index); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder setMember( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (memberBuilder_ == null) { + public Builder setConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor value) { + if (constructorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.set(index, value); + ensureConstructorIsMutable(); + constructor_.set(index, value); onChanged(); } else { - memberBuilder_.setMessage(index, value); + constructorBuilder_.setMessage(index, value); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder setMember( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - member_.set(index, builderForValue.build()); + public Builder setConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder builderForValue) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + constructor_.set(index, builderForValue.build()); onChanged(); } else { - memberBuilder_.setMessage(index, builderForValue.build()); + constructorBuilder_.setMessage(index, builderForValue.build()); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addMember(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (memberBuilder_ == null) { + public Builder addConstructor(org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor value) { + if (constructorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.add(value); + ensureConstructorIsMutable(); + constructor_.add(value); onChanged(); } else { - memberBuilder_.addMessage(value); + constructorBuilder_.addMessage(value); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addMember( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (memberBuilder_ == null) { + public Builder addConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor value) { + if (constructorBuilder_ == null) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.add(index, value); + ensureConstructorIsMutable(); + constructor_.add(index, value); onChanged(); } else { - memberBuilder_.addMessage(index, value); + constructorBuilder_.addMessage(index, value); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addMember( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - member_.add(builderForValue.build()); + public Builder addConstructor( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder builderForValue) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + constructor_.add(builderForValue.build()); onChanged(); } else { - memberBuilder_.addMessage(builderForValue.build()); + constructorBuilder_.addMessage(builderForValue.build()); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addMember( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - member_.add(index, builderForValue.build()); + public Builder addConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder builderForValue) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + constructor_.add(index, builderForValue.build()); onChanged(); } else { - memberBuilder_.addMessage(index, builderForValue.build()); + constructorBuilder_.addMessage(index, builderForValue.build()); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addAllMember( - java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> values) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - super.addAll(values, member_); + public Builder addAllConstructor( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> values) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + super.addAll(values, constructor_); onChanged(); } else { - memberBuilder_.addAllMessages(values); + constructorBuilder_.addAllMessages(values); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder clearMember() { - if (memberBuilder_ == null) { - member_ = java.util.Collections.emptyList(); + public Builder clearConstructor() { + if (constructorBuilder_ == null) { + constructor_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); onChanged(); } else { - memberBuilder_.clear(); + constructorBuilder_.clear(); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder removeMember(int index) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - member_.remove(index); + public Builder removeConstructor(int index) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + constructor_.remove(index); onChanged(); } else { - memberBuilder_.remove(index); + constructorBuilder_.remove(index); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder getMemberBuilder( + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder getConstructorBuilder( int index) { - return getMemberFieldBuilder().getBuilder(index); + return getConstructorFieldBuilder().getBuilder(index); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getMemberOrBuilder( + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder getConstructorOrBuilder( int index) { - if (memberBuilder_ == null) { - return member_.get(index); } else { - return memberBuilder_.getMessageOrBuilder(index); + if (constructorBuilder_ == null) { + return constructor_.get(index); } else { + return constructorBuilder_.getMessageOrBuilder(index); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> - getMemberOrBuilderList() { - if (memberBuilder_ != null) { - return memberBuilder_.getMessageOrBuilderList(); + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> + getConstructorOrBuilderList() { + if (constructorBuilder_ != null) { + return constructorBuilder_.getMessageOrBuilderList(); } else { - return java.util.Collections.unmodifiableList(member_); + return java.util.Collections.unmodifiableList(constructor_); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addMemberBuilder() { - return getMemberFieldBuilder().addBuilder( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder addConstructorBuilder() { + return getConstructorFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.getDefaultInstance()); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addMemberBuilder( + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder addConstructorBuilder( int index) { - return getMemberFieldBuilder().addBuilder( - index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + return getConstructorFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.getDefaultInstance()); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder> - getMemberBuilderList() { - return getMemberFieldBuilder().getBuilderList(); + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder> + getConstructorBuilderList() { + return getConstructorFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> - getMemberFieldBuilder() { - if (memberBuilder_ == null) { - memberBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder>( - member_, + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> + getConstructorFieldBuilder() { + if (constructorBuilder_ == null) { + constructorBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder>( + constructor_, ((bitField0_ & 0x00000040) == 0x00000040), getParentForChildren(), isClean()); - member_ = null; + constructor_ = null; } - return memberBuilder_; + return constructorBuilder_; } - // repeated int32 enum_entry = 12 [packed = true]; - private java.util.List<java.lang.Integer> enumEntry_ = java.util.Collections.emptyList(); - private void ensureEnumEntryIsMutable() { + // repeated .org.jetbrains.kotlin.serialization.Function function = 9; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> function_ = + java.util.Collections.emptyList(); + private void ensureFunctionIsMutable() { if (!((bitField0_ & 0x00000080) == 0x00000080)) { - enumEntry_ = new java.util.ArrayList<java.lang.Integer>(enumEntry_); + function_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function>(function_); bitField0_ |= 0x00000080; } } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> functionBuilder_; + /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public java.util.List<java.lang.Integer> - getEnumEntryList() { - return java.util.Collections.unmodifiableList(enumEntry_); + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> getFunctionList() { + if (functionBuilder_ == null) { + return java.util.Collections.unmodifiableList(function_); + } else { + return functionBuilder_.getMessageList(); + } } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public int getEnumEntryCount() { - return enumEntry_.size(); + public int getFunctionCount() { + if (functionBuilder_ == null) { + return function_.size(); + } else { + return functionBuilder_.getCount(); + } } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public int getEnumEntry(int index) { - return enumEntry_.get(index); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function getFunction(int index) { + if (functionBuilder_ == null) { + return function_.get(index); + } else { + return functionBuilder_.getMessage(index); + } } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder setEnumEntry( - int index, int value) { - ensureEnumEntryIsMutable(); - enumEntry_.set(index, value); - onChanged(); + public Builder setFunction( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function value) { + if (functionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.set(index, value); + onChanged(); + } else { + functionBuilder_.setMessage(index, value); + } return this; } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder addEnumEntry(int value) { - ensureEnumEntryIsMutable(); - enumEntry_.add(value); - onChanged(); + public Builder setFunction( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder builderForValue) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + function_.set(index, builderForValue.build()); + onChanged(); + } else { + functionBuilder_.setMessage(index, builderForValue.build()); + } return this; } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder addAllEnumEntry( - java.lang.Iterable<? extends java.lang.Integer> values) { - ensureEnumEntryIsMutable(); - super.addAll(values, enumEntry_); - onChanged(); + public Builder addFunction(org.jetbrains.kotlin.serialization.DebugProtoBuf.Function value) { + if (functionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.add(value); + onChanged(); + } else { + functionBuilder_.addMessage(value); + } return this; } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder clearEnumEntry() { - enumEntry_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000080); - onChanged(); + public Builder addFunction( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function value) { + if (functionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.add(index, value); + onChanged(); + } else { + functionBuilder_.addMessage(index, value); + } return this; } - - // optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13; - private org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor primaryConstructor_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); - private com.google.protobuf.SingleFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructorOrBuilder> primaryConstructorBuilder_; - /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> - */ - public boolean hasPrimaryConstructor() { - return ((bitField0_ & 0x00000100) == 0x00000100); - } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor getPrimaryConstructor() { - if (primaryConstructorBuilder_ == null) { - return primaryConstructor_; + public Builder addFunction( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder builderForValue) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + function_.add(builderForValue.build()); + onChanged(); } else { - return primaryConstructorBuilder_.getMessage(); + functionBuilder_.addMessage(builderForValue.build()); } + return this; } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder setPrimaryConstructor(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor value) { - if (primaryConstructorBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - primaryConstructor_ = value; + public Builder addFunction( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder builderForValue) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + function_.add(index, builderForValue.build()); onChanged(); } else { - primaryConstructorBuilder_.setMessage(value); + functionBuilder_.addMessage(index, builderForValue.build()); } - bitField0_ |= 0x00000100; return this; } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder setPrimaryConstructor( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder builderForValue) { - if (primaryConstructorBuilder_ == null) { - primaryConstructor_ = builderForValue.build(); + public Builder addAllFunction( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> values) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + super.addAll(values, function_); onChanged(); } else { - primaryConstructorBuilder_.setMessage(builderForValue.build()); + functionBuilder_.addAllMessages(values); } - bitField0_ |= 0x00000100; return this; } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder mergePrimaryConstructor(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor value) { - if (primaryConstructorBuilder_ == null) { - if (((bitField0_ & 0x00000100) == 0x00000100) && - primaryConstructor_ != org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.getDefaultInstance()) { - primaryConstructor_ = - org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.newBuilder(primaryConstructor_).mergeFrom(value).buildPartial(); - } else { - primaryConstructor_ = value; - } + public Builder clearFunction() { + if (functionBuilder_ == null) { + function_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000080); onChanged(); } else { - primaryConstructorBuilder_.mergeFrom(value); + functionBuilder_.clear(); } - bitField0_ |= 0x00000100; return this; } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder clearPrimaryConstructor() { - if (primaryConstructorBuilder_ == null) { - primaryConstructor_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); + public Builder removeFunction(int index) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + function_.remove(index); onChanged(); } else { - primaryConstructorBuilder_.clear(); + functionBuilder_.remove(index); } - bitField0_ = (bitField0_ & ~0x00000100); return this; } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder getPrimaryConstructorBuilder() { - bitField0_ |= 0x00000100; - onChanged(); - return getPrimaryConstructorFieldBuilder().getBuilder(); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder getFunctionBuilder( + int index) { + return getFunctionFieldBuilder().getBuilder(index); } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructorOrBuilder getPrimaryConstructorOrBuilder() { - if (primaryConstructorBuilder_ != null) { - return primaryConstructorBuilder_.getMessageOrBuilder(); - } else { - return primaryConstructor_; + public org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder getFunctionOrBuilder( + int index) { + if (functionBuilder_ == null) { + return function_.get(index); } else { + return functionBuilder_.getMessageOrBuilder(index); } } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - private com.google.protobuf.SingleFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructorOrBuilder> - getPrimaryConstructorFieldBuilder() { - if (primaryConstructorBuilder_ == null) { - primaryConstructorBuilder_ = new com.google.protobuf.SingleFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructorOrBuilder>( - primaryConstructor_, - getParentForChildren(), - isClean()); - primaryConstructor_ = null; + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> + getFunctionOrBuilderList() { + if (functionBuilder_ != null) { + return functionBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(function_); } - return primaryConstructorBuilder_; } - - // repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14; - private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> secondaryConstructor_ = + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder addFunctionBuilder() { + return getFunctionFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder addFunctionBuilder( + int index) { + return getFunctionFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder> + getFunctionBuilderList() { + return getFunctionFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> + getFunctionFieldBuilder() { + if (functionBuilder_ == null) { + functionBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder>( + function_, + ((bitField0_ & 0x00000080) == 0x00000080), + getParentForChildren(), + isClean()); + function_ = null; + } + return functionBuilder_; + } + + // repeated .org.jetbrains.kotlin.serialization.Property property = 10; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> property_ = java.util.Collections.emptyList(); - private void ensureSecondaryConstructorIsMutable() { - if (!((bitField0_ & 0x00000200) == 0x00000200)) { - secondaryConstructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(secondaryConstructor_); - bitField0_ |= 0x00000200; + private void ensurePropertyIsMutable() { + if (!((bitField0_ & 0x00000100) == 0x00000100)) { + property_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property>(property_); + bitField0_ |= 0x00000100; } } private com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> secondaryConstructorBuilder_; + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> propertyBuilder_; /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> getSecondaryConstructorList() { - if (secondaryConstructorBuilder_ == null) { - return java.util.Collections.unmodifiableList(secondaryConstructor_); + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> getPropertyList() { + if (propertyBuilder_ == null) { + return java.util.Collections.unmodifiableList(property_); } else { - return secondaryConstructorBuilder_.getMessageList(); + return propertyBuilder_.getMessageList(); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public int getSecondaryConstructorCount() { - if (secondaryConstructorBuilder_ == null) { - return secondaryConstructor_.size(); + public int getPropertyCount() { + if (propertyBuilder_ == null) { + return property_.size(); } else { - return secondaryConstructorBuilder_.getCount(); + return propertyBuilder_.getCount(); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getSecondaryConstructor(int index) { - if (secondaryConstructorBuilder_ == null) { - return secondaryConstructor_.get(index); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property getProperty(int index) { + if (propertyBuilder_ == null) { + return property_.get(index); } else { - return secondaryConstructorBuilder_.getMessage(index); + return propertyBuilder_.getMessage(index); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder setSecondaryConstructor( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (secondaryConstructorBuilder_ == null) { + public Builder setProperty( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property value) { + if (propertyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.set(index, value); + ensurePropertyIsMutable(); + property_.set(index, value); onChanged(); } else { - secondaryConstructorBuilder_.setMessage(index, value); + propertyBuilder_.setMessage(index, value); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder setSecondaryConstructor( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (secondaryConstructorBuilder_ == null) { - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.set(index, builderForValue.build()); + public Builder setProperty( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder builderForValue) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + property_.set(index, builderForValue.build()); onChanged(); } else { - secondaryConstructorBuilder_.setMessage(index, builderForValue.build()); + propertyBuilder_.setMessage(index, builderForValue.build()); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder addSecondaryConstructor(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (secondaryConstructorBuilder_ == null) { + public Builder addProperty(org.jetbrains.kotlin.serialization.DebugProtoBuf.Property value) { + if (propertyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.add(value); + ensurePropertyIsMutable(); + property_.add(value); onChanged(); } else { - secondaryConstructorBuilder_.addMessage(value); + propertyBuilder_.addMessage(value); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder addSecondaryConstructor( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (secondaryConstructorBuilder_ == null) { + public Builder addProperty( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property value) { + if (propertyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.add(index, value); + ensurePropertyIsMutable(); + property_.add(index, value); onChanged(); } else { - secondaryConstructorBuilder_.addMessage(index, value); + propertyBuilder_.addMessage(index, value); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder addSecondaryConstructor( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (secondaryConstructorBuilder_ == null) { - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.add(builderForValue.build()); + public Builder addProperty( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder builderForValue) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + property_.add(builderForValue.build()); onChanged(); } else { - secondaryConstructorBuilder_.addMessage(builderForValue.build()); + propertyBuilder_.addMessage(builderForValue.build()); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder addSecondaryConstructor( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (secondaryConstructorBuilder_ == null) { - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.add(index, builderForValue.build()); + public Builder addProperty( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder builderForValue) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + property_.add(index, builderForValue.build()); onChanged(); } else { - secondaryConstructorBuilder_.addMessage(index, builderForValue.build()); + propertyBuilder_.addMessage(index, builderForValue.build()); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder addAllSecondaryConstructor( - java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> values) { - if (secondaryConstructorBuilder_ == null) { - ensureSecondaryConstructorIsMutable(); - super.addAll(values, secondaryConstructor_); + public Builder addAllProperty( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> values) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + super.addAll(values, property_); onChanged(); } else { - secondaryConstructorBuilder_.addAllMessages(values); + propertyBuilder_.addAllMessages(values); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder clearSecondaryConstructor() { - if (secondaryConstructorBuilder_ == null) { - secondaryConstructor_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000200); + public Builder clearProperty() { + if (propertyBuilder_ == null) { + property_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000100); onChanged(); } else { - secondaryConstructorBuilder_.clear(); + propertyBuilder_.clear(); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder removeSecondaryConstructor(int index) { - if (secondaryConstructorBuilder_ == null) { - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.remove(index); + public Builder removeProperty(int index) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + property_.remove(index); onChanged(); } else { - secondaryConstructorBuilder_.remove(index); + propertyBuilder_.remove(index); } return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder getSecondaryConstructorBuilder( + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder getPropertyBuilder( int index) { - return getSecondaryConstructorFieldBuilder().getBuilder(index); + return getPropertyFieldBuilder().getBuilder(index); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getSecondaryConstructorOrBuilder( + public org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder getPropertyOrBuilder( int index) { - if (secondaryConstructorBuilder_ == null) { - return secondaryConstructor_.get(index); } else { - return secondaryConstructorBuilder_.getMessageOrBuilder(index); + if (propertyBuilder_ == null) { + return property_.get(index); } else { + return propertyBuilder_.getMessageOrBuilder(index); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> - getSecondaryConstructorOrBuilderList() { - if (secondaryConstructorBuilder_ != null) { - return secondaryConstructorBuilder_.getMessageOrBuilderList(); + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> + getPropertyOrBuilderList() { + if (propertyBuilder_ != null) { + return propertyBuilder_.getMessageOrBuilderList(); } else { - return java.util.Collections.unmodifiableList(secondaryConstructor_); + return java.util.Collections.unmodifiableList(property_); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addSecondaryConstructorBuilder() { - return getSecondaryConstructorFieldBuilder().addBuilder( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder addPropertyBuilder() { + return getPropertyFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.getDefaultInstance()); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addSecondaryConstructorBuilder( + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder addPropertyBuilder( int index) { - return getSecondaryConstructorFieldBuilder().addBuilder( - index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + return getPropertyFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.getDefaultInstance()); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder> - getSecondaryConstructorBuilderList() { - return getSecondaryConstructorFieldBuilder().getBuilderList(); + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder> + getPropertyBuilderList() { + return getPropertyFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> - getSecondaryConstructorFieldBuilder() { - if (secondaryConstructorBuilder_ == null) { - secondaryConstructorBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder>( - secondaryConstructor_, - ((bitField0_ & 0x00000200) == 0x00000200), + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> + getPropertyFieldBuilder() { + if (propertyBuilder_ == null) { + propertyBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder>( + property_, + ((bitField0_ & 0x00000100) == 0x00000100), getParentForChildren(), isClean()); - secondaryConstructor_ = null; + property_ = null; } - return secondaryConstructorBuilder_; + return propertyBuilder_; } - // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Class) - } - - static { - defaultInstance = new Class(true); - defaultInstance.initFields(); - } - - // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Class) - } - - public interface PackageOrBuilder extends - com.google.protobuf.GeneratedMessage. - ExtendableMessageOrBuilder<Package> { - - // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> - getMemberList(); - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getMember(int index); - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - int getMemberCount(); - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> - getMemberOrBuilderList(); - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getMemberOrBuilder( - int index); - } - /** - * Protobuf type {@code org.jetbrains.kotlin.serialization.Package} - */ - public static final class Package extends - com.google.protobuf.GeneratedMessage.ExtendableMessage< - Package> implements PackageOrBuilder { - // Use Package.newBuilder() to construct. - private Package(com.google.protobuf.GeneratedMessage.ExtendableBuilder<org.jetbrains.kotlin.serialization.DebugProtoBuf.Package, ?> builder) { - super(builder); - this.unknownFields = builder.getUnknownFields(); - } - private Package(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - - private static final Package defaultInstance; - public static Package getDefaultInstance() { - return defaultInstance; - } + // repeated .org.jetbrains.kotlin.serialization.Callable member = 11; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> member_ = + java.util.Collections.emptyList(); + private void ensureMemberIsMutable() { + if (!((bitField0_ & 0x00000200) == 0x00000200)) { + member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(member_); + bitField0_ |= 0x00000200; + } + } - public Package getDefaultInstanceForType() { - return defaultInstance; - } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> memberBuilder_; - private final com.google.protobuf.UnknownFieldSet unknownFields; - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private Package( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - initFields(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField(input, unknownFields, - extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(); - mutable_bitField0_ |= 0x00000001; - } - member_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.PARSER, extensionRegistry)); - break; - } - } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> getMemberList() { + if (memberBuilder_ == null) { + return java.util.Collections.unmodifiableList(member_); + } else { + return memberBuilder_.getMessageList(); } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - member_ = java.util.Collections.unmodifiableList(member_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public int getMemberCount() { + if (memberBuilder_ == null) { + return member_.size(); + } else { + return memberBuilder_.getCount(); } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.Builder.class); - } - - public static com.google.protobuf.Parser<Package> PARSER = - new com.google.protobuf.AbstractParser<Package>() { - public Package parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Package(input, extensionRegistry); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getMember(int index) { + if (memberBuilder_ == null) { + return member_.get(index); + } else { + return memberBuilder_.getMessage(index); + } } - }; - - @java.lang.Override - public com.google.protobuf.Parser<Package> getParserForType() { - return PARSER; - } - - // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; - public static final int MEMBER_FIELD_NUMBER = 1; - private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> member_; - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> getMemberList() { - return member_; - } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> - getMemberOrBuilderList() { - return member_; - } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public int getMemberCount() { - return member_.size(); - } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getMember(int index) { - return member_.get(index); - } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getMemberOrBuilder( - int index) { - return member_.get(index); - } - - private void initFields() { - member_ = java.util.Collections.emptyList(); - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized != -1) return isInitialized == 1; - - for (int i = 0; i < getMemberCount(); i++) { - if (!getMember(i).isInitialized()) { - memoizedIsInitialized = 0; - return false; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder setMember( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (memberBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.set(index, value); + onChanged(); + } else { + memberBuilder_.setMessage(index, value); } + return this; } - if (!extensionsAreInitialized()) { - memoizedIsInitialized = 0; - return false; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder setMember( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + member_.set(index, builderForValue.build()); + onChanged(); + } else { + memberBuilder_.setMessage(index, builderForValue.build()); + } + return this; } - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - com.google.protobuf.GeneratedMessage - .ExtendableMessage<org.jetbrains.kotlin.serialization.DebugProtoBuf.Package>.ExtensionWriter extensionWriter = - newExtensionWriter(); - for (int i = 0; i < member_.size(); i++) { - output.writeMessage(1, member_.get(i)); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder addMember(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (memberBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.add(value); + onChanged(); + } else { + memberBuilder_.addMessage(value); + } + return this; } - extensionWriter.writeUntil(200, output); - getUnknownFields().writeTo(output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - for (int i = 0; i < member_.size(); i++) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(1, member_.get(i)); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder addMember( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (memberBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.add(index, value); + onChanged(); + } else { + memberBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder addMember( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + member_.add(builderForValue.build()); + onChanged(); + } else { + memberBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder addMember( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + member_.add(index, builderForValue.build()); + onChanged(); + } else { + memberBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder addAllMember( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> values) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + super.addAll(values, member_); + onChanged(); + } else { + memberBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder clearMember() { + if (memberBuilder_ == null) { + member_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000200); + onChanged(); + } else { + memberBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public Builder removeMember(int index) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + member_.remove(index); + onChanged(); + } else { + memberBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder getMemberBuilder( + int index) { + return getMemberFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getMemberOrBuilder( + int index) { + if (memberBuilder_ == null) { + return member_.get(index); } else { + return memberBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> + getMemberOrBuilderList() { + if (memberBuilder_ != null) { + return memberBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(member_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addMemberBuilder() { + return getMemberFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addMemberBuilder( + int index) { + return getMemberFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder> + getMemberBuilderList() { + return getMemberFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> + getMemberFieldBuilder() { + if (memberBuilder_ == null) { + memberBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder>( + member_, + ((bitField0_ & 0x00000200) == 0x00000200), + getParentForChildren(), + isClean()); + member_ = null; + } + return memberBuilder_; + } + + // repeated int32 enum_entry = 12 [packed = true]; + private java.util.List<java.lang.Integer> enumEntry_ = java.util.Collections.emptyList(); + private void ensureEnumEntryIsMutable() { + if (!((bitField0_ & 0x00000400) == 0x00000400)) { + enumEntry_ = new java.util.ArrayList<java.lang.Integer>(enumEntry_); + bitField0_ |= 0x00000400; + } + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public java.util.List<java.lang.Integer> + getEnumEntryList() { + return java.util.Collections.unmodifiableList(enumEntry_); + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public int getEnumEntryCount() { + return enumEntry_.size(); + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public int getEnumEntry(int index) { + return enumEntry_.get(index); + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public Builder setEnumEntry( + int index, int value) { + ensureEnumEntryIsMutable(); + enumEntry_.set(index, value); + onChanged(); + return this; + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public Builder addEnumEntry(int value) { + ensureEnumEntryIsMutable(); + enumEntry_.add(value); + onChanged(); + return this; + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public Builder addAllEnumEntry( + java.lang.Iterable<? extends java.lang.Integer> values) { + ensureEnumEntryIsMutable(); + super.addAll(values, enumEntry_); + onChanged(); + return this; + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public Builder clearEnumEntry() { + enumEntry_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000400); + onChanged(); + return this; + } + + // optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor primaryConstructor_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructorOrBuilder> primaryConstructorBuilder_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public boolean hasPrimaryConstructor() { + return ((bitField0_ & 0x00000800) == 0x00000800); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor getPrimaryConstructor() { + if (primaryConstructorBuilder_ == null) { + return primaryConstructor_; + } else { + return primaryConstructorBuilder_.getMessage(); + } + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public Builder setPrimaryConstructor(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor value) { + if (primaryConstructorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + primaryConstructor_ = value; + onChanged(); + } else { + primaryConstructorBuilder_.setMessage(value); + } + bitField0_ |= 0x00000800; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public Builder setPrimaryConstructor( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder builderForValue) { + if (primaryConstructorBuilder_ == null) { + primaryConstructor_ = builderForValue.build(); + onChanged(); + } else { + primaryConstructorBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000800; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public Builder mergePrimaryConstructor(org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor value) { + if (primaryConstructorBuilder_ == null) { + if (((bitField0_ & 0x00000800) == 0x00000800) && + primaryConstructor_ != org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.getDefaultInstance()) { + primaryConstructor_ = + org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.newBuilder(primaryConstructor_).mergeFrom(value).buildPartial(); + } else { + primaryConstructor_ = value; + } + onChanged(); + } else { + primaryConstructorBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000800; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public Builder clearPrimaryConstructor() { + if (primaryConstructorBuilder_ == null) { + primaryConstructor_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); + onChanged(); + } else { + primaryConstructorBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000800); + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder getPrimaryConstructorBuilder() { + bitField0_ |= 0x00000800; + onChanged(); + return getPrimaryConstructorFieldBuilder().getBuilder(); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructorOrBuilder getPrimaryConstructorOrBuilder() { + if (primaryConstructorBuilder_ != null) { + return primaryConstructorBuilder_.getMessageOrBuilder(); + } else { + return primaryConstructor_; + } + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructorOrBuilder> + getPrimaryConstructorFieldBuilder() { + if (primaryConstructorBuilder_ == null) { + primaryConstructorBuilder_ = new com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.Class.PrimaryConstructorOrBuilder>( + primaryConstructor_, + getParentForChildren(), + isClean()); + primaryConstructor_ = null; + } + return primaryConstructorBuilder_; + } + + // repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> secondaryConstructor_ = + java.util.Collections.emptyList(); + private void ensureSecondaryConstructorIsMutable() { + if (!((bitField0_ & 0x00001000) == 0x00001000)) { + secondaryConstructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(secondaryConstructor_); + bitField0_ |= 0x00001000; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> secondaryConstructorBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> getSecondaryConstructorList() { + if (secondaryConstructorBuilder_ == null) { + return java.util.Collections.unmodifiableList(secondaryConstructor_); + } else { + return secondaryConstructorBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public int getSecondaryConstructorCount() { + if (secondaryConstructorBuilder_ == null) { + return secondaryConstructor_.size(); + } else { + return secondaryConstructorBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getSecondaryConstructor(int index) { + if (secondaryConstructorBuilder_ == null) { + return secondaryConstructor_.get(index); + } else { + return secondaryConstructorBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder setSecondaryConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (secondaryConstructorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.set(index, value); + onChanged(); + } else { + secondaryConstructorBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder setSecondaryConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (secondaryConstructorBuilder_ == null) { + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.set(index, builderForValue.build()); + onChanged(); + } else { + secondaryConstructorBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addSecondaryConstructor(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (secondaryConstructorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.add(value); + onChanged(); + } else { + secondaryConstructorBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addSecondaryConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (secondaryConstructorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.add(index, value); + onChanged(); + } else { + secondaryConstructorBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addSecondaryConstructor( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (secondaryConstructorBuilder_ == null) { + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.add(builderForValue.build()); + onChanged(); + } else { + secondaryConstructorBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addSecondaryConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (secondaryConstructorBuilder_ == null) { + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.add(index, builderForValue.build()); + onChanged(); + } else { + secondaryConstructorBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addAllSecondaryConstructor( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> values) { + if (secondaryConstructorBuilder_ == null) { + ensureSecondaryConstructorIsMutable(); + super.addAll(values, secondaryConstructor_); + onChanged(); + } else { + secondaryConstructorBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder clearSecondaryConstructor() { + if (secondaryConstructorBuilder_ == null) { + secondaryConstructor_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00001000); + onChanged(); + } else { + secondaryConstructorBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder removeSecondaryConstructor(int index) { + if (secondaryConstructorBuilder_ == null) { + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.remove(index); + onChanged(); + } else { + secondaryConstructorBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder getSecondaryConstructorBuilder( + int index) { + return getSecondaryConstructorFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getSecondaryConstructorOrBuilder( + int index) { + if (secondaryConstructorBuilder_ == null) { + return secondaryConstructor_.get(index); } else { + return secondaryConstructorBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> + getSecondaryConstructorOrBuilderList() { + if (secondaryConstructorBuilder_ != null) { + return secondaryConstructorBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(secondaryConstructor_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addSecondaryConstructorBuilder() { + return getSecondaryConstructorFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addSecondaryConstructorBuilder( + int index) { + return getSecondaryConstructorFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder> + getSecondaryConstructorBuilderList() { + return getSecondaryConstructorFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> + getSecondaryConstructorFieldBuilder() { + if (secondaryConstructorBuilder_ == null) { + secondaryConstructorBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder>( + secondaryConstructor_, + ((bitField0_ & 0x00001000) == 0x00001000), + getParentForChildren(), + isClean()); + secondaryConstructor_ = null; + } + return secondaryConstructorBuilder_; + } + + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Class) + } + + static { + defaultInstance = new Class(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Class) + } + + public interface PackageOrBuilder extends + com.google.protobuf.GeneratedMessage. + ExtendableMessageOrBuilder<Package> { + + // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> + getMemberList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getMember(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + int getMemberCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> + getMemberOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getMemberOrBuilder( + int index); + + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> + getConstructorList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor getConstructor(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + int getConstructorCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> + getConstructorOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder getConstructorOrBuilder( + int index); + + // repeated .org.jetbrains.kotlin.serialization.Function function = 3; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> + getFunctionList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function getFunction(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + int getFunctionCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> + getFunctionOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder getFunctionOrBuilder( + int index); + + // repeated .org.jetbrains.kotlin.serialization.Property property = 4; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> + getPropertyList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property getProperty(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + int getPropertyCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> + getPropertyOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder getPropertyOrBuilder( + int index); + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Package} + */ + public static final class Package extends + com.google.protobuf.GeneratedMessage.ExtendableMessage< + Package> implements PackageOrBuilder { + // Use Package.newBuilder() to construct. + private Package(com.google.protobuf.GeneratedMessage.ExtendableBuilder<org.jetbrains.kotlin.serialization.DebugProtoBuf.Package, ?> builder) { + super(builder); + this.unknownFields = builder.getUnknownFields(); + } + private Package(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } + + private static final Package defaultInstance; + public static Package getDefaultInstance() { + return defaultInstance; + } + + public Package getDefaultInstanceForType() { + return defaultInstance; + } + + private final com.google.protobuf.UnknownFieldSet unknownFields; + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Package( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(); + mutable_bitField0_ |= 0x00000001; + } + member_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.PARSER, extensionRegistry)); + break; + } + case 18: { + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + constructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor>(); + mutable_bitField0_ |= 0x00000002; + } + constructor_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.PARSER, extensionRegistry)); + break; + } + case 26: { + if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { + function_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function>(); + mutable_bitField0_ |= 0x00000004; + } + function_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.PARSER, extensionRegistry)); + break; + } + case 34: { + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + property_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property>(); + mutable_bitField0_ |= 0x00000008; + } + property_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.PARSER, extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + member_ = java.util.Collections.unmodifiableList(member_); + } + if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + constructor_ = java.util.Collections.unmodifiableList(constructor_); + } + if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { + function_ = java.util.Collections.unmodifiableList(function_); + } + if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + property_ = java.util.Collections.unmodifiableList(property_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.Builder.class); + } + + public static com.google.protobuf.Parser<Package> PARSER = + new com.google.protobuf.AbstractParser<Package>() { + public Package parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Package(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser<Package> getParserForType() { + return PARSER; + } + + // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; + public static final int MEMBER_FIELD_NUMBER = 1; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> member_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> getMemberList() { + return member_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> + getMemberOrBuilderList() { + return member_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public int getMemberCount() { + return member_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getMember(int index) { + return member_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getMemberOrBuilder( + int index) { + return member_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2; + public static final int CONSTRUCTOR_FIELD_NUMBER = 2; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> constructor_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> getConstructorList() { + return constructor_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> + getConstructorOrBuilderList() { + return constructor_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public int getConstructorCount() { + return constructor_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor getConstructor(int index) { + return constructor_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder getConstructorOrBuilder( + int index) { + return constructor_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Function function = 3; + public static final int FUNCTION_FIELD_NUMBER = 3; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> function_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> getFunctionList() { + return function_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> + getFunctionOrBuilderList() { + return function_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public int getFunctionCount() { + return function_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function getFunction(int index) { + return function_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder getFunctionOrBuilder( + int index) { + return function_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Property property = 4; + public static final int PROPERTY_FIELD_NUMBER = 4; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> property_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> getPropertyList() { + return property_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> + getPropertyOrBuilderList() { + return property_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public int getPropertyCount() { + return property_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property getProperty(int index) { + return property_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder getPropertyOrBuilder( + int index) { + return property_.get(index); + } + + private void initFields() { + member_ = java.util.Collections.emptyList(); + constructor_ = java.util.Collections.emptyList(); + function_ = java.util.Collections.emptyList(); + property_ = java.util.Collections.emptyList(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + for (int i = 0; i < getMemberCount(); i++) { + if (!getMember(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getConstructorCount(); i++) { + if (!getConstructor(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getFunctionCount(); i++) { + if (!getFunction(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getPropertyCount(); i++) { + if (!getProperty(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (!extensionsAreInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + com.google.protobuf.GeneratedMessage + .ExtendableMessage<org.jetbrains.kotlin.serialization.DebugProtoBuf.Package>.ExtensionWriter extensionWriter = + newExtensionWriter(); + for (int i = 0; i < member_.size(); i++) { + output.writeMessage(1, member_.get(i)); + } + for (int i = 0; i < constructor_.size(); i++) { + output.writeMessage(2, constructor_.get(i)); + } + for (int i = 0; i < function_.size(); i++) { + output.writeMessage(3, function_.get(i)); + } + for (int i = 0; i < property_.size(); i++) { + output.writeMessage(4, property_.get(i)); + } + extensionWriter.writeUntil(200, output); + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + for (int i = 0; i < member_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, member_.get(i)); + } + for (int i = 0; i < constructor_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, constructor_.get(i)); + } + for (int i = 0; i < function_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, function_.get(i)); + } + for (int i = 0; i < property_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, property_.get(i)); + } + size += extensionsSerializedSize(); + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jetbrains.kotlin.serialization.DebugProtoBuf.Package prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Package} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.ExtendableBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Package, Builder> implements org.jetbrains.kotlin.serialization.DebugProtoBuf.PackageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.Builder.class); + } + + // Construct using org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getMemberFieldBuilder(); + getConstructorFieldBuilder(); + getFunctionFieldBuilder(); + getPropertyFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + if (memberBuilder_ == null) { + member_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + } else { + memberBuilder_.clear(); + } + if (constructorBuilder_ == null) { + constructor_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + } else { + constructorBuilder_.clear(); + } + if (functionBuilder_ == null) { + function_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000004); + } else { + functionBuilder_.clear(); + } + if (propertyBuilder_ == null) { + property_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + } else { + propertyBuilder_.clear(); + } + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_descriptor; + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Package getDefaultInstanceForType() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.getDefaultInstance(); + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Package build() { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Package result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Package buildPartial() { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Package result = new org.jetbrains.kotlin.serialization.DebugProtoBuf.Package(this); + int from_bitField0_ = bitField0_; + if (memberBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + member_ = java.util.Collections.unmodifiableList(member_); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.member_ = member_; + } else { + result.member_ = memberBuilder_.build(); + } + if (constructorBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { + constructor_ = java.util.Collections.unmodifiableList(constructor_); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.constructor_ = constructor_; + } else { + result.constructor_ = constructorBuilder_.build(); + } + if (functionBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { + function_ = java.util.Collections.unmodifiableList(function_); + bitField0_ = (bitField0_ & ~0x00000004); + } + result.function_ = function_; + } else { + result.function_ = functionBuilder_.build(); + } + if (propertyBuilder_ == null) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { + property_ = java.util.Collections.unmodifiableList(property_); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.property_ = property_; + } else { + result.property_ = propertyBuilder_.build(); + } + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.jetbrains.kotlin.serialization.DebugProtoBuf.Package) { + return mergeFrom((org.jetbrains.kotlin.serialization.DebugProtoBuf.Package)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Package other) { + if (other == org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.getDefaultInstance()) return this; + if (memberBuilder_ == null) { + if (!other.member_.isEmpty()) { + if (member_.isEmpty()) { + member_ = other.member_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureMemberIsMutable(); + member_.addAll(other.member_); + } + onChanged(); + } + } else { + if (!other.member_.isEmpty()) { + if (memberBuilder_.isEmpty()) { + memberBuilder_.dispose(); + memberBuilder_ = null; + member_ = other.member_; + bitField0_ = (bitField0_ & ~0x00000001); + memberBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getMemberFieldBuilder() : null; + } else { + memberBuilder_.addAllMessages(other.member_); + } + } + } + if (constructorBuilder_ == null) { + if (!other.constructor_.isEmpty()) { + if (constructor_.isEmpty()) { + constructor_ = other.constructor_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureConstructorIsMutable(); + constructor_.addAll(other.constructor_); + } + onChanged(); + } + } else { + if (!other.constructor_.isEmpty()) { + if (constructorBuilder_.isEmpty()) { + constructorBuilder_.dispose(); + constructorBuilder_ = null; + constructor_ = other.constructor_; + bitField0_ = (bitField0_ & ~0x00000002); + constructorBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getConstructorFieldBuilder() : null; + } else { + constructorBuilder_.addAllMessages(other.constructor_); + } + } + } + if (functionBuilder_ == null) { + if (!other.function_.isEmpty()) { + if (function_.isEmpty()) { + function_ = other.function_; + bitField0_ = (bitField0_ & ~0x00000004); + } else { + ensureFunctionIsMutable(); + function_.addAll(other.function_); + } + onChanged(); + } + } else { + if (!other.function_.isEmpty()) { + if (functionBuilder_.isEmpty()) { + functionBuilder_.dispose(); + functionBuilder_ = null; + function_ = other.function_; + bitField0_ = (bitField0_ & ~0x00000004); + functionBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getFunctionFieldBuilder() : null; + } else { + functionBuilder_.addAllMessages(other.function_); + } + } + } + if (propertyBuilder_ == null) { + if (!other.property_.isEmpty()) { + if (property_.isEmpty()) { + property_ = other.property_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensurePropertyIsMutable(); + property_.addAll(other.property_); + } + onChanged(); + } + } else { + if (!other.property_.isEmpty()) { + if (propertyBuilder_.isEmpty()) { + propertyBuilder_.dispose(); + propertyBuilder_ = null; + property_ = other.property_; + bitField0_ = (bitField0_ & ~0x00000008); + propertyBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getPropertyFieldBuilder() : null; + } else { + propertyBuilder_.addAllMessages(other.property_); + } + } + } + this.mergeExtensionFields(other); + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + for (int i = 0; i < getMemberCount(); i++) { + if (!getMember(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getConstructorCount(); i++) { + if (!getConstructor(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getFunctionCount(); i++) { + if (!getFunction(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getPropertyCount(); i++) { + if (!getProperty(i).isInitialized()) { + + return false; + } + } + if (!extensionsAreInitialized()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jetbrains.kotlin.serialization.DebugProtoBuf.Package) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> member_ = + java.util.Collections.emptyList(); + private void ensureMemberIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(member_); + bitField0_ |= 0x00000001; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> memberBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> getMemberList() { + if (memberBuilder_ == null) { + return java.util.Collections.unmodifiableList(member_); + } else { + return memberBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public int getMemberCount() { + if (memberBuilder_ == null) { + return member_.size(); + } else { + return memberBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getMember(int index) { + if (memberBuilder_ == null) { + return member_.get(index); + } else { + return memberBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder setMember( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (memberBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.set(index, value); + onChanged(); + } else { + memberBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder setMember( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + member_.set(index, builderForValue.build()); + onChanged(); + } else { + memberBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addMember(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (memberBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.add(value); + onChanged(); + } else { + memberBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addMember( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { + if (memberBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.add(index, value); + onChanged(); + } else { + memberBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addMember( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + member_.add(builderForValue.build()); + onChanged(); + } else { + memberBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addMember( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + member_.add(index, builderForValue.build()); + onChanged(); + } else { + memberBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addAllMember( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> values) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + super.addAll(values, member_); + onChanged(); + } else { + memberBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder clearMember() { + if (memberBuilder_ == null) { + member_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + } else { + memberBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder removeMember(int index) { + if (memberBuilder_ == null) { + ensureMemberIsMutable(); + member_.remove(index); + onChanged(); + } else { + memberBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder getMemberBuilder( + int index) { + return getMemberFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getMemberOrBuilder( + int index) { + if (memberBuilder_ == null) { + return member_.get(index); } else { + return memberBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> + getMemberOrBuilderList() { + if (memberBuilder_ != null) { + return memberBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(member_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addMemberBuilder() { + return getMemberFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addMemberBuilder( + int index) { + return getMemberFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder> + getMemberBuilderList() { + return getMemberFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> + getMemberFieldBuilder() { + if (memberBuilder_ == null) { + memberBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder>( + member_, + ((bitField0_ & 0x00000001) == 0x00000001), + getParentForChildren(), + isClean()); + member_ = null; + } + return memberBuilder_; + } + + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> constructor_ = + java.util.Collections.emptyList(); + private void ensureConstructorIsMutable() { + if (!((bitField0_ & 0x00000002) == 0x00000002)) { + constructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor>(constructor_); + bitField0_ |= 0x00000002; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> constructorBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> getConstructorList() { + if (constructorBuilder_ == null) { + return java.util.Collections.unmodifiableList(constructor_); + } else { + return constructorBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public int getConstructorCount() { + if (constructorBuilder_ == null) { + return constructor_.size(); + } else { + return constructorBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor getConstructor(int index) { + if (constructorBuilder_ == null) { + return constructor_.get(index); + } else { + return constructorBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder setConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor value) { + if (constructorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureConstructorIsMutable(); + constructor_.set(index, value); + onChanged(); + } else { + constructorBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder setConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder builderForValue) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + constructor_.set(index, builderForValue.build()); + onChanged(); + } else { + constructorBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addConstructor(org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor value) { + if (constructorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureConstructorIsMutable(); + constructor_.add(value); + onChanged(); + } else { + constructorBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor value) { + if (constructorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureConstructorIsMutable(); + constructor_.add(index, value); + onChanged(); + } else { + constructorBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addConstructor( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder builderForValue) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + constructor_.add(builderForValue.build()); + onChanged(); + } else { + constructorBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addConstructor( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder builderForValue) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + constructor_.add(index, builderForValue.build()); + onChanged(); + } else { + constructorBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addAllConstructor( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor> values) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + super.addAll(values, constructor_); + onChanged(); + } else { + constructorBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder clearConstructor() { + if (constructorBuilder_ == null) { + constructor_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + onChanged(); + } else { + constructorBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder removeConstructor(int index) { + if (constructorBuilder_ == null) { + ensureConstructorIsMutable(); + constructor_.remove(index); + onChanged(); + } else { + constructorBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder getConstructorBuilder( + int index) { + return getConstructorFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder getConstructorOrBuilder( + int index) { + if (constructorBuilder_ == null) { + return constructor_.get(index); } else { + return constructorBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> + getConstructorOrBuilderList() { + if (constructorBuilder_ != null) { + return constructorBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(constructor_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder addConstructorBuilder() { + return getConstructorFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder addConstructorBuilder( + int index) { + return getConstructorFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder> + getConstructorBuilderList() { + return getConstructorFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder> + getConstructorFieldBuilder() { + if (constructorBuilder_ == null) { + constructorBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder>( + constructor_, + ((bitField0_ & 0x00000002) == 0x00000002), + getParentForChildren(), + isClean()); + constructor_ = null; + } + return constructorBuilder_; + } + + // repeated .org.jetbrains.kotlin.serialization.Function function = 3; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> function_ = + java.util.Collections.emptyList(); + private void ensureFunctionIsMutable() { + if (!((bitField0_ & 0x00000004) == 0x00000004)) { + function_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function>(function_); + bitField0_ |= 0x00000004; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> functionBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> getFunctionList() { + if (functionBuilder_ == null) { + return java.util.Collections.unmodifiableList(function_); + } else { + return functionBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public int getFunctionCount() { + if (functionBuilder_ == null) { + return function_.size(); + } else { + return functionBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function getFunction(int index) { + if (functionBuilder_ == null) { + return function_.get(index); + } else { + return functionBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder setFunction( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function value) { + if (functionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.set(index, value); + onChanged(); + } else { + functionBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder setFunction( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder builderForValue) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + function_.set(index, builderForValue.build()); + onChanged(); + } else { + functionBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addFunction(org.jetbrains.kotlin.serialization.DebugProtoBuf.Function value) { + if (functionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.add(value); + onChanged(); + } else { + functionBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addFunction( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function value) { + if (functionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.add(index, value); + onChanged(); + } else { + functionBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addFunction( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder builderForValue) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + function_.add(builderForValue.build()); + onChanged(); + } else { + functionBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addFunction( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder builderForValue) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + function_.add(index, builderForValue.build()); + onChanged(); + } else { + functionBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addAllFunction( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Function> values) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + super.addAll(values, function_); + onChanged(); + } else { + functionBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder clearFunction() { + if (functionBuilder_ == null) { + function_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000004); + onChanged(); + } else { + functionBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder removeFunction(int index) { + if (functionBuilder_ == null) { + ensureFunctionIsMutable(); + function_.remove(index); + onChanged(); + } else { + functionBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder getFunctionBuilder( + int index) { + return getFunctionFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder getFunctionOrBuilder( + int index) { + if (functionBuilder_ == null) { + return function_.get(index); } else { + return functionBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> + getFunctionOrBuilderList() { + if (functionBuilder_ != null) { + return functionBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(function_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder addFunctionBuilder() { + return getFunctionFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder addFunctionBuilder( + int index) { + return getFunctionFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder> + getFunctionBuilderList() { + return getFunctionFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder> + getFunctionFieldBuilder() { + if (functionBuilder_ == null) { + functionBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder>( + function_, + ((bitField0_ & 0x00000004) == 0x00000004), + getParentForChildren(), + isClean()); + function_ = null; + } + return functionBuilder_; + } + + // repeated .org.jetbrains.kotlin.serialization.Property property = 4; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> property_ = + java.util.Collections.emptyList(); + private void ensurePropertyIsMutable() { + if (!((bitField0_ & 0x00000008) == 0x00000008)) { + property_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property>(property_); + bitField0_ |= 0x00000008; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> propertyBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> getPropertyList() { + if (propertyBuilder_ == null) { + return java.util.Collections.unmodifiableList(property_); + } else { + return propertyBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public int getPropertyCount() { + if (propertyBuilder_ == null) { + return property_.size(); + } else { + return propertyBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property getProperty(int index) { + if (propertyBuilder_ == null) { + return property_.get(index); + } else { + return propertyBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder setProperty( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property value) { + if (propertyBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePropertyIsMutable(); + property_.set(index, value); + onChanged(); + } else { + propertyBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder setProperty( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder builderForValue) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + property_.set(index, builderForValue.build()); + onChanged(); + } else { + propertyBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addProperty(org.jetbrains.kotlin.serialization.DebugProtoBuf.Property value) { + if (propertyBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePropertyIsMutable(); + property_.add(value); + onChanged(); + } else { + propertyBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addProperty( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property value) { + if (propertyBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePropertyIsMutable(); + property_.add(index, value); + onChanged(); + } else { + propertyBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addProperty( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder builderForValue) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + property_.add(builderForValue.build()); + onChanged(); + } else { + propertyBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addProperty( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder builderForValue) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + property_.add(index, builderForValue.build()); + onChanged(); + } else { + propertyBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addAllProperty( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Property> values) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + super.addAll(values, property_); + onChanged(); + } else { + propertyBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder clearProperty() { + if (propertyBuilder_ == null) { + property_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + onChanged(); + } else { + propertyBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder removeProperty(int index) { + if (propertyBuilder_ == null) { + ensurePropertyIsMutable(); + property_.remove(index); + onChanged(); + } else { + propertyBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder getPropertyBuilder( + int index) { + return getPropertyFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder getPropertyOrBuilder( + int index) { + if (propertyBuilder_ == null) { + return property_.get(index); } else { + return propertyBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> + getPropertyOrBuilderList() { + if (propertyBuilder_ != null) { + return propertyBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(property_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder addPropertyBuilder() { + return getPropertyFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder addPropertyBuilder( + int index) { + return getPropertyFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder> + getPropertyBuilderList() { + return getPropertyFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder> + getPropertyFieldBuilder() { + if (propertyBuilder_ == null) { + propertyBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder>( + property_, + ((bitField0_ & 0x00000008) == 0x00000008), + getParentForChildren(), + isClean()); + property_ = null; + } + return propertyBuilder_; + } + + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Package) + } + + static { + defaultInstance = new Package(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Package) + } + + public interface ConstructorOrBuilder extends + com.google.protobuf.GeneratedMessage. + ExtendableMessageOrBuilder<Constructor> { + + // optional int32 flags = 1; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + boolean hasFlags(); + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + int getFlags(); + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> + getValueParameterList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getValueParameter(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + int getValueParameterCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getValueParameterOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getValueParameterOrBuilder( + int index); + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Constructor} + */ + public static final class Constructor extends + com.google.protobuf.GeneratedMessage.ExtendableMessage< + Constructor> implements ConstructorOrBuilder { + // Use Constructor.newBuilder() to construct. + private Constructor(com.google.protobuf.GeneratedMessage.ExtendableBuilder<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor, ?> builder) { + super(builder); + this.unknownFields = builder.getUnknownFields(); + } + private Constructor(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } + + private static final Constructor defaultInstance; + public static Constructor getDefaultInstance() { + return defaultInstance; + } + + public Constructor getDefaultInstanceForType() { + return defaultInstance; + } + + private final com.google.protobuf.UnknownFieldSet unknownFields; + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Constructor( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + flags_ = input.readInt32(); + break; + } + case 18: { + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + valueParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter>(); + mutable_bitField0_ |= 0x00000002; + } + valueParameter_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.PARSER, extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + valueParameter_ = java.util.Collections.unmodifiableList(valueParameter_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Constructor_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Constructor_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder.class); + } + + public static com.google.protobuf.Parser<Constructor> PARSER = + new com.google.protobuf.AbstractParser<Constructor>() { + public Constructor parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Constructor(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser<Constructor> getParserForType() { + return PARSER; + } + + private int bitField0_; + // optional int32 flags = 1; + public static final int FLAGS_FIELD_NUMBER = 1; + private int flags_; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public int getFlags() { + return flags_; + } + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2; + public static final int VALUE_PARAMETER_FIELD_NUMBER = 2; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> valueParameter_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> getValueParameterList() { + return valueParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getValueParameterOrBuilderList() { + return valueParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public int getValueParameterCount() { + return valueParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getValueParameter(int index) { + return valueParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getValueParameterOrBuilder( + int index) { + return valueParameter_.get(index); + } + + private void initFields() { + flags_ = 0; + valueParameter_ = java.util.Collections.emptyList(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + for (int i = 0; i < getValueParameterCount(); i++) { + if (!getValueParameter(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (!extensionsAreInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + com.google.protobuf.GeneratedMessage + .ExtendableMessage<org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor>.ExtensionWriter extensionWriter = + newExtensionWriter(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, flags_); + } + for (int i = 0; i < valueParameter_.size(); i++) { + output.writeMessage(2, valueParameter_.get(i)); + } + extensionWriter.writeUntil(200, output); + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, flags_); + } + for (int i = 0; i < valueParameter_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, valueParameter_.get(i)); + } + size += extensionsSerializedSize(); + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Constructor} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.ExtendableBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor, Builder> implements org.jetbrains.kotlin.serialization.DebugProtoBuf.ConstructorOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Constructor_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Constructor_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.Builder.class); + } + + // Construct using org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getValueParameterFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + flags_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + if (valueParameterBuilder_ == null) { + valueParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + } else { + valueParameterBuilder_.clear(); + } + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Constructor_descriptor; + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor getDefaultInstanceForType() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.getDefaultInstance(); + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor build() { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor buildPartial() { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor result = new org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.flags_ = flags_; + if (valueParameterBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { + valueParameter_ = java.util.Collections.unmodifiableList(valueParameter_); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.valueParameter_ = valueParameter_; + } else { + result.valueParameter_ = valueParameterBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor) { + return mergeFrom((org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor other) { + if (other == org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor.getDefaultInstance()) return this; + if (other.hasFlags()) { + setFlags(other.getFlags()); + } + if (valueParameterBuilder_ == null) { + if (!other.valueParameter_.isEmpty()) { + if (valueParameter_.isEmpty()) { + valueParameter_ = other.valueParameter_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureValueParameterIsMutable(); + valueParameter_.addAll(other.valueParameter_); + } + onChanged(); + } + } else { + if (!other.valueParameter_.isEmpty()) { + if (valueParameterBuilder_.isEmpty()) { + valueParameterBuilder_.dispose(); + valueParameterBuilder_ = null; + valueParameter_ = other.valueParameter_; + bitField0_ = (bitField0_ & ~0x00000002); + valueParameterBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getValueParameterFieldBuilder() : null; + } else { + valueParameterBuilder_.addAllMessages(other.valueParameter_); + } + } + } + this.mergeExtensionFields(other); + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + for (int i = 0; i < getValueParameterCount(); i++) { + if (!getValueParameter(i).isInitialized()) { + + return false; + } + } + if (!extensionsAreInitialized()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jetbrains.kotlin.serialization.DebugProtoBuf.Constructor) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + // optional int32 flags = 1; + private int flags_ ; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public int getFlags() { + return flags_; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public Builder setFlags(int value) { + bitField0_ |= 0x00000001; + flags_ = value; + onChanged(); + return this; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public Builder clearFlags() { + bitField0_ = (bitField0_ & ~0x00000001); + flags_ = 0; + onChanged(); + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> valueParameter_ = + java.util.Collections.emptyList(); + private void ensureValueParameterIsMutable() { + if (!((bitField0_ & 0x00000002) == 0x00000002)) { + valueParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter>(valueParameter_); + bitField0_ |= 0x00000002; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> valueParameterBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> getValueParameterList() { + if (valueParameterBuilder_ == null) { + return java.util.Collections.unmodifiableList(valueParameter_); + } else { + return valueParameterBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public int getValueParameterCount() { + if (valueParameterBuilder_ == null) { + return valueParameter_.size(); + } else { + return valueParameterBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getValueParameter(int index) { + if (valueParameterBuilder_ == null) { + return valueParameter_.get(index); + } else { + return valueParameterBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder setValueParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter value) { + if (valueParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.set(index, value); + onChanged(); + } else { + valueParameterBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder setValueParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder builderForValue) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + valueParameter_.set(index, builderForValue.build()); + onChanged(); + } else { + valueParameterBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addValueParameter(org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter value) { + if (valueParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.add(value); + onChanged(); + } else { + valueParameterBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addValueParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter value) { + if (valueParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.add(index, value); + onChanged(); + } else { + valueParameterBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addValueParameter( + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder builderForValue) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + valueParameter_.add(builderForValue.build()); + onChanged(); + } else { + valueParameterBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addValueParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder builderForValue) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + valueParameter_.add(index, builderForValue.build()); + onChanged(); + } else { + valueParameterBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addAllValueParameter( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> values) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + super.addAll(values, valueParameter_); + onChanged(); + } else { + valueParameterBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder clearValueParameter() { + if (valueParameterBuilder_ == null) { + valueParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + onChanged(); + } else { + valueParameterBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder removeValueParameter(int index) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + valueParameter_.remove(index); + onChanged(); + } else { + valueParameterBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder getValueParameterBuilder( + int index) { + return getValueParameterFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getValueParameterOrBuilder( + int index) { + if (valueParameterBuilder_ == null) { + return valueParameter_.get(index); } else { + return valueParameterBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getValueParameterOrBuilderList() { + if (valueParameterBuilder_ != null) { + return valueParameterBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(valueParameter_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder addValueParameterBuilder() { + return getValueParameterFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder addValueParameterBuilder( + int index) { + return getValueParameterFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder> + getValueParameterBuilderList() { + return getValueParameterFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getValueParameterFieldBuilder() { + if (valueParameterBuilder_ == null) { + valueParameterBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder>( + valueParameter_, + ((bitField0_ & 0x00000002) == 0x00000002), + getParentForChildren(), + isClean()); + valueParameter_ = null; + } + return valueParameterBuilder_; + } + + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Constructor) + } + + static { + defaultInstance = new Constructor(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Constructor) + } + + public interface FunctionOrBuilder extends + com.google.protobuf.GeneratedMessage. + ExtendableMessageOrBuilder<Function> { + + // optional int32 flags = 1; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + boolean hasFlags(); + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + int getFlags(); + + // required int32 name = 2; + /** + * <code>required int32 name = 2;</code> + */ + boolean hasName(); + /** + * <code>required int32 name = 2;</code> + */ + int getName(); + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + boolean hasReturnType(); + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReturnType(); + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReturnTypeOrBuilder(); + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> + getTypeParameterList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter getTypeParameter(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + int getTypeParameterCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> + getTypeParameterOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder getTypeParameterOrBuilder( + int index); + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + boolean hasReceiverType(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReceiverType(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReceiverTypeOrBuilder(); + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> + getValueParameterList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getValueParameter(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + int getValueParameterCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getValueParameterOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getValueParameterOrBuilder( + int index); + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Function} + */ + public static final class Function extends + com.google.protobuf.GeneratedMessage.ExtendableMessage< + Function> implements FunctionOrBuilder { + // Use Function.newBuilder() to construct. + private Function(com.google.protobuf.GeneratedMessage.ExtendableBuilder<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function, ?> builder) { + super(builder); + this.unknownFields = builder.getUnknownFields(); + } + private Function(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } + + private static final Function defaultInstance; + public static Function getDefaultInstance() { + return defaultInstance; + } + + public Function getDefaultInstanceForType() { + return defaultInstance; + } + + private final com.google.protobuf.UnknownFieldSet unknownFields; + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Function( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + flags_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + name_ = input.readInt32(); + break; + } + case 26: { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder subBuilder = null; + if (((bitField0_ & 0x00000004) == 0x00000004)) { + subBuilder = returnType_.toBuilder(); + } + returnType_ = input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(returnType_); + returnType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000004; + break; + } + case 34: { + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter>(); + mutable_bitField0_ |= 0x00000008; + } + typeParameter_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.PARSER, extensionRegistry)); + break; + } + case 42: { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder subBuilder = null; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + subBuilder = receiverType_.toBuilder(); + } + receiverType_ = input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(receiverType_); + receiverType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000008; + break; + } + case 50: { + if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) { + valueParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter>(); + mutable_bitField0_ |= 0x00000020; + } + valueParameter_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.PARSER, extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = java.util.Collections.unmodifiableList(typeParameter_); + } + if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) { + valueParameter_ = java.util.Collections.unmodifiableList(valueParameter_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Function_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Function_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder.class); + } + + public static com.google.protobuf.Parser<Function> PARSER = + new com.google.protobuf.AbstractParser<Function>() { + public Function parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Function(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser<Function> getParserForType() { + return PARSER; + } + + private int bitField0_; + // optional int32 flags = 1; + public static final int FLAGS_FIELD_NUMBER = 1; + private int flags_; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public int getFlags() { + return flags_; + } + + // required int32 name = 2; + public static final int NAME_FIELD_NUMBER = 2; + private int name_; + /** + * <code>required int32 name = 2;</code> + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>required int32 name = 2;</code> + */ + public int getName() { + return name_; + } + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + public static final int RETURN_TYPE_FIELD_NUMBER = 3; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Type returnType_; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public boolean hasReturnType() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReturnType() { + return returnType_; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReturnTypeOrBuilder() { + return returnType_; + } + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + public static final int TYPE_PARAMETER_FIELD_NUMBER = 4; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> typeParameter_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> getTypeParameterList() { + return typeParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> + getTypeParameterOrBuilderList() { + return typeParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public int getTypeParameterCount() { + return typeParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter getTypeParameter(int index) { + return typeParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder getTypeParameterOrBuilder( + int index) { + return typeParameter_.get(index); + } + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + public static final int RECEIVER_TYPE_FIELD_NUMBER = 5; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Type receiverType_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public boolean hasReceiverType() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReceiverType() { + return receiverType_; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReceiverTypeOrBuilder() { + return receiverType_; + } + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6; + public static final int VALUE_PARAMETER_FIELD_NUMBER = 6; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> valueParameter_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> getValueParameterList() { + return valueParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getValueParameterOrBuilderList() { + return valueParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public int getValueParameterCount() { + return valueParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getValueParameter(int index) { + return valueParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getValueParameterOrBuilder( + int index) { + return valueParameter_.get(index); + } + + private void initFields() { + flags_ = 0; + name_ = 0; + returnType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + typeParameter_ = java.util.Collections.emptyList(); + receiverType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + valueParameter_ = java.util.Collections.emptyList(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasReturnType()) { + memoizedIsInitialized = 0; + return false; + } + if (!getReturnType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + for (int i = 0; i < getTypeParameterCount(); i++) { + if (!getTypeParameter(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (hasReceiverType()) { + if (!getReceiverType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getValueParameterCount(); i++) { + if (!getValueParameter(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (!extensionsAreInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + com.google.protobuf.GeneratedMessage + .ExtendableMessage<org.jetbrains.kotlin.serialization.DebugProtoBuf.Function>.ExtensionWriter extensionWriter = + newExtensionWriter(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, flags_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeInt32(2, name_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, returnType_); + } + for (int i = 0; i < typeParameter_.size(); i++) { + output.writeMessage(4, typeParameter_.get(i)); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeMessage(5, receiverType_); + } + for (int i = 0; i < valueParameter_.size(); i++) { + output.writeMessage(6, valueParameter_.get(i)); + } + extensionWriter.writeUntil(200, output); + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, flags_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(2, name_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, returnType_); + } + for (int i = 0; i < typeParameter_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, typeParameter_.get(i)); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, receiverType_); + } + for (int i = 0; i < valueParameter_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, valueParameter_.get(i)); + } + size += extensionsSerializedSize(); + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jetbrains.kotlin.serialization.DebugProtoBuf.Function prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Function} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.ExtendableBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function, Builder> implements org.jetbrains.kotlin.serialization.DebugProtoBuf.FunctionOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Function_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Function_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.Builder.class); + } + + // Construct using org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getReturnTypeFieldBuilder(); + getTypeParameterFieldBuilder(); + getReceiverTypeFieldBuilder(); + getValueParameterFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + flags_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + if (returnTypeBuilder_ == null) { + returnType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + } else { + returnTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + if (typeParameterBuilder_ == null) { + typeParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + } else { + typeParameterBuilder_.clear(); + } + if (receiverTypeBuilder_ == null) { + receiverType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + } else { + receiverTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); + if (valueParameterBuilder_ == null) { + valueParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000020); + } else { + valueParameterBuilder_.clear(); + } + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Function_descriptor; + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function getDefaultInstanceForType() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.getDefaultInstance(); + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function build() { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Function buildPartial() { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function result = new org.jetbrains.kotlin.serialization.DebugProtoBuf.Function(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.flags_ = flags_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (returnTypeBuilder_ == null) { + result.returnType_ = returnType_; + } else { + result.returnType_ = returnTypeBuilder_.build(); + } + if (typeParameterBuilder_ == null) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = java.util.Collections.unmodifiableList(typeParameter_); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.typeParameter_ = typeParameter_; + } else { + result.typeParameter_ = typeParameterBuilder_.build(); + } + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000008; + } + if (receiverTypeBuilder_ == null) { + result.receiverType_ = receiverType_; + } else { + result.receiverType_ = receiverTypeBuilder_.build(); + } + if (valueParameterBuilder_ == null) { + if (((bitField0_ & 0x00000020) == 0x00000020)) { + valueParameter_ = java.util.Collections.unmodifiableList(valueParameter_); + bitField0_ = (bitField0_ & ~0x00000020); + } + result.valueParameter_ = valueParameter_; + } else { + result.valueParameter_ = valueParameterBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.jetbrains.kotlin.serialization.DebugProtoBuf.Function) { + return mergeFrom((org.jetbrains.kotlin.serialization.DebugProtoBuf.Function)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Function other) { + if (other == org.jetbrains.kotlin.serialization.DebugProtoBuf.Function.getDefaultInstance()) return this; + if (other.hasFlags()) { + setFlags(other.getFlags()); + } + if (other.hasName()) { + setName(other.getName()); + } + if (other.hasReturnType()) { + mergeReturnType(other.getReturnType()); + } + if (typeParameterBuilder_ == null) { + if (!other.typeParameter_.isEmpty()) { + if (typeParameter_.isEmpty()) { + typeParameter_ = other.typeParameter_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensureTypeParameterIsMutable(); + typeParameter_.addAll(other.typeParameter_); + } + onChanged(); + } + } else { + if (!other.typeParameter_.isEmpty()) { + if (typeParameterBuilder_.isEmpty()) { + typeParameterBuilder_.dispose(); + typeParameterBuilder_ = null; + typeParameter_ = other.typeParameter_; + bitField0_ = (bitField0_ & ~0x00000008); + typeParameterBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getTypeParameterFieldBuilder() : null; + } else { + typeParameterBuilder_.addAllMessages(other.typeParameter_); + } + } + } + if (other.hasReceiverType()) { + mergeReceiverType(other.getReceiverType()); + } + if (valueParameterBuilder_ == null) { + if (!other.valueParameter_.isEmpty()) { + if (valueParameter_.isEmpty()) { + valueParameter_ = other.valueParameter_; + bitField0_ = (bitField0_ & ~0x00000020); + } else { + ensureValueParameterIsMutable(); + valueParameter_.addAll(other.valueParameter_); + } + onChanged(); + } + } else { + if (!other.valueParameter_.isEmpty()) { + if (valueParameterBuilder_.isEmpty()) { + valueParameterBuilder_.dispose(); + valueParameterBuilder_ = null; + valueParameter_ = other.valueParameter_; + bitField0_ = (bitField0_ & ~0x00000020); + valueParameterBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getValueParameterFieldBuilder() : null; + } else { + valueParameterBuilder_.addAllMessages(other.valueParameter_); + } + } + } + this.mergeExtensionFields(other); + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + if (!hasName()) { + + return false; + } + if (!hasReturnType()) { + + return false; + } + if (!getReturnType().isInitialized()) { + + return false; + } + for (int i = 0; i < getTypeParameterCount(); i++) { + if (!getTypeParameter(i).isInitialized()) { + + return false; + } + } + if (hasReceiverType()) { + if (!getReceiverType().isInitialized()) { + + return false; + } + } + for (int i = 0; i < getValueParameterCount(); i++) { + if (!getValueParameter(i).isInitialized()) { + + return false; + } + } + if (!extensionsAreInitialized()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Function parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jetbrains.kotlin.serialization.DebugProtoBuf.Function) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + // optional int32 flags = 1; + private int flags_ ; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public int getFlags() { + return flags_; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public Builder setFlags(int value) { + bitField0_ |= 0x00000001; + flags_ = value; + onChanged(); + return this; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public Builder clearFlags() { + bitField0_ = (bitField0_ & ~0x00000001); + flags_ = 0; + onChanged(); + return this; + } + + // required int32 name = 2; + private int name_ ; + /** + * <code>required int32 name = 2;</code> + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>required int32 name = 2;</code> + */ + public int getName() { + return name_; + } + /** + * <code>required int32 name = 2;</code> + */ + public Builder setName(int value) { + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + /** + * <code>required int32 name = 2;</code> + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = 0; + onChanged(); + return this; + } + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Type returnType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder> returnTypeBuilder_; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public boolean hasReturnType() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReturnType() { + if (returnTypeBuilder_ == null) { + return returnType_; + } else { + return returnTypeBuilder_.getMessage(); + } + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder setReturnType(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type value) { + if (returnTypeBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + returnType_ = value; + onChanged(); + } else { + returnTypeBuilder_.setMessage(value); + } + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder setReturnType( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder builderForValue) { + if (returnTypeBuilder_ == null) { + returnType_ = builderForValue.build(); + onChanged(); + } else { + returnTypeBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder mergeReturnType(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type value) { + if (returnTypeBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + returnType_ != org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance()) { + returnType_ = + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.newBuilder(returnType_).mergeFrom(value).buildPartial(); + } else { + returnType_ = value; + } + onChanged(); + } else { + returnTypeBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder clearReturnType() { + if (returnTypeBuilder_ == null) { + returnType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + onChanged(); + } else { + returnTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder getReturnTypeBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getReturnTypeFieldBuilder().getBuilder(); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReturnTypeOrBuilder() { + if (returnTypeBuilder_ != null) { + return returnTypeBuilder_.getMessageOrBuilder(); + } else { + return returnType_; + } + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder> + getReturnTypeFieldBuilder() { + if (returnTypeBuilder_ == null) { + returnTypeBuilder_ = new com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder>( + returnType_, + getParentForChildren(), + isClean()); + returnType_ = null; + } + return returnTypeBuilder_; + } + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> typeParameter_ = + java.util.Collections.emptyList(); + private void ensureTypeParameterIsMutable() { + if (!((bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter>(typeParameter_); + bitField0_ |= 0x00000008; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> typeParameterBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> getTypeParameterList() { + if (typeParameterBuilder_ == null) { + return java.util.Collections.unmodifiableList(typeParameter_); + } else { + return typeParameterBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public int getTypeParameterCount() { + if (typeParameterBuilder_ == null) { + return typeParameter_.size(); + } else { + return typeParameterBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter getTypeParameter(int index) { + if (typeParameterBuilder_ == null) { + return typeParameter_.get(index); + } else { + return typeParameterBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder setTypeParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter value) { + if (typeParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.set(index, value); + onChanged(); + } else { + typeParameterBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder setTypeParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder builderForValue) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + typeParameter_.set(index, builderForValue.build()); + onChanged(); + } else { + typeParameterBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter(org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter value) { + if (typeParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.add(value); + onChanged(); + } else { + typeParameterBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter value) { + if (typeParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.add(index, value); + onChanged(); + } else { + typeParameterBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder builderForValue) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + typeParameter_.add(builderForValue.build()); + onChanged(); + } else { + typeParameterBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder builderForValue) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + typeParameter_.add(index, builderForValue.build()); + onChanged(); + } else { + typeParameterBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addAllTypeParameter( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> values) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + super.addAll(values, typeParameter_); + onChanged(); + } else { + typeParameterBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder clearTypeParameter() { + if (typeParameterBuilder_ == null) { + typeParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + onChanged(); + } else { + typeParameterBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder removeTypeParameter(int index) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + typeParameter_.remove(index); + onChanged(); + } else { + typeParameterBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder getTypeParameterBuilder( + int index) { + return getTypeParameterFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder getTypeParameterOrBuilder( + int index) { + if (typeParameterBuilder_ == null) { + return typeParameter_.get(index); } else { + return typeParameterBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> + getTypeParameterOrBuilderList() { + if (typeParameterBuilder_ != null) { + return typeParameterBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(typeParameter_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder addTypeParameterBuilder() { + return getTypeParameterFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder addTypeParameterBuilder( + int index) { + return getTypeParameterFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder> + getTypeParameterBuilderList() { + return getTypeParameterFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> + getTypeParameterFieldBuilder() { + if (typeParameterBuilder_ == null) { + typeParameterBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder>( + typeParameter_, + ((bitField0_ & 0x00000008) == 0x00000008), + getParentForChildren(), + isClean()); + typeParameter_ = null; + } + return typeParameterBuilder_; + } + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Type receiverType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder> receiverTypeBuilder_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public boolean hasReceiverType() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReceiverType() { + if (receiverTypeBuilder_ == null) { + return receiverType_; + } else { + return receiverTypeBuilder_.getMessage(); + } + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder setReceiverType(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type value) { + if (receiverTypeBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + receiverType_ = value; + onChanged(); + } else { + receiverTypeBuilder_.setMessage(value); + } + bitField0_ |= 0x00000010; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder setReceiverType( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder builderForValue) { + if (receiverTypeBuilder_ == null) { + receiverType_ = builderForValue.build(); + onChanged(); + } else { + receiverTypeBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000010; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder mergeReceiverType(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type value) { + if (receiverTypeBuilder_ == null) { + if (((bitField0_ & 0x00000010) == 0x00000010) && + receiverType_ != org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance()) { + receiverType_ = + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.newBuilder(receiverType_).mergeFrom(value).buildPartial(); + } else { + receiverType_ = value; + } + onChanged(); + } else { + receiverTypeBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000010; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder clearReceiverType() { + if (receiverTypeBuilder_ == null) { + receiverType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + onChanged(); + } else { + receiverTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder getReceiverTypeBuilder() { + bitField0_ |= 0x00000010; + onChanged(); + return getReceiverTypeFieldBuilder().getBuilder(); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReceiverTypeOrBuilder() { + if (receiverTypeBuilder_ != null) { + return receiverTypeBuilder_.getMessageOrBuilder(); + } else { + return receiverType_; + } + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder> + getReceiverTypeFieldBuilder() { + if (receiverTypeBuilder_ == null) { + receiverTypeBuilder_ = new com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder>( + receiverType_, + getParentForChildren(), + isClean()); + receiverType_ = null; + } + return receiverTypeBuilder_; + } + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> valueParameter_ = + java.util.Collections.emptyList(); + private void ensureValueParameterIsMutable() { + if (!((bitField0_ & 0x00000020) == 0x00000020)) { + valueParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter>(valueParameter_); + bitField0_ |= 0x00000020; + } + } + + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> valueParameterBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> getValueParameterList() { + if (valueParameterBuilder_ == null) { + return java.util.Collections.unmodifiableList(valueParameter_); + } else { + return valueParameterBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public int getValueParameterCount() { + if (valueParameterBuilder_ == null) { + return valueParameter_.size(); + } else { + return valueParameterBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getValueParameter(int index) { + if (valueParameterBuilder_ == null) { + return valueParameter_.get(index); + } else { + return valueParameterBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder setValueParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter value) { + if (valueParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.set(index, value); + onChanged(); + } else { + valueParameterBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder setValueParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder builderForValue) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + valueParameter_.set(index, builderForValue.build()); + onChanged(); + } else { + valueParameterBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addValueParameter(org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter value) { + if (valueParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.add(value); + onChanged(); + } else { + valueParameterBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addValueParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter value) { + if (valueParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.add(index, value); + onChanged(); + } else { + valueParameterBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addValueParameter( + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder builderForValue) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + valueParameter_.add(builderForValue.build()); + onChanged(); + } else { + valueParameterBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addValueParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder builderForValue) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + valueParameter_.add(index, builderForValue.build()); + onChanged(); + } else { + valueParameterBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addAllValueParameter( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter> values) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + super.addAll(values, valueParameter_); + onChanged(); + } else { + valueParameterBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder clearValueParameter() { + if (valueParameterBuilder_ == null) { + valueParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000020); + onChanged(); + } else { + valueParameterBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder removeValueParameter(int index) { + if (valueParameterBuilder_ == null) { + ensureValueParameterIsMutable(); + valueParameter_.remove(index); + onChanged(); + } else { + valueParameterBuilder_.remove(index); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder getValueParameterBuilder( + int index) { + return getValueParameterFieldBuilder().getBuilder(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getValueParameterOrBuilder( + int index) { + if (valueParameterBuilder_ == null) { + return valueParameter_.get(index); } else { + return valueParameterBuilder_.getMessageOrBuilder(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getValueParameterOrBuilderList() { + if (valueParameterBuilder_ != null) { + return valueParameterBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(valueParameter_); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder addValueParameterBuilder() { + return getValueParameterFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder addValueParameterBuilder( + int index) { + return getValueParameterFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance()); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder> + getValueParameterBuilderList() { + return getValueParameterFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getValueParameterFieldBuilder() { + if (valueParameterBuilder_ == null) { + valueParameterBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder>( + valueParameter_, + ((bitField0_ & 0x00000020) == 0x00000020), + getParentForChildren(), + isClean()); + valueParameter_ = null; + } + return valueParameterBuilder_; + } + + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Function) + } + + static { + defaultInstance = new Function(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Function) + } + + public interface PropertyOrBuilder extends + com.google.protobuf.GeneratedMessage. + ExtendableMessageOrBuilder<Property> { + + // optional int32 flags = 1; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + boolean hasFlags(); + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + int getFlags(); + + // required int32 name = 2; + /** + * <code>required int32 name = 2;</code> + */ + boolean hasName(); + /** + * <code>required int32 name = 2;</code> + */ + int getName(); + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + boolean hasReturnType(); + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReturnType(); + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReturnTypeOrBuilder(); + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> + getTypeParameterList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter getTypeParameter(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + int getTypeParameterCount(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> + getTypeParameterOrBuilderList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder getTypeParameterOrBuilder( + int index); + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + boolean hasReceiverType(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReceiverType(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReceiverTypeOrBuilder(); + + // optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6; + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + boolean hasSetterValueParameter(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getSetterValueParameter(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getSetterValueParameterOrBuilder(); + + // optional int32 getter_flags = 7; + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + boolean hasGetterFlags(); + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + int getGetterFlags(); + + // optional int32 setter_flags = 8; + /** + * <code>optional int32 setter_flags = 8;</code> + */ + boolean hasSetterFlags(); + /** + * <code>optional int32 setter_flags = 8;</code> + */ + int getSetterFlags(); + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Property} + */ + public static final class Property extends + com.google.protobuf.GeneratedMessage.ExtendableMessage< + Property> implements PropertyOrBuilder { + // Use Property.newBuilder() to construct. + private Property(com.google.protobuf.GeneratedMessage.ExtendableBuilder<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property, ?> builder) { + super(builder); + this.unknownFields = builder.getUnknownFields(); + } + private Property(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } + + private static final Property defaultInstance; + public static Property getDefaultInstance() { + return defaultInstance; + } + + public Property getDefaultInstanceForType() { + return defaultInstance; + } + + private final com.google.protobuf.UnknownFieldSet unknownFields; + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Property( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + flags_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + name_ = input.readInt32(); + break; + } + case 26: { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder subBuilder = null; + if (((bitField0_ & 0x00000004) == 0x00000004)) { + subBuilder = returnType_.toBuilder(); + } + returnType_ = input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(returnType_); + returnType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000004; + break; + } + case 34: { + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter>(); + mutable_bitField0_ |= 0x00000008; + } + typeParameter_.add(input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.PARSER, extensionRegistry)); + break; + } + case 42: { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder subBuilder = null; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + subBuilder = receiverType_.toBuilder(); + } + receiverType_ = input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(receiverType_); + receiverType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000008; + break; + } + case 50: { + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder subBuilder = null; + if (((bitField0_ & 0x00000010) == 0x00000010)) { + subBuilder = setterValueParameter_.toBuilder(); + } + setterValueParameter_ = input.readMessage(org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(setterValueParameter_); + setterValueParameter_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000010; + break; + } + case 56: { + bitField0_ |= 0x00000020; + getterFlags_ = input.readInt32(); + break; + } + case 64: { + bitField0_ |= 0x00000040; + setterFlags_ = input.readInt32(); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = java.util.Collections.unmodifiableList(typeParameter_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Property_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Property_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder.class); + } + + public static com.google.protobuf.Parser<Property> PARSER = + new com.google.protobuf.AbstractParser<Property>() { + public Property parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Property(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser<Property> getParserForType() { + return PARSER; + } + + private int bitField0_; + // optional int32 flags = 1; + public static final int FLAGS_FIELD_NUMBER = 1; + private int flags_; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public int getFlags() { + return flags_; + } + + // required int32 name = 2; + public static final int NAME_FIELD_NUMBER = 2; + private int name_; + /** + * <code>required int32 name = 2;</code> + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>required int32 name = 2;</code> + */ + public int getName() { + return name_; + } + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + public static final int RETURN_TYPE_FIELD_NUMBER = 3; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Type returnType_; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public boolean hasReturnType() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReturnType() { + return returnType_; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReturnTypeOrBuilder() { + return returnType_; + } + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + public static final int TYPE_PARAMETER_FIELD_NUMBER = 4; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> typeParameter_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> getTypeParameterList() { + return typeParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> + getTypeParameterOrBuilderList() { + return typeParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public int getTypeParameterCount() { + return typeParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter getTypeParameter(int index) { + return typeParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder getTypeParameterOrBuilder( + int index) { + return typeParameter_.get(index); + } + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + public static final int RECEIVER_TYPE_FIELD_NUMBER = 5; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Type receiverType_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public boolean hasReceiverType() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReceiverType() { + return receiverType_; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReceiverTypeOrBuilder() { + return receiverType_; + } + + // optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6; + public static final int SETTER_VALUE_PARAMETER_FIELD_NUMBER = 6; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter setterValueParameter_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public boolean hasSetterValueParameter() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getSetterValueParameter() { + return setterValueParameter_; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getSetterValueParameterOrBuilder() { + return setterValueParameter_; + } + + // optional int32 getter_flags = 7; + public static final int GETTER_FLAGS_FIELD_NUMBER = 7; + private int getterFlags_; + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + public boolean hasGetterFlags() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + public int getGetterFlags() { + return getterFlags_; + } + + // optional int32 setter_flags = 8; + public static final int SETTER_FLAGS_FIELD_NUMBER = 8; + private int setterFlags_; + /** + * <code>optional int32 setter_flags = 8;</code> + */ + public boolean hasSetterFlags() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + /** + * <code>optional int32 setter_flags = 8;</code> + */ + public int getSetterFlags() { + return setterFlags_; + } + + private void initFields() { + flags_ = 0; + name_ = 0; + returnType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + typeParameter_ = java.util.Collections.emptyList(); + receiverType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + setterValueParameter_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance(); + getterFlags_ = 0; + setterFlags_ = 0; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasReturnType()) { + memoizedIsInitialized = 0; + return false; + } + if (!getReturnType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + for (int i = 0; i < getTypeParameterCount(); i++) { + if (!getTypeParameter(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (hasReceiverType()) { + if (!getReceiverType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (hasSetterValueParameter()) { + if (!getSetterValueParameter().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (!extensionsAreInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + com.google.protobuf.GeneratedMessage + .ExtendableMessage<org.jetbrains.kotlin.serialization.DebugProtoBuf.Property>.ExtensionWriter extensionWriter = + newExtensionWriter(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, flags_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeInt32(2, name_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, returnType_); + } + for (int i = 0; i < typeParameter_.size(); i++) { + output.writeMessage(4, typeParameter_.get(i)); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeMessage(5, receiverType_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeMessage(6, setterValueParameter_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeInt32(7, getterFlags_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeInt32(8, setterFlags_); + } + extensionWriter.writeUntil(200, output); + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, flags_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(2, name_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, returnType_); + } + for (int i = 0; i < typeParameter_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, typeParameter_.get(i)); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, receiverType_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, setterValueParameter_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(7, getterFlags_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(8, setterFlags_); + } + size += extensionsSerializedSize(); + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jetbrains.kotlin.serialization.DebugProtoBuf.Property prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Property} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.ExtendableBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property, Builder> implements org.jetbrains.kotlin.serialization.DebugProtoBuf.PropertyOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Property_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Property_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.Builder.class); + } + + // Construct using org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getReturnTypeFieldBuilder(); + getTypeParameterFieldBuilder(); + getReceiverTypeFieldBuilder(); + getSetterValueParameterFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + flags_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + if (returnTypeBuilder_ == null) { + returnType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + } else { + returnTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + if (typeParameterBuilder_ == null) { + typeParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + } else { + typeParameterBuilder_.clear(); + } + if (receiverTypeBuilder_ == null) { + receiverType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + } else { + receiverTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); + if (setterValueParameterBuilder_ == null) { + setterValueParameter_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance(); + } else { + setterValueParameterBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000020); + getterFlags_ = 0; + bitField0_ = (bitField0_ & ~0x00000040); + setterFlags_ = 0; + bitField0_ = (bitField0_ & ~0x00000080); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Property_descriptor; + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property getDefaultInstanceForType() { + return org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.getDefaultInstance(); + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property build() { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Property buildPartial() { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property result = new org.jetbrains.kotlin.serialization.DebugProtoBuf.Property(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.flags_ = flags_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (returnTypeBuilder_ == null) { + result.returnType_ = returnType_; + } else { + result.returnType_ = returnTypeBuilder_.build(); + } + if (typeParameterBuilder_ == null) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = java.util.Collections.unmodifiableList(typeParameter_); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.typeParameter_ = typeParameter_; + } else { + result.typeParameter_ = typeParameterBuilder_.build(); + } + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000008; + } + if (receiverTypeBuilder_ == null) { + result.receiverType_ = receiverType_; + } else { + result.receiverType_ = receiverTypeBuilder_.build(); + } + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000010; + } + if (setterValueParameterBuilder_ == null) { + result.setterValueParameter_ = setterValueParameter_; + } else { + result.setterValueParameter_ = setterValueParameterBuilder_.build(); + } + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000020; + } + result.getterFlags_ = getterFlags_; + if (((from_bitField0_ & 0x00000080) == 0x00000080)) { + to_bitField0_ |= 0x00000040; + } + result.setterFlags_ = setterFlags_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.jetbrains.kotlin.serialization.DebugProtoBuf.Property) { + return mergeFrom((org.jetbrains.kotlin.serialization.DebugProtoBuf.Property)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Property other) { + if (other == org.jetbrains.kotlin.serialization.DebugProtoBuf.Property.getDefaultInstance()) return this; + if (other.hasFlags()) { + setFlags(other.getFlags()); + } + if (other.hasName()) { + setName(other.getName()); + } + if (other.hasReturnType()) { + mergeReturnType(other.getReturnType()); + } + if (typeParameterBuilder_ == null) { + if (!other.typeParameter_.isEmpty()) { + if (typeParameter_.isEmpty()) { + typeParameter_ = other.typeParameter_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensureTypeParameterIsMutable(); + typeParameter_.addAll(other.typeParameter_); + } + onChanged(); + } + } else { + if (!other.typeParameter_.isEmpty()) { + if (typeParameterBuilder_.isEmpty()) { + typeParameterBuilder_.dispose(); + typeParameterBuilder_ = null; + typeParameter_ = other.typeParameter_; + bitField0_ = (bitField0_ & ~0x00000008); + typeParameterBuilder_ = + com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? + getTypeParameterFieldBuilder() : null; + } else { + typeParameterBuilder_.addAllMessages(other.typeParameter_); + } + } + } + if (other.hasReceiverType()) { + mergeReceiverType(other.getReceiverType()); + } + if (other.hasSetterValueParameter()) { + mergeSetterValueParameter(other.getSetterValueParameter()); + } + if (other.hasGetterFlags()) { + setGetterFlags(other.getGetterFlags()); + } + if (other.hasSetterFlags()) { + setSetterFlags(other.getSetterFlags()); + } + this.mergeExtensionFields(other); + this.mergeUnknownFields(other.getUnknownFields()); + return this; } - size += extensionsSerializedSize(); - size += getUnknownFields().getSerializedSize(); - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; - @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); - } - - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(org.jetbrains.kotlin.serialization.DebugProtoBuf.Package prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code org.jetbrains.kotlin.serialization.Package} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.ExtendableBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Package, Builder> implements org.jetbrains.kotlin.serialization.DebugProtoBuf.PackageOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_descriptor; + public final boolean isInitialized() { + if (!hasName()) { + + return false; + } + if (!hasReturnType()) { + + return false; + } + if (!getReturnType().isInitialized()) { + + return false; + } + for (int i = 0; i < getTypeParameterCount(); i++) { + if (!getTypeParameter(i).isInitialized()) { + + return false; + } + } + if (hasReceiverType()) { + if (!getReceiverType().isInitialized()) { + + return false; + } + } + if (hasSetterValueParameter()) { + if (!getSetterValueParameter().isInitialized()) { + + return false; + } + } + if (!extensionsAreInitialized()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jetbrains.kotlin.serialization.DebugProtoBuf.Property parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jetbrains.kotlin.serialization.DebugProtoBuf.Property) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + // optional int32 flags = 1; + private int flags_ ; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public int getFlags() { + return flags_; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public Builder setFlags(int value) { + bitField0_ |= 0x00000001; + flags_ = value; + onChanged(); + return this; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public Builder clearFlags() { + bitField0_ = (bitField0_ & ~0x00000001); + flags_ = 0; + onChanged(); + return this; + } + + // required int32 name = 2; + private int name_ ; + /** + * <code>required int32 name = 2;</code> + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>required int32 name = 2;</code> + */ + public int getName() { + return name_; + } + /** + * <code>required int32 name = 2;</code> + */ + public Builder setName(int value) { + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + /** + * <code>required int32 name = 2;</code> + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = 0; + onChanged(); + return this; + } + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Type returnType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder> returnTypeBuilder_; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public boolean hasReturnType() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReturnType() { + if (returnTypeBuilder_ == null) { + return returnType_; + } else { + return returnTypeBuilder_.getMessage(); + } + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder setReturnType(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type value) { + if (returnTypeBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + returnType_ = value; + onChanged(); + } else { + returnTypeBuilder_.setMessage(value); + } + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder setReturnType( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder builderForValue) { + if (returnTypeBuilder_ == null) { + returnType_ = builderForValue.build(); + onChanged(); + } else { + returnTypeBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder mergeReturnType(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type value) { + if (returnTypeBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + returnType_ != org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance()) { + returnType_ = + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.newBuilder(returnType_).mergeFrom(value).buildPartial(); + } else { + returnType_ = value; + } + onChanged(); + } else { + returnTypeBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder clearReturnType() { + if (returnTypeBuilder_ == null) { + returnType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + onChanged(); + } else { + returnTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder getReturnTypeBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getReturnTypeFieldBuilder().getBuilder(); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReturnTypeOrBuilder() { + if (returnTypeBuilder_ != null) { + return returnTypeBuilder_.getMessageOrBuilder(); + } else { + return returnType_; + } + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder> + getReturnTypeFieldBuilder() { + if (returnTypeBuilder_ == null) { + returnTypeBuilder_ = new com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder>( + returnType_, + getParentForChildren(), + isClean()); + returnType_ = null; + } + return returnTypeBuilder_; } - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.class, org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.Builder.class); + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> typeParameter_ = + java.util.Collections.emptyList(); + private void ensureTypeParameterIsMutable() { + if (!((bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter>(typeParameter_); + bitField0_ |= 0x00000008; + } } - // Construct using org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> typeParameterBuilder_; + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> getTypeParameterList() { + if (typeParameterBuilder_ == null) { + return java.util.Collections.unmodifiableList(typeParameter_); + } else { + return typeParameterBuilder_.getMessageList(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public int getTypeParameterCount() { + if (typeParameterBuilder_ == null) { + return typeParameter_.size(); + } else { + return typeParameterBuilder_.getCount(); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter getTypeParameter(int index) { + if (typeParameterBuilder_ == null) { + return typeParameter_.get(index); + } else { + return typeParameterBuilder_.getMessage(index); + } + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder setTypeParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter value) { + if (typeParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.set(index, value); + onChanged(); + } else { + typeParameterBuilder_.setMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder setTypeParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder builderForValue) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + typeParameter_.set(index, builderForValue.build()); + onChanged(); + } else { + typeParameterBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter(org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter value) { + if (typeParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.add(value); + onChanged(); + } else { + typeParameterBuilder_.addMessage(value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter value) { + if (typeParameterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.add(index, value); + onChanged(); + } else { + typeParameterBuilder_.addMessage(index, value); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder builderForValue) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + typeParameter_.add(builderForValue.build()); + onChanged(); + } else { + typeParameterBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder builderForValue) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + typeParameter_.add(index, builderForValue.build()); + onChanged(); + } else { + typeParameterBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addAllTypeParameter( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter> values) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + super.addAll(values, typeParameter_); + onChanged(); + } else { + typeParameterBuilder_.addAllMessages(values); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder clearTypeParameter() { + if (typeParameterBuilder_ == null) { + typeParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + onChanged(); + } else { + typeParameterBuilder_.clear(); + } + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder removeTypeParameter(int index) { + if (typeParameterBuilder_ == null) { + ensureTypeParameterIsMutable(); + typeParameter_.remove(index); + onChanged(); + } else { + typeParameterBuilder_.remove(index); + } + return this; } - - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder getTypeParameterBuilder( + int index) { + return getTypeParameterFieldBuilder().getBuilder(index); } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { - getMemberFieldBuilder(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder getTypeParameterOrBuilder( + int index) { + if (typeParameterBuilder_ == null) { + return typeParameter_.get(index); } else { + return typeParameterBuilder_.getMessageOrBuilder(index); } } - private static Builder create() { - return new Builder(); - } - - public Builder clear() { - super.clear(); - if (memberBuilder_ == null) { - member_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> + getTypeParameterOrBuilderList() { + if (typeParameterBuilder_ != null) { + return typeParameterBuilder_.getMessageOrBuilderList(); } else { - memberBuilder_.clear(); + return java.util.Collections.unmodifiableList(typeParameter_); } - return this; } - - public Builder clone() { - return create().mergeFrom(buildPartial()); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder addTypeParameterBuilder() { + return getTypeParameterFieldBuilder().addBuilder( + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.getDefaultInstance()); } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.jetbrains.kotlin.serialization.DebugProtoBuf.internal_static_org_jetbrains_kotlin_serialization_Package_descriptor; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder addTypeParameterBuilder( + int index) { + return getTypeParameterFieldBuilder().addBuilder( + index, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.getDefaultInstance()); } - - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Package getDefaultInstanceForType() { - return org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.getDefaultInstance(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder> + getTypeParameterBuilderList() { + return getTypeParameterFieldBuilder().getBuilderList(); } - - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Package build() { - org.jetbrains.kotlin.serialization.DebugProtoBuf.Package result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + private com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder> + getTypeParameterFieldBuilder() { + if (typeParameterBuilder_ == null) { + typeParameterBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeParameterOrBuilder>( + typeParameter_, + ((bitField0_ & 0x00000008) == 0x00000008), + getParentForChildren(), + isClean()); + typeParameter_ = null; } - return result; + return typeParameterBuilder_; } - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Package buildPartial() { - org.jetbrains.kotlin.serialization.DebugProtoBuf.Package result = new org.jetbrains.kotlin.serialization.DebugProtoBuf.Package(this); - int from_bitField0_ = bitField0_; - if (memberBuilder_ == null) { - if (((bitField0_ & 0x00000001) == 0x00000001)) { - member_ = java.util.Collections.unmodifiableList(member_); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.member_ = member_; + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.Type receiverType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder> receiverTypeBuilder_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public boolean hasReceiverType() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type getReceiverType() { + if (receiverTypeBuilder_ == null) { + return receiverType_; } else { - result.member_ = memberBuilder_.build(); + return receiverTypeBuilder_.getMessage(); } - onBuilt(); - return result; } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.jetbrains.kotlin.serialization.DebugProtoBuf.Package) { - return mergeFrom((org.jetbrains.kotlin.serialization.DebugProtoBuf.Package)other); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder setReceiverType(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type value) { + if (receiverTypeBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + receiverType_ = value; + onChanged(); } else { - super.mergeFrom(other); - return this; + receiverTypeBuilder_.setMessage(value); } + bitField0_ |= 0x00000010; + return this; } - - public Builder mergeFrom(org.jetbrains.kotlin.serialization.DebugProtoBuf.Package other) { - if (other == org.jetbrains.kotlin.serialization.DebugProtoBuf.Package.getDefaultInstance()) return this; - if (memberBuilder_ == null) { - if (!other.member_.isEmpty()) { - if (member_.isEmpty()) { - member_ = other.member_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureMemberIsMutable(); - member_.addAll(other.member_); - } - onChanged(); - } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder setReceiverType( + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder builderForValue) { + if (receiverTypeBuilder_ == null) { + receiverType_ = builderForValue.build(); + onChanged(); } else { - if (!other.member_.isEmpty()) { - if (memberBuilder_.isEmpty()) { - memberBuilder_.dispose(); - memberBuilder_ = null; - member_ = other.member_; - bitField0_ = (bitField0_ & ~0x00000001); - memberBuilder_ = - com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? - getMemberFieldBuilder() : null; - } else { - memberBuilder_.addAllMessages(other.member_); - } - } + receiverTypeBuilder_.setMessage(builderForValue.build()); } - this.mergeExtensionFields(other); - this.mergeUnknownFields(other.getUnknownFields()); + bitField0_ |= 0x00000010; return this; } - - public final boolean isInitialized() { - for (int i = 0; i < getMemberCount(); i++) { - if (!getMember(i).isInitialized()) { - - return false; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder mergeReceiverType(org.jetbrains.kotlin.serialization.DebugProtoBuf.Type value) { + if (receiverTypeBuilder_ == null) { + if (((bitField0_ & 0x00000010) == 0x00000010) && + receiverType_ != org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance()) { + receiverType_ = + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.newBuilder(receiverType_).mergeFrom(value).buildPartial(); + } else { + receiverType_ = value; } + onChanged(); + } else { + receiverTypeBuilder_.mergeFrom(value); } - if (!extensionsAreInitialized()) { - - return false; - } - return true; + bitField0_ |= 0x00000010; + return this; } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.jetbrains.kotlin.serialization.DebugProtoBuf.Package parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.jetbrains.kotlin.serialization.DebugProtoBuf.Package) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder clearReceiverType() { + if (receiverTypeBuilder_ == null) { + receiverType_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.getDefaultInstance(); + onChanged(); + } else { + receiverTypeBuilder_.clear(); } + bitField0_ = (bitField0_ & ~0x00000010); return this; } - private int bitField0_; - - // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; - private java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> member_ = - java.util.Collections.emptyList(); - private void ensureMemberIsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable>(member_); - bitField0_ |= 0x00000001; - } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder getReceiverTypeBuilder() { + bitField0_ |= 0x00000010; + onChanged(); + return getReceiverTypeFieldBuilder().getBuilder(); } - - private com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> memberBuilder_; - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> getMemberList() { - if (memberBuilder_ == null) { - return java.util.Collections.unmodifiableList(member_); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getReceiverTypeOrBuilder() { + if (receiverTypeBuilder_ != null) { + return receiverTypeBuilder_.getMessageOrBuilder(); } else { - return memberBuilder_.getMessageList(); + return receiverType_; } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> */ - public int getMemberCount() { - if (memberBuilder_ == null) { - return member_.size(); - } else { - return memberBuilder_.getCount(); + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder> + getReceiverTypeFieldBuilder() { + if (receiverTypeBuilder_ == null) { + receiverTypeBuilder_ = new com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.Type, org.jetbrains.kotlin.serialization.DebugProtoBuf.Type.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder>( + receiverType_, + getParentForChildren(), + isClean()); + receiverType_ = null; } + return receiverTypeBuilder_; + } + + // optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6; + private org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter setterValueParameter_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> setterValueParameterBuilder_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public boolean hasSetterValueParameter() { + return ((bitField0_ & 0x00000020) == 0x00000020); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable getMember(int index) { - if (memberBuilder_ == null) { - return member_.get(index); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter getSetterValueParameter() { + if (setterValueParameterBuilder_ == null) { + return setterValueParameter_; } else { - return memberBuilder_.getMessage(index); + return setterValueParameterBuilder_.getMessage(); } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder setMember( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (memberBuilder_ == null) { + public Builder setSetterValueParameter(org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter value) { + if (setterValueParameterBuilder_ == null) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.set(index, value); + setterValueParameter_ = value; onChanged(); } else { - memberBuilder_.setMessage(index, value); + setterValueParameterBuilder_.setMessage(value); } + bitField0_ |= 0x00000020; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder setMember( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - member_.set(index, builderForValue.build()); + public Builder setSetterValueParameter( + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder builderForValue) { + if (setterValueParameterBuilder_ == null) { + setterValueParameter_ = builderForValue.build(); onChanged(); } else { - memberBuilder_.setMessage(index, builderForValue.build()); + setterValueParameterBuilder_.setMessage(builderForValue.build()); } + bitField0_ |= 0x00000020; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder addMember(org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (memberBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); + public Builder mergeSetterValueParameter(org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter value) { + if (setterValueParameterBuilder_ == null) { + if (((bitField0_ & 0x00000020) == 0x00000020) && + setterValueParameter_ != org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance()) { + setterValueParameter_ = + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.newBuilder(setterValueParameter_).mergeFrom(value).buildPartial(); + } else { + setterValueParameter_ = value; } - ensureMemberIsMutable(); - member_.add(value); onChanged(); } else { - memberBuilder_.addMessage(value); + setterValueParameterBuilder_.mergeFrom(value); } + bitField0_ |= 0x00000020; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder addMember( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable value) { - if (memberBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureMemberIsMutable(); - member_.add(index, value); + public Builder clearSetterValueParameter() { + if (setterValueParameterBuilder_ == null) { + setterValueParameter_ = org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.getDefaultInstance(); onChanged(); } else { - memberBuilder_.addMessage(index, value); + setterValueParameterBuilder_.clear(); } + bitField0_ = (bitField0_ & ~0x00000020); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder addMember( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - member_.add(builderForValue.build()); - onChanged(); - } else { - memberBuilder_.addMessage(builderForValue.build()); - } - return this; + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder getSetterValueParameterBuilder() { + bitField0_ |= 0x00000020; + onChanged(); + return getSetterValueParameterFieldBuilder().getBuilder(); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder addMember( - int index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder builderForValue) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - member_.add(index, builderForValue.build()); - onChanged(); + public org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder getSetterValueParameterOrBuilder() { + if (setterValueParameterBuilder_ != null) { + return setterValueParameterBuilder_.getMessageOrBuilder(); } else { - memberBuilder_.addMessage(index, builderForValue.build()); + return setterValueParameter_; } - return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder addAllMember( - java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable> values) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - super.addAll(values, member_); - onChanged(); - } else { - memberBuilder_.addAllMessages(values); + private com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder> + getSetterValueParameterFieldBuilder() { + if (setterValueParameterBuilder_ == null) { + setterValueParameterBuilder_ = new com.google.protobuf.SingleFieldBuilder< + org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameter.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.ValueParameterOrBuilder>( + setterValueParameter_, + getParentForChildren(), + isClean()); + setterValueParameter_ = null; } - return this; + return setterValueParameterBuilder_; } + + // optional int32 getter_flags = 7; + private int getterFlags_ ; /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> */ - public Builder clearMember() { - if (memberBuilder_ == null) { - member_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - } else { - memberBuilder_.clear(); - } - return this; + public boolean hasGetterFlags() { + return ((bitField0_ & 0x00000040) == 0x00000040); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> */ - public Builder removeMember(int index) { - if (memberBuilder_ == null) { - ensureMemberIsMutable(); - member_.remove(index); - onChanged(); - } else { - memberBuilder_.remove(index); - } - return this; + public int getGetterFlags() { + return getterFlags_; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder getMemberBuilder( - int index) { - return getMemberFieldBuilder().getBuilder(index); + public Builder setGetterFlags(int value) { + bitField0_ |= 0x00000040; + getterFlags_ = value; + onChanged(); + return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder getMemberOrBuilder( - int index) { - if (memberBuilder_ == null) { - return member_.get(index); } else { - return memberBuilder_.getMessageOrBuilder(index); - } + public Builder clearGetterFlags() { + bitField0_ = (bitField0_ & ~0x00000040); + getterFlags_ = 0; + onChanged(); + return this; } + + // optional int32 setter_flags = 8; + private int setterFlags_ ; /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 setter_flags = 8;</code> */ - public java.util.List<? extends org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> - getMemberOrBuilderList() { - if (memberBuilder_ != null) { - return memberBuilder_.getMessageOrBuilderList(); - } else { - return java.util.Collections.unmodifiableList(member_); - } + public boolean hasSetterFlags() { + return ((bitField0_ & 0x00000080) == 0x00000080); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 setter_flags = 8;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addMemberBuilder() { - return getMemberFieldBuilder().addBuilder( - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + public int getSetterFlags() { + return setterFlags_; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 setter_flags = 8;</code> */ - public org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder addMemberBuilder( - int index) { - return getMemberFieldBuilder().addBuilder( - index, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.getDefaultInstance()); + public Builder setSetterFlags(int value) { + bitField0_ |= 0x00000080; + setterFlags_ = value; + onChanged(); + return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 setter_flags = 8;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder> - getMemberBuilderList() { - return getMemberFieldBuilder().getBuilderList(); - } - private com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder> - getMemberFieldBuilder() { - if (memberBuilder_ == null) { - memberBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< - org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable, org.jetbrains.kotlin.serialization.DebugProtoBuf.Callable.Builder, org.jetbrains.kotlin.serialization.DebugProtoBuf.CallableOrBuilder>( - member_, - ((bitField0_ & 0x00000001) == 0x00000001), - getParentForChildren(), - isClean()); - member_ = null; - } - return memberBuilder_; + public Builder clearSetterFlags() { + bitField0_ = (bitField0_ & ~0x00000080); + setterFlags_ = 0; + onChanged(); + return this; } - // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Package) + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Property) } static { - defaultInstance = new Package(true); + defaultInstance = new Property(true); defaultInstance.initFields(); } - // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Package) + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Property) } public interface CallableOrBuilder extends @@ -15999,6 +22652,21 @@ public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getVarargE private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_org_jetbrains_kotlin_serialization_Package_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_org_jetbrains_kotlin_serialization_Constructor_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_org_jetbrains_kotlin_serialization_Constructor_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_org_jetbrains_kotlin_serialization_Function_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_org_jetbrains_kotlin_serialization_Function_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_org_jetbrains_kotlin_serialization_Property_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_org_jetbrains_kotlin_serialization_Property_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_org_jetbrains_kotlin_serialization_Callable_descriptor; private static @@ -16068,49 +22736,80 @@ public org.jetbrains.kotlin.serialization.DebugProtoBuf.TypeOrBuilder getVarargE "eParameter.Variance:\003INV\022=\n\013upper_bound\030" + "\005 \003(\0132(.org.jetbrains.kotlin.serializati" + "on.Type\"$\n\010Variance\022\006\n\002IN\020\000\022\007\n\003OUT\020\001\022\007\n\003", - "INV\020\002\"\325\005\n\005Class\022\020\n\005flags\030\001 \001(\005:\0010\022\025\n\007fq_" + + "INV\020\002\"\233\007\n\005Class\022\020\n\005flags\030\001 \001(\005:\0010\022\025\n\007fq_" + "name\030\003 \002(\005B\004\220\265\030\001\022#\n\025companion_object_nam" + "e\030\004 \001(\005B\004\210\265\030\001\022I\n\016type_parameter\030\005 \003(\01321." + "org.jetbrains.kotlin.serialization.TypeP" + "arameter\022;\n\tsupertype\030\006 \003(\0132(.org.jetbra" + "ins.kotlin.serialization.Type\022!\n\021nested_" + - "class_name\030\007 \003(\005B\006\020\001\210\265\030\001\022<\n\006member\030\013 \003(\013" + - "2,.org.jetbrains.kotlin.serialization.Ca" + - "llable\022\032\n\nenum_entry\030\014 \003(\005B\006\020\001\210\265\030\001\022Y\n\023pr" + - "imary_constructor\030\r \001(\0132<.org.jetbrains.", - "kotlin.serialization.Class.PrimaryConstr" + - "uctor\022K\n\025secondary_constructor\030\016 \003(\0132,.o" + - "rg.jetbrains.kotlin.serialization.Callab" + - "le\032P\n\022PrimaryConstructor\022:\n\004data\030\001 \001(\0132," + + "class_name\030\007 \003(\005B\006\020\001\210\265\030\001\022D\n\013constructor\030" + + "\010 \003(\0132/.org.jetbrains.kotlin.serializati" + + "on.Constructor\022>\n\010function\030\t \003(\0132,.org.j" + + "etbrains.kotlin.serialization.Function\022>", + "\n\010property\030\n \003(\0132,.org.jetbrains.kotlin." + + "serialization.Property\022<\n\006member\030\013 \003(\0132," + ".org.jetbrains.kotlin.serialization.Call" + - "able\"x\n\004Kind\022\t\n\005CLASS\020\000\022\r\n\tINTERFACE\020\001\022\016" + - "\n\nENUM_CLASS\020\002\022\016\n\nENUM_ENTRY\020\003\022\024\n\020ANNOTA" + - "TION_CLASS\020\004\022\n\n\006OBJECT\020\005\022\024\n\020COMPANION_OB" + - "JECT\020\006*\005\010d\020\310\001\"N\n\007Package\022<\n\006member\030\001 \003(\013" + - "2,.org.jetbrains.kotlin.serialization.Ca", - "llable*\005\010d\020\310\001\"\370\002\n\010Callable\022\r\n\005flags\030\001 \001(" + - "\005\022\024\n\014getter_flags\030\t \001(\005\022\024\n\014setter_flags\030" + - "\n \001(\005\022I\n\016type_parameter\030\004 \003(\01321.org.jetb" + - "rains.kotlin.serialization.TypeParameter" + - "\022?\n\rreceiver_type\030\005 \001(\0132(.org.jetbrains." + - "kotlin.serialization.Type\022\022\n\004name\030\006 \002(\005B" + - "\004\210\265\030\001\022K\n\017value_parameter\030\007 \003(\01322.org.jet" + - "brains.kotlin.serialization.ValueParamet" + - "er\022=\n\013return_type\030\010 \002(\0132(.org.jetbrains." + - "kotlin.serialization.Type*\005\010d\020\310\001\"\271\001\n\016Val", - "ueParameter\022\r\n\005flags\030\001 \001(\005\022\022\n\004name\030\002 \002(\005" + - "B\004\210\265\030\001\0226\n\004type\030\003 \002(\0132(.org.jetbrains.kot" + - "lin.serialization.Type\022E\n\023vararg_element" + - "_type\030\004 \001(\0132(.org.jetbrains.kotlin.seria" + - "lization.Type*\005\010d\020\310\001*9\n\010Modality\022\t\n\005FINA" + - "L\020\000\022\010\n\004OPEN\020\001\022\014\n\010ABSTRACT\020\002\022\n\n\006SEALED\020\003*" + - "b\n\nVisibility\022\014\n\010INTERNAL\020\000\022\013\n\007PRIVATE\020\001" + - "\022\r\n\tPROTECTED\020\002\022\n\n\006PUBLIC\020\003\022\023\n\017PRIVATE_T" + - "O_THIS\020\004\022\t\n\005LOCAL\020\005*:\n\014CallableKind\022\007\n\003F" + - "UN\020\000\022\007\n\003VAL\020\001\022\007\n\003VAR\020\002\022\017\n\013CONSTRUCTOR\020\003*", - "Q\n\nMemberKind\022\017\n\013DECLARATION\020\000\022\021\n\rFAKE_O" + - "VERRIDE\020\001\022\016\n\nDELEGATION\020\002\022\017\n\013SYNTHESIZED" + - "\020\003B\022B\rDebugProtoBuf\210\001\000" + "able\022\032\n\nenum_entry\030\014 \003(\005B\006\020\001\210\265\030\001\022Y\n\023prim" + + "ary_constructor\030\r \001(\0132<.org.jetbrains.ko" + + "tlin.serialization.Class.PrimaryConstruc" + + "tor\022K\n\025secondary_constructor\030\016 \003(\0132,.org" + + ".jetbrains.kotlin.serialization.Callable" + + "\032P\n\022PrimaryConstructor\022:\n\004data\030\001 \001(\0132,.o" + + "rg.jetbrains.kotlin.serialization.Callab", + "le\"x\n\004Kind\022\t\n\005CLASS\020\000\022\r\n\tINTERFACE\020\001\022\016\n\n" + + "ENUM_CLASS\020\002\022\016\n\nENUM_ENTRY\020\003\022\024\n\020ANNOTATI" + + "ON_CLASS\020\004\022\n\n\006OBJECT\020\005\022\024\n\020COMPANION_OBJE" + + "CT\020\006*\005\010d\020\310\001\"\224\002\n\007Package\022<\n\006member\030\001 \003(\0132" + + ",.org.jetbrains.kotlin.serialization.Cal" + + "lable\022D\n\013constructor\030\002 \003(\0132/.org.jetbrai" + + "ns.kotlin.serialization.Constructor\022>\n\010f" + + "unction\030\003 \003(\0132,.org.jetbrains.kotlin.ser" + + "ialization.Function\022>\n\010property\030\004 \003(\0132,." + + "org.jetbrains.kotlin.serialization.Prope", + "rty*\005\010d\020\310\001\"p\n\013Constructor\022\r\n\005flags\030\001 \001(\005" + + "\022K\n\017value_parameter\030\002 \003(\01322.org.jetbrain" + + "s.kotlin.serialization.ValueParameter*\005\010" + + "d\020\310\001\"\314\002\n\010Function\022\r\n\005flags\030\001 \001(\005\022\022\n\004name" + + "\030\002 \002(\005B\004\210\265\030\001\022=\n\013return_type\030\003 \002(\0132(.org." + + "jetbrains.kotlin.serialization.Type\022I\n\016t" + + "ype_parameter\030\004 \003(\01321.org.jetbrains.kotl" + + "in.serialization.TypeParameter\022?\n\rreceiv" + + "er_type\030\005 \001(\0132(.org.jetbrains.kotlin.ser" + + "ialization.Type\022K\n\017value_parameter\030\006 \003(\013", + "22.org.jetbrains.kotlin.serialization.Va" + + "lueParameter*\005\010d\020\310\001\"\377\002\n\010Property\022\r\n\005flag" + + "s\030\001 \001(\005\022\022\n\004name\030\002 \002(\005B\004\210\265\030\001\022=\n\013return_ty" + + "pe\030\003 \002(\0132(.org.jetbrains.kotlin.serializ" + + "ation.Type\022I\n\016type_parameter\030\004 \003(\01321.org" + + ".jetbrains.kotlin.serialization.TypePara" + + "meter\022?\n\rreceiver_type\030\005 \001(\0132(.org.jetbr" + + "ains.kotlin.serialization.Type\022R\n\026setter" + + "_value_parameter\030\006 \001(\01322.org.jetbrains.k" + + "otlin.serialization.ValueParameter\022\024\n\014ge", + "tter_flags\030\007 \001(\005\022\024\n\014setter_flags\030\010 \001(\005*\005" + + "\010d\020\310\001\"\370\002\n\010Callable\022\r\n\005flags\030\001 \001(\005\022\024\n\014get" + + "ter_flags\030\t \001(\005\022\024\n\014setter_flags\030\n \001(\005\022I\n" + + "\016type_parameter\030\004 \003(\01321.org.jetbrains.ko" + + "tlin.serialization.TypeParameter\022?\n\rrece" + + "iver_type\030\005 \001(\0132(.org.jetbrains.kotlin.s" + + "erialization.Type\022\022\n\004name\030\006 \002(\005B\004\210\265\030\001\022K\n" + + "\017value_parameter\030\007 \003(\01322.org.jetbrains.k" + + "otlin.serialization.ValueParameter\022=\n\013re" + + "turn_type\030\010 \002(\0132(.org.jetbrains.kotlin.s", + "erialization.Type*\005\010d\020\310\001\"\271\001\n\016ValueParame" + + "ter\022\r\n\005flags\030\001 \001(\005\022\022\n\004name\030\002 \002(\005B\004\210\265\030\001\0226" + + "\n\004type\030\003 \002(\0132(.org.jetbrains.kotlin.seri" + + "alization.Type\022E\n\023vararg_element_type\030\004 " + + "\001(\0132(.org.jetbrains.kotlin.serialization" + + ".Type*\005\010d\020\310\001*9\n\010Modality\022\t\n\005FINAL\020\000\022\010\n\004O" + + "PEN\020\001\022\014\n\010ABSTRACT\020\002\022\n\n\006SEALED\020\003*b\n\nVisib" + + "ility\022\014\n\010INTERNAL\020\000\022\013\n\007PRIVATE\020\001\022\r\n\tPROT" + + "ECTED\020\002\022\n\n\006PUBLIC\020\003\022\023\n\017PRIVATE_TO_THIS\020\004" + + "\022\t\n\005LOCAL\020\005*:\n\014CallableKind\022\007\n\003FUN\020\000\022\007\n\003", + "VAL\020\001\022\007\n\003VAR\020\002\022\017\n\013CONSTRUCTOR\020\003*Q\n\nMembe" + + "rKind\022\017\n\013DECLARATION\020\000\022\021\n\rFAKE_OVERRIDE\020" + + "\001\022\016\n\nDELEGATION\020\002\022\017\n\013SYNTHESIZED\020\003B\022B\rDe" + + "bugProtoBuf\210\001\000" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { @@ -16176,7 +22875,7 @@ public com.google.protobuf.ExtensionRegistry assignDescriptors( internal_static_org_jetbrains_kotlin_serialization_Class_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jetbrains_kotlin_serialization_Class_descriptor, - new java.lang.String[] { "Flags", "FqName", "CompanionObjectName", "TypeParameter", "Supertype", "NestedClassName", "Member", "EnumEntry", "PrimaryConstructor", "SecondaryConstructor", }); + new java.lang.String[] { "Flags", "FqName", "CompanionObjectName", "TypeParameter", "Supertype", "NestedClassName", "Constructor", "Function", "Property", "Member", "EnumEntry", "PrimaryConstructor", "SecondaryConstructor", }); internal_static_org_jetbrains_kotlin_serialization_Class_PrimaryConstructor_descriptor = internal_static_org_jetbrains_kotlin_serialization_Class_descriptor.getNestedTypes().get(0); internal_static_org_jetbrains_kotlin_serialization_Class_PrimaryConstructor_fieldAccessorTable = new @@ -16188,15 +22887,33 @@ public com.google.protobuf.ExtensionRegistry assignDescriptors( internal_static_org_jetbrains_kotlin_serialization_Package_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jetbrains_kotlin_serialization_Package_descriptor, - new java.lang.String[] { "Member", }); - internal_static_org_jetbrains_kotlin_serialization_Callable_descriptor = + new java.lang.String[] { "Member", "Constructor", "Function", "Property", }); + internal_static_org_jetbrains_kotlin_serialization_Constructor_descriptor = getDescriptor().getMessageTypes().get(7); + internal_static_org_jetbrains_kotlin_serialization_Constructor_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_org_jetbrains_kotlin_serialization_Constructor_descriptor, + new java.lang.String[] { "Flags", "ValueParameter", }); + internal_static_org_jetbrains_kotlin_serialization_Function_descriptor = + getDescriptor().getMessageTypes().get(8); + internal_static_org_jetbrains_kotlin_serialization_Function_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_org_jetbrains_kotlin_serialization_Function_descriptor, + new java.lang.String[] { "Flags", "Name", "ReturnType", "TypeParameter", "ReceiverType", "ValueParameter", }); + internal_static_org_jetbrains_kotlin_serialization_Property_descriptor = + getDescriptor().getMessageTypes().get(9); + internal_static_org_jetbrains_kotlin_serialization_Property_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_org_jetbrains_kotlin_serialization_Property_descriptor, + new java.lang.String[] { "Flags", "Name", "ReturnType", "TypeParameter", "ReceiverType", "SetterValueParameter", "GetterFlags", "SetterFlags", }); + internal_static_org_jetbrains_kotlin_serialization_Callable_descriptor = + getDescriptor().getMessageTypes().get(10); internal_static_org_jetbrains_kotlin_serialization_Callable_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jetbrains_kotlin_serialization_Callable_descriptor, new java.lang.String[] { "Flags", "GetterFlags", "SetterFlags", "TypeParameter", "ReceiverType", "Name", "ValueParameter", "ReturnType", }); internal_static_org_jetbrains_kotlin_serialization_ValueParameter_descriptor = - getDescriptor().getMessageTypes().get(8); + getDescriptor().getMessageTypes().get(11); internal_static_org_jetbrains_kotlin_serialization_ValueParameter_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jetbrains_kotlin_serialization_ValueParameter_descriptor, @@ -16217,6 +22934,8 @@ public com.google.protobuf.ExtensionRegistry assignDescriptors( registry.add(org.jetbrains.kotlin.serialization.DebugExtOptionsProtoBuf.nameIdInTable); registry.add(org.jetbrains.kotlin.serialization.DebugExtOptionsProtoBuf.nameIdInTable); registry.add(org.jetbrains.kotlin.serialization.DebugExtOptionsProtoBuf.nameIdInTable); + registry.add(org.jetbrains.kotlin.serialization.DebugExtOptionsProtoBuf.nameIdInTable); + registry.add(org.jetbrains.kotlin.serialization.DebugExtOptionsProtoBuf.nameIdInTable); return registry; } }; diff --git a/core/deserialization/src/descriptors.proto b/core/deserialization/src/descriptors.proto index 2dad9a1f08213..1d9a273813ef6 100644 --- a/core/deserialization/src/descriptors.proto +++ b/core/deserialization/src/descriptors.proto @@ -173,6 +173,10 @@ message Class { repeated int32 nested_class_name = 7 [packed = true, (name_id_in_table) = true]; + repeated Constructor constructor = 8; + repeated Function function = 9; + repeated Property property = 10; + repeated Callable member = 11; repeated int32 enum_entry = 12 [packed = true, (name_id_in_table) = true]; @@ -194,6 +198,84 @@ message Class { message Package { repeated Callable member = 1; + repeated Constructor constructor = 2; + repeated Function function = 3; + repeated Property property = 4; + + extensions 100 to 199; +} + +message Constructor { + /* + hasAnnotations + Visibility + isSecondary + */ + optional int32 flags = 1; + + repeated ValueParameter value_parameter = 2; + + extensions 100 to 199; +} + +message Function { + /* + hasAnnotations + Visibility + Modality + MemberKind + isOperator + isInfix + */ + optional int32 flags = 1; + + required int32 name = 2 [(name_id_in_table) = true]; + + required Type return_type = 3; + + repeated TypeParameter type_parameter = 4; + + optional Type receiver_type = 5; + + repeated ValueParameter value_parameter = 6; + + extensions 100 to 199; +} + +message Property { + /* + hasAnnotations + Visibility + Modality + MemberKind + isVar + hasGetter + hasSetter + isConst + lateinit + hasConstant + */ + optional int32 flags = 1; + + required int32 name = 2 [(name_id_in_table) = true]; + + required Type return_type = 3; + + repeated TypeParameter type_parameter = 4; + + optional Type receiver_type = 5; + + optional ValueParameter setter_value_parameter = 6; + + /* + hasAnnotations + Visibility + Modality + isNotDefault + */ + optional int32 getter_flags = 7 /* absent => same as property */; + optional int32 setter_flags = 8 /* absent => same as property */; + extensions 100 to 199; } diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/Flags.java b/core/deserialization/src/org/jetbrains/kotlin/serialization/Flags.java index df1e78dbf7dd2..1e46a8287a97b 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/Flags.java +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/Flags.java @@ -26,34 +26,47 @@ private Flags() {} // Common public static final FlagField<Boolean> HAS_ANNOTATIONS = FlagField.booleanFirst(); - public static final FlagField<ProtoBuf.Visibility> VISIBILITY = FlagField.after(HAS_ANNOTATIONS, ProtoBuf.Visibility.values()); - public static final FlagField<ProtoBuf.Modality> MODALITY = FlagField.after(VISIBILITY, ProtoBuf.Modality.values()); // Class public static final FlagField<ProtoBuf.Class.Kind> CLASS_KIND = FlagField.after(MODALITY, ProtoBuf.Class.Kind.values()); - public static final FlagField<Boolean> INNER = FlagField.booleanAfter(CLASS_KIND); // Callables public static final FlagField<ProtoBuf.CallableKind> CALLABLE_KIND = FlagField.after(MODALITY, ProtoBuf.CallableKind.values()); - public static final FlagField<ProtoBuf.MemberKind> MEMBER_KIND = FlagField.after(CALLABLE_KIND, ProtoBuf.MemberKind.values()); - public static final FlagField<Boolean> HAS_GETTER = FlagField.booleanAfter(MEMBER_KIND); - public static final FlagField<Boolean> HAS_SETTER = FlagField.booleanAfter(HAS_GETTER); - public static final FlagField<Boolean> HAS_CONSTANT = FlagField.booleanAfter(HAS_SETTER); - public static final FlagField<Boolean> IS_CONST = FlagField.booleanAfter(HAS_CONSTANT); + // Constructors - public static final FlagField<Boolean> LATE_INIT = FlagField.booleanAfter(IS_CONST); + public static final FlagField<Boolean> IS_SECONDARY = FlagField.booleanAfter(VISIBILITY); - public static final FlagField<Boolean> IS_OPERATOR = FlagField.booleanAfter(LATE_INIT); + // Functions + public static final FlagField<Boolean> IS_OPERATOR = FlagField.booleanAfter(MEMBER_KIND); public static final FlagField<Boolean> IS_INFIX = FlagField.booleanAfter(IS_OPERATOR); + // Properties + + public static final FlagField<Boolean> IS_VAR = FlagField.booleanAfter(MEMBER_KIND); + public static final FlagField<Boolean> HAS_GETTER = FlagField.booleanAfter(IS_VAR); + public static final FlagField<Boolean> HAS_SETTER = FlagField.booleanAfter(HAS_GETTER); + public static final FlagField<Boolean> IS_CONST = FlagField.booleanAfter(HAS_SETTER); + public static final FlagField<Boolean> LATE_INIT = FlagField.booleanAfter(IS_CONST); + public static final FlagField<Boolean> HAS_CONSTANT = FlagField.booleanAfter(LATE_INIT); + + // Old callables. TODO: delete + + public static final FlagField<Boolean> OLD_HAS_GETTER = FlagField.booleanAfter(MEMBER_KIND); + public static final FlagField<Boolean> OLD_HAS_SETTER = FlagField.booleanAfter(OLD_HAS_GETTER); + public static final FlagField<Boolean> OLD_HAS_CONSTANT = FlagField.booleanAfter(OLD_HAS_SETTER); + public static final FlagField<Boolean> OLD_IS_CONST = FlagField.booleanAfter(OLD_HAS_CONSTANT); + public static final FlagField<Boolean> OLD_LATE_INIT = FlagField.booleanAfter(OLD_IS_CONST); + public static final FlagField<Boolean> OLD_IS_OPERATOR = FlagField.booleanAfter(OLD_LATE_INIT); + public static final FlagField<Boolean> OLD_IS_INFIX = FlagField.booleanAfter(OLD_IS_OPERATOR); + // Parameters public static final FlagField<Boolean> DECLARES_DEFAULT_VALUE = FlagField.booleanAfter(HAS_ANNOTATIONS); @@ -129,14 +142,67 @@ public static int getCallableFlags( | VISIBILITY.toFlags(visibility(visibility)) | MEMBER_KIND.toFlags(memberKind(memberKind)) | CALLABLE_KIND.toFlags(callableKind) + | OLD_HAS_GETTER.toFlags(hasGetter) + | OLD_HAS_SETTER.toFlags(hasSetter) + | OLD_HAS_CONSTANT.toFlags(hasConstant) + | OLD_LATE_INIT.toFlags(lateInit) + | OLD_IS_CONST.toFlags(isConst) + | OLD_IS_OPERATOR.toFlags(isOperator) + | OLD_IS_INFIX.toFlags(isInfix) + ; + } + + public static int getConstructorFlags( + boolean hasAnnotations, + @NotNull Visibility visibility, + boolean isSecondary + ) { + return HAS_ANNOTATIONS.toFlags(hasAnnotations) + | VISIBILITY.toFlags(visibility(visibility)) + | IS_SECONDARY.toFlags(isSecondary) + ; + } + + public static int getFunctionFlags( + boolean hasAnnotations, + @NotNull Visibility visibility, + @NotNull Modality modality, + @NotNull CallableMemberDescriptor.Kind memberKind, + boolean isOperator, + boolean isInfix + ) { + return HAS_ANNOTATIONS.toFlags(hasAnnotations) + | VISIBILITY.toFlags(visibility(visibility)) + | MODALITY.toFlags(modality(modality)) + | MEMBER_KIND.toFlags(memberKind(memberKind)) + | IS_OPERATOR.toFlags(isOperator) + | IS_INFIX.toFlags(isInfix) + ; + } + + public static int getPropertyFlags( + boolean hasAnnotations, + @NotNull Visibility visibility, + @NotNull Modality modality, + @NotNull CallableMemberDescriptor.Kind memberKind, + boolean isVar, + boolean hasGetter, + boolean hasSetter, + boolean hasConstant, + boolean isConst, + boolean lateInit + ) { + return HAS_ANNOTATIONS.toFlags(hasAnnotations) + | VISIBILITY.toFlags(visibility(visibility)) + | MODALITY.toFlags(modality(modality)) + | MEMBER_KIND.toFlags(memberKind(memberKind)) + | IS_VAR.toFlags(isVar) | HAS_GETTER.toFlags(hasGetter) | HAS_SETTER.toFlags(hasSetter) - | HAS_CONSTANT.toFlags(hasConstant) - | LATE_INIT.toFlags(lateInit) | IS_CONST.toFlags(isConst) - | IS_OPERATOR.toFlags(isOperator) - | IS_INFIX.toFlags(isInfix) - ; + | LATE_INIT.toFlags(lateInit) + | HAS_CONSTANT.toFlags(hasConstant) + ; } public static int getAccessorFlags( diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/ProtoBuf.java b/core/deserialization/src/org/jetbrains/kotlin/serialization/ProtoBuf.java index d21257b92cdeb..b79f9a87a2c3b 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/ProtoBuf.java +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/ProtoBuf.java @@ -6903,6 +6903,51 @@ public interface ClassOrBuilder extends */ int getNestedClassName(int index); + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> + getConstructorList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Constructor getConstructor(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + int getConstructorCount(); + + // repeated .org.jetbrains.kotlin.serialization.Function function = 9; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> + getFunctionList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Function getFunction(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + int getFunctionCount(); + + // repeated .org.jetbrains.kotlin.serialization.Property property = 10; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> + getPropertyList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Property getProperty(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + int getPropertyCount(); + // repeated .org.jetbrains.kotlin.serialization.Callable member = 11; /** * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> @@ -7060,18 +7105,42 @@ private Class( input.popLimit(limit); break; } - case 90: { + case 66: { if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) { - member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(); + constructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor>(); mutable_bitField0_ |= 0x00000040; } + constructor_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.PARSER, extensionRegistry)); + break; + } + case 74: { + if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { + function_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Function>(); + mutable_bitField0_ |= 0x00000080; + } + function_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Function.PARSER, extensionRegistry)); + break; + } + case 82: { + if (!((mutable_bitField0_ & 0x00000100) == 0x00000100)) { + property_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Property>(); + mutable_bitField0_ |= 0x00000100; + } + property_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Property.PARSER, extensionRegistry)); + break; + } + case 90: { + if (!((mutable_bitField0_ & 0x00000200) == 0x00000200)) { + member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(); + mutable_bitField0_ |= 0x00000200; + } member_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Callable.PARSER, extensionRegistry)); break; } case 96: { - if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { + if (!((mutable_bitField0_ & 0x00000400) == 0x00000400)) { enumEntry_ = new java.util.ArrayList<java.lang.Integer>(); - mutable_bitField0_ |= 0x00000080; + mutable_bitField0_ |= 0x00000400; } enumEntry_.add(input.readInt32()); break; @@ -7079,9 +7148,9 @@ private Class( case 98: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); - if (!((mutable_bitField0_ & 0x00000080) == 0x00000080) && input.getBytesUntilLimit() > 0) { + if (!((mutable_bitField0_ & 0x00000400) == 0x00000400) && input.getBytesUntilLimit() > 0) { enumEntry_ = new java.util.ArrayList<java.lang.Integer>(); - mutable_bitField0_ |= 0x00000080; + mutable_bitField0_ |= 0x00000400; } while (input.getBytesUntilLimit() > 0) { enumEntry_.add(input.readInt32()); @@ -7103,9 +7172,9 @@ private Class( break; } case 114: { - if (!((mutable_bitField0_ & 0x00000200) == 0x00000200)) { + if (!((mutable_bitField0_ & 0x00001000) == 0x00001000)) { secondaryConstructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(); - mutable_bitField0_ |= 0x00000200; + mutable_bitField0_ |= 0x00001000; } secondaryConstructor_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Callable.PARSER, extensionRegistry)); break; @@ -7128,12 +7197,21 @@ private Class( nestedClassName_ = java.util.Collections.unmodifiableList(nestedClassName_); } if (((mutable_bitField0_ & 0x00000040) == 0x00000040)) { - member_ = java.util.Collections.unmodifiableList(member_); + constructor_ = java.util.Collections.unmodifiableList(constructor_); } if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) { - enumEntry_ = java.util.Collections.unmodifiableList(enumEntry_); + function_ = java.util.Collections.unmodifiableList(function_); + } + if (((mutable_bitField0_ & 0x00000100) == 0x00000100)) { + property_ = java.util.Collections.unmodifiableList(property_); } if (((mutable_bitField0_ & 0x00000200) == 0x00000200)) { + member_ = java.util.Collections.unmodifiableList(member_); + } + if (((mutable_bitField0_ & 0x00000400) == 0x00000400)) { + enumEntry_ = java.util.Collections.unmodifiableList(enumEntry_); + } + if (((mutable_bitField0_ & 0x00001000) == 0x00001000)) { secondaryConstructor_ = java.util.Collections.unmodifiableList(secondaryConstructor_); } makeExtensionsImmutable(); @@ -7867,6 +7945,114 @@ public int getNestedClassName(int index) { } private int nestedClassNameMemoizedSerializedSize = -1; + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8; + public static final int CONSTRUCTOR_FIELD_NUMBER = 8; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> constructor_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> getConstructorList() { + return constructor_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.ConstructorOrBuilder> + getConstructorOrBuilderList() { + return constructor_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public int getConstructorCount() { + return constructor_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Constructor getConstructor(int index) { + return constructor_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ConstructorOrBuilder getConstructorOrBuilder( + int index) { + return constructor_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Function function = 9; + public static final int FUNCTION_FIELD_NUMBER = 9; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> function_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> getFunctionList() { + return function_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.FunctionOrBuilder> + getFunctionOrBuilderList() { + return function_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public int getFunctionCount() { + return function_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Function getFunction(int index) { + return function_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.FunctionOrBuilder getFunctionOrBuilder( + int index) { + return function_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Property property = 10; + public static final int PROPERTY_FIELD_NUMBER = 10; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> property_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> getPropertyList() { + return property_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.PropertyOrBuilder> + getPropertyOrBuilderList() { + return property_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public int getPropertyCount() { + return property_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Property getProperty(int index) { + return property_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.PropertyOrBuilder getPropertyOrBuilder( + int index) { + return property_.get(index); + } + // repeated .org.jetbrains.kotlin.serialization.Callable member = 11; public static final int MEMBER_FIELD_NUMBER = 11; private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> member_; @@ -7994,6 +8180,9 @@ private void initFields() { typeParameter_ = java.util.Collections.emptyList(); supertype_ = java.util.Collections.emptyList(); nestedClassName_ = java.util.Collections.emptyList(); + constructor_ = java.util.Collections.emptyList(); + function_ = java.util.Collections.emptyList(); + property_ = java.util.Collections.emptyList(); member_ = java.util.Collections.emptyList(); enumEntry_ = java.util.Collections.emptyList(); primaryConstructor_ = org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); @@ -8020,6 +8209,24 @@ public final boolean isInitialized() { return false; } } + for (int i = 0; i < getConstructorCount(); i++) { + if (!getConstructor(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getFunctionCount(); i++) { + if (!getFunction(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getPropertyCount(); i++) { + if (!getProperty(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } for (int i = 0; i < getMemberCount(); i++) { if (!getMember(i).isInitialized()) { memoizedIsInitialized = 0; @@ -8074,6 +8281,15 @@ public void writeTo(com.google.protobuf.CodedOutputStream output) for (int i = 0; i < nestedClassName_.size(); i++) { output.writeInt32NoTag(nestedClassName_.get(i)); } + for (int i = 0; i < constructor_.size(); i++) { + output.writeMessage(8, constructor_.get(i)); + } + for (int i = 0; i < function_.size(); i++) { + output.writeMessage(9, function_.get(i)); + } + for (int i = 0; i < property_.size(); i++) { + output.writeMessage(10, property_.get(i)); + } for (int i = 0; i < member_.size(); i++) { output.writeMessage(11, member_.get(i)); } @@ -8133,6 +8349,18 @@ public int getSerializedSize() { } nestedClassNameMemoizedSerializedSize = dataSize; } + for (int i = 0; i < constructor_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(8, constructor_.get(i)); + } + for (int i = 0; i < function_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(9, function_.get(i)); + } + for (int i = 0; i < property_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(10, property_.get(i)); + } for (int i = 0; i < member_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(11, member_.get(i)); @@ -8262,14 +8490,20 @@ public Builder clear() { bitField0_ = (bitField0_ & ~0x00000010); nestedClassName_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000020); - member_ = java.util.Collections.emptyList(); + constructor_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); - enumEntry_ = java.util.Collections.emptyList(); + function_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000080); - primaryConstructor_ = org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); + property_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000100); - secondaryConstructor_ = java.util.Collections.emptyList(); + member_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000200); + enumEntry_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000400); + primaryConstructor_ = org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); + bitField0_ = (bitField0_ & ~0x00000800); + secondaryConstructor_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00001000); return this; } @@ -8321,22 +8555,37 @@ public org.jetbrains.kotlin.serialization.ProtoBuf.Class buildPartial() { } result.nestedClassName_ = nestedClassName_; if (((bitField0_ & 0x00000040) == 0x00000040)) { - member_ = java.util.Collections.unmodifiableList(member_); + constructor_ = java.util.Collections.unmodifiableList(constructor_); bitField0_ = (bitField0_ & ~0x00000040); } - result.member_ = member_; + result.constructor_ = constructor_; if (((bitField0_ & 0x00000080) == 0x00000080)) { - enumEntry_ = java.util.Collections.unmodifiableList(enumEntry_); + function_ = java.util.Collections.unmodifiableList(function_); bitField0_ = (bitField0_ & ~0x00000080); } + result.function_ = function_; + if (((bitField0_ & 0x00000100) == 0x00000100)) { + property_ = java.util.Collections.unmodifiableList(property_); + bitField0_ = (bitField0_ & ~0x00000100); + } + result.property_ = property_; + if (((bitField0_ & 0x00000200) == 0x00000200)) { + member_ = java.util.Collections.unmodifiableList(member_); + bitField0_ = (bitField0_ & ~0x00000200); + } + result.member_ = member_; + if (((bitField0_ & 0x00000400) == 0x00000400)) { + enumEntry_ = java.util.Collections.unmodifiableList(enumEntry_); + bitField0_ = (bitField0_ & ~0x00000400); + } result.enumEntry_ = enumEntry_; - if (((from_bitField0_ & 0x00000100) == 0x00000100)) { + if (((from_bitField0_ & 0x00000800) == 0x00000800)) { to_bitField0_ |= 0x00000008; } result.primaryConstructor_ = primaryConstructor_; - if (((bitField0_ & 0x00000200) == 0x00000200)) { + if (((bitField0_ & 0x00001000) == 0x00001000)) { secondaryConstructor_ = java.util.Collections.unmodifiableList(secondaryConstructor_); - bitField0_ = (bitField0_ & ~0x00000200); + bitField0_ = (bitField0_ & ~0x00001000); } result.secondaryConstructor_ = secondaryConstructor_; result.bitField0_ = to_bitField0_; @@ -8383,11 +8632,41 @@ public Builder mergeFrom(org.jetbrains.kotlin.serialization.ProtoBuf.Class other nestedClassName_.addAll(other.nestedClassName_); } + } + if (!other.constructor_.isEmpty()) { + if (constructor_.isEmpty()) { + constructor_ = other.constructor_; + bitField0_ = (bitField0_ & ~0x00000040); + } else { + ensureConstructorIsMutable(); + constructor_.addAll(other.constructor_); + } + + } + if (!other.function_.isEmpty()) { + if (function_.isEmpty()) { + function_ = other.function_; + bitField0_ = (bitField0_ & ~0x00000080); + } else { + ensureFunctionIsMutable(); + function_.addAll(other.function_); + } + + } + if (!other.property_.isEmpty()) { + if (property_.isEmpty()) { + property_ = other.property_; + bitField0_ = (bitField0_ & ~0x00000100); + } else { + ensurePropertyIsMutable(); + property_.addAll(other.property_); + } + } if (!other.member_.isEmpty()) { if (member_.isEmpty()) { member_ = other.member_; - bitField0_ = (bitField0_ & ~0x00000040); + bitField0_ = (bitField0_ & ~0x00000200); } else { ensureMemberIsMutable(); member_.addAll(other.member_); @@ -8397,7 +8676,7 @@ public Builder mergeFrom(org.jetbrains.kotlin.serialization.ProtoBuf.Class other if (!other.enumEntry_.isEmpty()) { if (enumEntry_.isEmpty()) { enumEntry_ = other.enumEntry_; - bitField0_ = (bitField0_ & ~0x00000080); + bitField0_ = (bitField0_ & ~0x00000400); } else { ensureEnumEntryIsMutable(); enumEntry_.addAll(other.enumEntry_); @@ -8410,7 +8689,7 @@ public Builder mergeFrom(org.jetbrains.kotlin.serialization.ProtoBuf.Class other if (!other.secondaryConstructor_.isEmpty()) { if (secondaryConstructor_.isEmpty()) { secondaryConstructor_ = other.secondaryConstructor_; - bitField0_ = (bitField0_ & ~0x00000200); + bitField0_ = (bitField0_ & ~0x00001000); } else { ensureSecondaryConstructorIsMutable(); secondaryConstructor_.addAll(other.secondaryConstructor_); @@ -8438,6 +8717,24 @@ public final boolean isInitialized() { return false; } } + for (int i = 0; i < getConstructorCount(); i++) { + if (!getConstructor(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getFunctionCount(); i++) { + if (!getFunction(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getPropertyCount(); i++) { + if (!getProperty(i).isInitialized()) { + + return false; + } + } for (int i = 0; i < getMemberCount(); i++) { if (!getMember(i).isInitialized()) { @@ -8933,903 +9230,5192 @@ public Builder clearNestedClassName() { return this; } - // repeated .org.jetbrains.kotlin.serialization.Callable member = 11; - private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> member_ = + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> constructor_ = java.util.Collections.emptyList(); - private void ensureMemberIsMutable() { + private void ensureConstructorIsMutable() { if (!((bitField0_ & 0x00000040) == 0x00000040)) { - member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(member_); + constructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor>(constructor_); bitField0_ |= 0x00000040; } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> getMemberList() { - return java.util.Collections.unmodifiableList(member_); + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> getConstructorList() { + return java.util.Collections.unmodifiableList(constructor_); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public int getMemberCount() { - return member_.size(); + public int getConstructorCount() { + return constructor_.size(); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public org.jetbrains.kotlin.serialization.ProtoBuf.Callable getMember(int index) { - return member_.get(index); + public org.jetbrains.kotlin.serialization.ProtoBuf.Constructor getConstructor(int index) { + return constructor_.get(index); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder setMember( - int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + public Builder setConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Constructor value) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.set(index, value); + ensureConstructorIsMutable(); + constructor_.set(index, value); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder setMember( - int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureMemberIsMutable(); - member_.set(index, builderForValue.build()); + public Builder setConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.Builder builderForValue) { + ensureConstructorIsMutable(); + constructor_.set(index, builderForValue.build()); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addMember(org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + public Builder addConstructor(org.jetbrains.kotlin.serialization.ProtoBuf.Constructor value) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.add(value); + ensureConstructorIsMutable(); + constructor_.add(value); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addMember( - int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + public Builder addConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Constructor value) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.add(index, value); + ensureConstructorIsMutable(); + constructor_.add(index, value); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addMember( - org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureMemberIsMutable(); - member_.add(builderForValue.build()); + public Builder addConstructor( + org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.Builder builderForValue) { + ensureConstructorIsMutable(); + constructor_.add(builderForValue.build()); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addMember( - int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureMemberIsMutable(); - member_.add(index, builderForValue.build()); + public Builder addConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.Builder builderForValue) { + ensureConstructorIsMutable(); + constructor_.add(index, builderForValue.build()); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder addAllMember( - java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Callable> values) { - ensureMemberIsMutable(); - super.addAll(values, member_); + public Builder addAllConstructor( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> values) { + ensureConstructorIsMutable(); + super.addAll(values, constructor_); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder clearMember() { - member_ = java.util.Collections.emptyList(); + public Builder clearConstructor() { + constructor_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 8;</code> */ - public Builder removeMember(int index) { - ensureMemberIsMutable(); - member_.remove(index); + public Builder removeConstructor(int index) { + ensureConstructorIsMutable(); + constructor_.remove(index); return this; } - // repeated int32 enum_entry = 12 [packed = true]; - private java.util.List<java.lang.Integer> enumEntry_ = java.util.Collections.emptyList(); - private void ensureEnumEntryIsMutable() { + // repeated .org.jetbrains.kotlin.serialization.Function function = 9; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> function_ = + java.util.Collections.emptyList(); + private void ensureFunctionIsMutable() { if (!((bitField0_ & 0x00000080) == 0x00000080)) { - enumEntry_ = new java.util.ArrayList<java.lang.Integer>(enumEntry_); + function_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Function>(function_); bitField0_ |= 0x00000080; } } + /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public java.util.List<java.lang.Integer> - getEnumEntryList() { - return java.util.Collections.unmodifiableList(enumEntry_); + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> getFunctionList() { + return java.util.Collections.unmodifiableList(function_); } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public int getEnumEntryCount() { - return enumEntry_.size(); + public int getFunctionCount() { + return function_.size(); } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public int getEnumEntry(int index) { - return enumEntry_.get(index); + public org.jetbrains.kotlin.serialization.ProtoBuf.Function getFunction(int index) { + return function_.get(index); } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder setEnumEntry( - int index, int value) { - ensureEnumEntryIsMutable(); - enumEntry_.set(index, value); - + public Builder setFunction( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Function value) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.set(index, value); + return this; } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder addEnumEntry(int value) { - ensureEnumEntryIsMutable(); - enumEntry_.add(value); - + public Builder setFunction( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Function.Builder builderForValue) { + ensureFunctionIsMutable(); + function_.set(index, builderForValue.build()); + return this; } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder addAllEnumEntry( - java.lang.Iterable<? extends java.lang.Integer> values) { - ensureEnumEntryIsMutable(); - super.addAll(values, enumEntry_); - + public Builder addFunction(org.jetbrains.kotlin.serialization.ProtoBuf.Function value) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.add(value); + return this; } /** - * <code>repeated int32 enum_entry = 12 [packed = true];</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> */ - public Builder clearEnumEntry() { - enumEntry_ = java.util.Collections.emptyList(); + public Builder addFunction( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Function value) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public Builder addFunction( + org.jetbrains.kotlin.serialization.ProtoBuf.Function.Builder builderForValue) { + ensureFunctionIsMutable(); + function_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public Builder addFunction( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Function.Builder builderForValue) { + ensureFunctionIsMutable(); + function_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public Builder addAllFunction( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Function> values) { + ensureFunctionIsMutable(); + super.addAll(values, function_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public Builder clearFunction() { + function_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000080); - + return this; } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 9;</code> + */ + public Builder removeFunction(int index) { + ensureFunctionIsMutable(); + function_.remove(index); + + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.Property property = 10; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> property_ = + java.util.Collections.emptyList(); + private void ensurePropertyIsMutable() { + if (!((bitField0_ & 0x00000100) == 0x00000100)) { + property_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Property>(property_); + bitField0_ |= 0x00000100; + } + } - // optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13; - private org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor primaryConstructor_ = org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public boolean hasPrimaryConstructor() { - return ((bitField0_ & 0x00000100) == 0x00000100); + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> getPropertyList() { + return java.util.Collections.unmodifiableList(property_); } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor getPrimaryConstructor() { - return primaryConstructor_; + public int getPropertyCount() { + return property_.size(); } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder setPrimaryConstructor(org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor value) { + public org.jetbrains.kotlin.serialization.ProtoBuf.Property getProperty(int index) { + return property_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public Builder setProperty( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Property value) { if (value == null) { throw new NullPointerException(); } - primaryConstructor_ = value; + ensurePropertyIsMutable(); + property_.set(index, value); - bitField0_ |= 0x00000100; return this; } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder setPrimaryConstructor( - org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.Builder builderForValue) { - primaryConstructor_ = builderForValue.build(); + public Builder setProperty( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Property.Builder builderForValue) { + ensurePropertyIsMutable(); + property_.set(index, builderForValue.build()); - bitField0_ |= 0x00000100; return this; } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder mergePrimaryConstructor(org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor value) { - if (((bitField0_ & 0x00000100) == 0x00000100) && - primaryConstructor_ != org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance()) { - primaryConstructor_ = - org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.newBuilder(primaryConstructor_).mergeFrom(value).buildPartial(); - } else { - primaryConstructor_ = value; + public Builder addProperty(org.jetbrains.kotlin.serialization.ProtoBuf.Property value) { + if (value == null) { + throw new NullPointerException(); } + ensurePropertyIsMutable(); + property_.add(value); - bitField0_ |= 0x00000100; return this; } /** - * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> - * - * <pre> - * This field is present if and only if the class has a primary constructor - * </pre> + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> */ - public Builder clearPrimaryConstructor() { - primaryConstructor_ = org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); + public Builder addProperty( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Property value) { + if (value == null) { + throw new NullPointerException(); + } + ensurePropertyIsMutable(); + property_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public Builder addProperty( + org.jetbrains.kotlin.serialization.ProtoBuf.Property.Builder builderForValue) { + ensurePropertyIsMutable(); + property_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public Builder addProperty( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Property.Builder builderForValue) { + ensurePropertyIsMutable(); + property_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public Builder addAllProperty( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Property> values) { + ensurePropertyIsMutable(); + super.addAll(values, property_); + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public Builder clearProperty() { + property_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000100); + return this; } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 10;</code> + */ + public Builder removeProperty(int index) { + ensurePropertyIsMutable(); + property_.remove(index); - // repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14; - private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> secondaryConstructor_ = + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.Callable member = 11; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> member_ = java.util.Collections.emptyList(); - private void ensureSecondaryConstructorIsMutable() { + private void ensureMemberIsMutable() { if (!((bitField0_ & 0x00000200) == 0x00000200)) { - secondaryConstructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(secondaryConstructor_); + member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(member_); bitField0_ |= 0x00000200; } } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> getSecondaryConstructorList() { - return java.util.Collections.unmodifiableList(secondaryConstructor_); + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> getMemberList() { + return java.util.Collections.unmodifiableList(member_); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public int getSecondaryConstructorCount() { - return secondaryConstructor_.size(); + public int getMemberCount() { + return member_.size(); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public org.jetbrains.kotlin.serialization.ProtoBuf.Callable getSecondaryConstructor(int index) { - return secondaryConstructor_.get(index); + public org.jetbrains.kotlin.serialization.ProtoBuf.Callable getMember(int index) { + return member_.get(index); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder setSecondaryConstructor( + public Builder setMember( int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { if (value == null) { throw new NullPointerException(); } - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.set(index, value); + ensureMemberIsMutable(); + member_.set(index, value); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder setSecondaryConstructor( + public Builder setMember( int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.set(index, builderForValue.build()); + ensureMemberIsMutable(); + member_.set(index, builderForValue.build()); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder addSecondaryConstructor(org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + public Builder addMember(org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { if (value == null) { throw new NullPointerException(); } - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.add(value); + ensureMemberIsMutable(); + member_.add(value); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder addSecondaryConstructor( + public Builder addMember( int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { if (value == null) { throw new NullPointerException(); } - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.add(index, value); + ensureMemberIsMutable(); + member_.add(index, value); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder addSecondaryConstructor( + public Builder addMember( org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.add(builderForValue.build()); + ensureMemberIsMutable(); + member_.add(builderForValue.build()); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder addSecondaryConstructor( + public Builder addMember( int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.add(index, builderForValue.build()); + ensureMemberIsMutable(); + member_.add(index, builderForValue.build()); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder addAllSecondaryConstructor( + public Builder addAllMember( java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Callable> values) { - ensureSecondaryConstructorIsMutable(); - super.addAll(values, secondaryConstructor_); + ensureMemberIsMutable(); + super.addAll(values, member_); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder clearSecondaryConstructor() { - secondaryConstructor_ = java.util.Collections.emptyList(); + public Builder clearMember() { + member_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000200); return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 11;</code> */ - public Builder removeSecondaryConstructor(int index) { - ensureSecondaryConstructorIsMutable(); - secondaryConstructor_.remove(index); + public Builder removeMember(int index) { + ensureMemberIsMutable(); + member_.remove(index); return this; } - // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Class) - } - - static { - defaultInstance = new Class(true); - defaultInstance.initFields(); - } - - // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Class) - } - - public interface PackageOrBuilder extends - com.google.protobuf.GeneratedMessageLite. - ExtendableMessageOrBuilder<Package> { - - // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> - getMemberList(); - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - org.jetbrains.kotlin.serialization.ProtoBuf.Callable getMember(int index); - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + // repeated int32 enum_entry = 12 [packed = true]; + private java.util.List<java.lang.Integer> enumEntry_ = java.util.Collections.emptyList(); + private void ensureEnumEntryIsMutable() { + if (!((bitField0_ & 0x00000400) == 0x00000400)) { + enumEntry_ = new java.util.ArrayList<java.lang.Integer>(enumEntry_); + bitField0_ |= 0x00000400; + } + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public java.util.List<java.lang.Integer> + getEnumEntryList() { + return java.util.Collections.unmodifiableList(enumEntry_); + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public int getEnumEntryCount() { + return enumEntry_.size(); + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public int getEnumEntry(int index) { + return enumEntry_.get(index); + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public Builder setEnumEntry( + int index, int value) { + ensureEnumEntryIsMutable(); + enumEntry_.set(index, value); + + return this; + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public Builder addEnumEntry(int value) { + ensureEnumEntryIsMutable(); + enumEntry_.add(value); + + return this; + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public Builder addAllEnumEntry( + java.lang.Iterable<? extends java.lang.Integer> values) { + ensureEnumEntryIsMutable(); + super.addAll(values, enumEntry_); + + return this; + } + /** + * <code>repeated int32 enum_entry = 12 [packed = true];</code> + */ + public Builder clearEnumEntry() { + enumEntry_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000400); + + return this; + } + + // optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13; + private org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor primaryConstructor_ = org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public boolean hasPrimaryConstructor() { + return ((bitField0_ & 0x00000800) == 0x00000800); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor getPrimaryConstructor() { + return primaryConstructor_; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public Builder setPrimaryConstructor(org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor value) { + if (value == null) { + throw new NullPointerException(); + } + primaryConstructor_ = value; + + bitField0_ |= 0x00000800; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public Builder setPrimaryConstructor( + org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.Builder builderForValue) { + primaryConstructor_ = builderForValue.build(); + + bitField0_ |= 0x00000800; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public Builder mergePrimaryConstructor(org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor value) { + if (((bitField0_ & 0x00000800) == 0x00000800) && + primaryConstructor_ != org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance()) { + primaryConstructor_ = + org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.newBuilder(primaryConstructor_).mergeFrom(value).buildPartial(); + } else { + primaryConstructor_ = value; + } + + bitField0_ |= 0x00000800; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Class.PrimaryConstructor primary_constructor = 13;</code> + * + * <pre> + * This field is present if and only if the class has a primary constructor + * </pre> + */ + public Builder clearPrimaryConstructor() { + primaryConstructor_ = org.jetbrains.kotlin.serialization.ProtoBuf.Class.PrimaryConstructor.getDefaultInstance(); + + bitField0_ = (bitField0_ & ~0x00000800); + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> secondaryConstructor_ = + java.util.Collections.emptyList(); + private void ensureSecondaryConstructorIsMutable() { + if (!((bitField0_ & 0x00001000) == 0x00001000)) { + secondaryConstructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(secondaryConstructor_); + bitField0_ |= 0x00001000; + } + } + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> getSecondaryConstructorList() { + return java.util.Collections.unmodifiableList(secondaryConstructor_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public int getSecondaryConstructorCount() { + return secondaryConstructor_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Callable getSecondaryConstructor(int index) { + return secondaryConstructor_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder setSecondaryConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + if (value == null) { + throw new NullPointerException(); + } + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.set(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder setSecondaryConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.set(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addSecondaryConstructor(org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + if (value == null) { + throw new NullPointerException(); + } + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.add(value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addSecondaryConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + if (value == null) { + throw new NullPointerException(); + } + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addSecondaryConstructor( + org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addSecondaryConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder addAllSecondaryConstructor( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Callable> values) { + ensureSecondaryConstructorIsMutable(); + super.addAll(values, secondaryConstructor_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder clearSecondaryConstructor() { + secondaryConstructor_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00001000); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable secondary_constructor = 14;</code> + */ + public Builder removeSecondaryConstructor(int index) { + ensureSecondaryConstructorIsMutable(); + secondaryConstructor_.remove(index); + + return this; + } + + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Class) + } + + static { + defaultInstance = new Class(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Class) + } + + public interface PackageOrBuilder extends + com.google.protobuf.GeneratedMessageLite. + ExtendableMessageOrBuilder<Package> { + + // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> + getMemberList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Callable getMember(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + int getMemberCount(); + + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> + getConstructorList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Constructor getConstructor(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + int getConstructorCount(); + + // repeated .org.jetbrains.kotlin.serialization.Function function = 3; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> + getFunctionList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Function getFunction(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + int getFunctionCount(); + + // repeated .org.jetbrains.kotlin.serialization.Property property = 4; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> + getPropertyList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Property getProperty(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + int getPropertyCount(); + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Package} + */ + public static final class Package extends + com.google.protobuf.GeneratedMessageLite.ExtendableMessage< + Package> implements PackageOrBuilder { + // Use Package.newBuilder() to construct. + private Package(com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<org.jetbrains.kotlin.serialization.ProtoBuf.Package, ?> builder) { + super(builder); + + } + private Package(boolean noInit) {} + + private static final Package defaultInstance; + public static Package getDefaultInstance() { + return defaultInstance; + } + + public Package getDefaultInstanceForType() { + return defaultInstance; + } + + private Package( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(); + mutable_bitField0_ |= 0x00000001; + } + member_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Callable.PARSER, extensionRegistry)); + break; + } + case 18: { + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + constructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor>(); + mutable_bitField0_ |= 0x00000002; + } + constructor_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.PARSER, extensionRegistry)); + break; + } + case 26: { + if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { + function_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Function>(); + mutable_bitField0_ |= 0x00000004; + } + function_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Function.PARSER, extensionRegistry)); + break; + } + case 34: { + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + property_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Property>(); + mutable_bitField0_ |= 0x00000008; + } + property_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Property.PARSER, extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + member_ = java.util.Collections.unmodifiableList(member_); + } + if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + constructor_ = java.util.Collections.unmodifiableList(constructor_); + } + if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { + function_ = java.util.Collections.unmodifiableList(function_); + } + if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + property_ = java.util.Collections.unmodifiableList(property_); + } + makeExtensionsImmutable(); + } + } + public static com.google.protobuf.Parser<Package> PARSER = + new com.google.protobuf.AbstractParser<Package>() { + public Package parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Package(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser<Package> getParserForType() { + return PARSER; + } + + // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; + public static final int MEMBER_FIELD_NUMBER = 1; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> member_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> getMemberList() { + return member_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.CallableOrBuilder> + getMemberOrBuilderList() { + return member_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public int getMemberCount() { + return member_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Callable getMember(int index) { + return member_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.CallableOrBuilder getMemberOrBuilder( + int index) { + return member_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2; + public static final int CONSTRUCTOR_FIELD_NUMBER = 2; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> constructor_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> getConstructorList() { + return constructor_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.ConstructorOrBuilder> + getConstructorOrBuilderList() { + return constructor_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public int getConstructorCount() { + return constructor_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Constructor getConstructor(int index) { + return constructor_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ConstructorOrBuilder getConstructorOrBuilder( + int index) { + return constructor_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Function function = 3; + public static final int FUNCTION_FIELD_NUMBER = 3; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> function_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> getFunctionList() { + return function_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.FunctionOrBuilder> + getFunctionOrBuilderList() { + return function_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public int getFunctionCount() { + return function_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Function getFunction(int index) { + return function_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.FunctionOrBuilder getFunctionOrBuilder( + int index) { + return function_.get(index); + } + + // repeated .org.jetbrains.kotlin.serialization.Property property = 4; + public static final int PROPERTY_FIELD_NUMBER = 4; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> property_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> getPropertyList() { + return property_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.PropertyOrBuilder> + getPropertyOrBuilderList() { + return property_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public int getPropertyCount() { + return property_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Property getProperty(int index) { + return property_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.PropertyOrBuilder getPropertyOrBuilder( + int index) { + return property_.get(index); + } + + private void initFields() { + member_ = java.util.Collections.emptyList(); + constructor_ = java.util.Collections.emptyList(); + function_ = java.util.Collections.emptyList(); + property_ = java.util.Collections.emptyList(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + for (int i = 0; i < getMemberCount(); i++) { + if (!getMember(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getConstructorCount(); i++) { + if (!getConstructor(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getFunctionCount(); i++) { + if (!getFunction(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getPropertyCount(); i++) { + if (!getProperty(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (!extensionsAreInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + com.google.protobuf.GeneratedMessageLite + .ExtendableMessage<org.jetbrains.kotlin.serialization.ProtoBuf.Package>.ExtensionWriter extensionWriter = + newExtensionWriter(); + for (int i = 0; i < member_.size(); i++) { + output.writeMessage(1, member_.get(i)); + } + for (int i = 0; i < constructor_.size(); i++) { + output.writeMessage(2, constructor_.get(i)); + } + for (int i = 0; i < function_.size(); i++) { + output.writeMessage(3, function_.get(i)); + } + for (int i = 0; i < property_.size(); i++) { + output.writeMessage(4, property_.get(i)); + } + extensionWriter.writeUntil(200, output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + for (int i = 0; i < member_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, member_.get(i)); + } + for (int i = 0; i < constructor_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, constructor_.get(i)); + } + for (int i = 0; i < function_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, function_.get(i)); + } + for (int i = 0; i < property_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, property_.get(i)); + } + size += extensionsSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jetbrains.kotlin.serialization.ProtoBuf.Package prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Package} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageLite.ExtendableBuilder< + org.jetbrains.kotlin.serialization.ProtoBuf.Package, Builder> implements org.jetbrains.kotlin.serialization.ProtoBuf.PackageOrBuilder { + // Construct using org.jetbrains.kotlin.serialization.ProtoBuf.Package.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + member_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + constructor_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + function_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000004); + property_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Package getDefaultInstanceForType() { + return org.jetbrains.kotlin.serialization.ProtoBuf.Package.getDefaultInstance(); + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Package build() { + org.jetbrains.kotlin.serialization.ProtoBuf.Package result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Package buildPartial() { + org.jetbrains.kotlin.serialization.ProtoBuf.Package result = new org.jetbrains.kotlin.serialization.ProtoBuf.Package(this); + int from_bitField0_ = bitField0_; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + member_ = java.util.Collections.unmodifiableList(member_); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.member_ = member_; + if (((bitField0_ & 0x00000002) == 0x00000002)) { + constructor_ = java.util.Collections.unmodifiableList(constructor_); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.constructor_ = constructor_; + if (((bitField0_ & 0x00000004) == 0x00000004)) { + function_ = java.util.Collections.unmodifiableList(function_); + bitField0_ = (bitField0_ & ~0x00000004); + } + result.function_ = function_; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + property_ = java.util.Collections.unmodifiableList(property_); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.property_ = property_; + return result; + } + + public Builder mergeFrom(org.jetbrains.kotlin.serialization.ProtoBuf.Package other) { + if (other == org.jetbrains.kotlin.serialization.ProtoBuf.Package.getDefaultInstance()) return this; + if (!other.member_.isEmpty()) { + if (member_.isEmpty()) { + member_ = other.member_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureMemberIsMutable(); + member_.addAll(other.member_); + } + + } + if (!other.constructor_.isEmpty()) { + if (constructor_.isEmpty()) { + constructor_ = other.constructor_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureConstructorIsMutable(); + constructor_.addAll(other.constructor_); + } + + } + if (!other.function_.isEmpty()) { + if (function_.isEmpty()) { + function_ = other.function_; + bitField0_ = (bitField0_ & ~0x00000004); + } else { + ensureFunctionIsMutable(); + function_.addAll(other.function_); + } + + } + if (!other.property_.isEmpty()) { + if (property_.isEmpty()) { + property_ = other.property_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensurePropertyIsMutable(); + property_.addAll(other.property_); + } + + } + this.mergeExtensionFields(other); + return this; + } + + public final boolean isInitialized() { + for (int i = 0; i < getMemberCount(); i++) { + if (!getMember(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getConstructorCount(); i++) { + if (!getConstructor(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getFunctionCount(); i++) { + if (!getFunction(i).isInitialized()) { + + return false; + } + } + for (int i = 0; i < getPropertyCount(); i++) { + if (!getProperty(i).isInitialized()) { + + return false; + } + } + if (!extensionsAreInitialized()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jetbrains.kotlin.serialization.ProtoBuf.Package parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jetbrains.kotlin.serialization.ProtoBuf.Package) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> member_ = + java.util.Collections.emptyList(); + private void ensureMemberIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(member_); + bitField0_ |= 0x00000001; + } + } + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> getMemberList() { + return java.util.Collections.unmodifiableList(member_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public int getMemberCount() { + return member_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Callable getMember(int index) { + return member_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder setMember( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.set(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder setMember( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { + ensureMemberIsMutable(); + member_.set(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addMember(org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.add(value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addMember( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + if (value == null) { + throw new NullPointerException(); + } + ensureMemberIsMutable(); + member_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addMember( + org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { + ensureMemberIsMutable(); + member_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addMember( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { + ensureMemberIsMutable(); + member_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder addAllMember( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Callable> values) { + ensureMemberIsMutable(); + super.addAll(values, member_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder clearMember() { + member_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + */ + public Builder removeMember(int index) { + ensureMemberIsMutable(); + member_.remove(index); + + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> constructor_ = + java.util.Collections.emptyList(); + private void ensureConstructorIsMutable() { + if (!((bitField0_ & 0x00000002) == 0x00000002)) { + constructor_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor>(constructor_); + bitField0_ |= 0x00000002; + } + } + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> getConstructorList() { + return java.util.Collections.unmodifiableList(constructor_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public int getConstructorCount() { + return constructor_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Constructor getConstructor(int index) { + return constructor_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder setConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Constructor value) { + if (value == null) { + throw new NullPointerException(); + } + ensureConstructorIsMutable(); + constructor_.set(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder setConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.Builder builderForValue) { + ensureConstructorIsMutable(); + constructor_.set(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addConstructor(org.jetbrains.kotlin.serialization.ProtoBuf.Constructor value) { + if (value == null) { + throw new NullPointerException(); + } + ensureConstructorIsMutable(); + constructor_.add(value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Constructor value) { + if (value == null) { + throw new NullPointerException(); + } + ensureConstructorIsMutable(); + constructor_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addConstructor( + org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.Builder builderForValue) { + ensureConstructorIsMutable(); + constructor_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addConstructor( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.Builder builderForValue) { + ensureConstructorIsMutable(); + constructor_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder addAllConstructor( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Constructor> values) { + ensureConstructorIsMutable(); + super.addAll(values, constructor_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder clearConstructor() { + constructor_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Constructor constructor = 2;</code> + */ + public Builder removeConstructor(int index) { + ensureConstructorIsMutable(); + constructor_.remove(index); + + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.Function function = 3; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> function_ = + java.util.Collections.emptyList(); + private void ensureFunctionIsMutable() { + if (!((bitField0_ & 0x00000004) == 0x00000004)) { + function_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Function>(function_); + bitField0_ |= 0x00000004; + } + } + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Function> getFunctionList() { + return java.util.Collections.unmodifiableList(function_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public int getFunctionCount() { + return function_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Function getFunction(int index) { + return function_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder setFunction( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Function value) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.set(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder setFunction( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Function.Builder builderForValue) { + ensureFunctionIsMutable(); + function_.set(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addFunction(org.jetbrains.kotlin.serialization.ProtoBuf.Function value) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.add(value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addFunction( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Function value) { + if (value == null) { + throw new NullPointerException(); + } + ensureFunctionIsMutable(); + function_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addFunction( + org.jetbrains.kotlin.serialization.ProtoBuf.Function.Builder builderForValue) { + ensureFunctionIsMutable(); + function_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addFunction( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Function.Builder builderForValue) { + ensureFunctionIsMutable(); + function_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder addAllFunction( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Function> values) { + ensureFunctionIsMutable(); + super.addAll(values, function_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder clearFunction() { + function_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000004); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Function function = 3;</code> + */ + public Builder removeFunction(int index) { + ensureFunctionIsMutable(); + function_.remove(index); + + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.Property property = 4; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> property_ = + java.util.Collections.emptyList(); + private void ensurePropertyIsMutable() { + if (!((bitField0_ & 0x00000008) == 0x00000008)) { + property_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Property>(property_); + bitField0_ |= 0x00000008; + } + } + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Property> getPropertyList() { + return java.util.Collections.unmodifiableList(property_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public int getPropertyCount() { + return property_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Property getProperty(int index) { + return property_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder setProperty( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Property value) { + if (value == null) { + throw new NullPointerException(); + } + ensurePropertyIsMutable(); + property_.set(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder setProperty( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Property.Builder builderForValue) { + ensurePropertyIsMutable(); + property_.set(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addProperty(org.jetbrains.kotlin.serialization.ProtoBuf.Property value) { + if (value == null) { + throw new NullPointerException(); + } + ensurePropertyIsMutable(); + property_.add(value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addProperty( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Property value) { + if (value == null) { + throw new NullPointerException(); + } + ensurePropertyIsMutable(); + property_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addProperty( + org.jetbrains.kotlin.serialization.ProtoBuf.Property.Builder builderForValue) { + ensurePropertyIsMutable(); + property_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addProperty( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.Property.Builder builderForValue) { + ensurePropertyIsMutable(); + property_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder addAllProperty( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Property> values) { + ensurePropertyIsMutable(); + super.addAll(values, property_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder clearProperty() { + property_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.Property property = 4;</code> + */ + public Builder removeProperty(int index) { + ensurePropertyIsMutable(); + property_.remove(index); + + return this; + } + + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Package) + } + + static { + defaultInstance = new Package(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Package) + } + + public interface ConstructorOrBuilder extends + com.google.protobuf.GeneratedMessageLite. + ExtendableMessageOrBuilder<Constructor> { + + // optional int32 flags = 1; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + boolean hasFlags(); + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + int getFlags(); + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> + getValueParameterList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getValueParameter(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + int getValueParameterCount(); + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Constructor} + */ + public static final class Constructor extends + com.google.protobuf.GeneratedMessageLite.ExtendableMessage< + Constructor> implements ConstructorOrBuilder { + // Use Constructor.newBuilder() to construct. + private Constructor(com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor, ?> builder) { + super(builder); + + } + private Constructor(boolean noInit) {} + + private static final Constructor defaultInstance; + public static Constructor getDefaultInstance() { + return defaultInstance; + } + + public Constructor getDefaultInstanceForType() { + return defaultInstance; + } + + private Constructor( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + flags_ = input.readInt32(); + break; + } + case 18: { + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + valueParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter>(); + mutable_bitField0_ |= 0x00000002; + } + valueParameter_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.PARSER, extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + valueParameter_ = java.util.Collections.unmodifiableList(valueParameter_); + } + makeExtensionsImmutable(); + } + } + public static com.google.protobuf.Parser<Constructor> PARSER = + new com.google.protobuf.AbstractParser<Constructor>() { + public Constructor parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Constructor(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser<Constructor> getParserForType() { + return PARSER; + } + + private int bitField0_; + // optional int32 flags = 1; + public static final int FLAGS_FIELD_NUMBER = 1; + private int flags_; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public int getFlags() { + return flags_; + } + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2; + public static final int VALUE_PARAMETER_FIELD_NUMBER = 2; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> valueParameter_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> getValueParameterList() { + return valueParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameterOrBuilder> + getValueParameterOrBuilderList() { + return valueParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public int getValueParameterCount() { + return valueParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getValueParameter(int index) { + return valueParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameterOrBuilder getValueParameterOrBuilder( + int index) { + return valueParameter_.get(index); + } + + private void initFields() { + flags_ = 0; + valueParameter_ = java.util.Collections.emptyList(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + for (int i = 0; i < getValueParameterCount(); i++) { + if (!getValueParameter(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (!extensionsAreInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + com.google.protobuf.GeneratedMessageLite + .ExtendableMessage<org.jetbrains.kotlin.serialization.ProtoBuf.Constructor>.ExtensionWriter extensionWriter = + newExtensionWriter(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, flags_); + } + for (int i = 0; i < valueParameter_.size(); i++) { + output.writeMessage(2, valueParameter_.get(i)); + } + extensionWriter.writeUntil(200, output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, flags_); + } + for (int i = 0; i < valueParameter_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, valueParameter_.get(i)); + } + size += extensionsSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jetbrains.kotlin.serialization.ProtoBuf.Constructor prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Constructor} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageLite.ExtendableBuilder< + org.jetbrains.kotlin.serialization.ProtoBuf.Constructor, Builder> implements org.jetbrains.kotlin.serialization.ProtoBuf.ConstructorOrBuilder { + // Construct using org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + flags_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + valueParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Constructor getDefaultInstanceForType() { + return org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.getDefaultInstance(); + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Constructor build() { + org.jetbrains.kotlin.serialization.ProtoBuf.Constructor result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Constructor buildPartial() { + org.jetbrains.kotlin.serialization.ProtoBuf.Constructor result = new org.jetbrains.kotlin.serialization.ProtoBuf.Constructor(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.flags_ = flags_; + if (((bitField0_ & 0x00000002) == 0x00000002)) { + valueParameter_ = java.util.Collections.unmodifiableList(valueParameter_); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.valueParameter_ = valueParameter_; + result.bitField0_ = to_bitField0_; + return result; + } + + public Builder mergeFrom(org.jetbrains.kotlin.serialization.ProtoBuf.Constructor other) { + if (other == org.jetbrains.kotlin.serialization.ProtoBuf.Constructor.getDefaultInstance()) return this; + if (other.hasFlags()) { + setFlags(other.getFlags()); + } + if (!other.valueParameter_.isEmpty()) { + if (valueParameter_.isEmpty()) { + valueParameter_ = other.valueParameter_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureValueParameterIsMutable(); + valueParameter_.addAll(other.valueParameter_); + } + + } + this.mergeExtensionFields(other); + return this; + } + + public final boolean isInitialized() { + for (int i = 0; i < getValueParameterCount(); i++) { + if (!getValueParameter(i).isInitialized()) { + + return false; + } + } + if (!extensionsAreInitialized()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jetbrains.kotlin.serialization.ProtoBuf.Constructor parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jetbrains.kotlin.serialization.ProtoBuf.Constructor) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + // optional int32 flags = 1; + private int flags_ ; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public int getFlags() { + return flags_; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public Builder setFlags(int value) { + bitField0_ |= 0x00000001; + flags_ = value; + + return this; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *isSecondary + * </pre> + */ + public Builder clearFlags() { + bitField0_ = (bitField0_ & ~0x00000001); + flags_ = 0; + + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> valueParameter_ = + java.util.Collections.emptyList(); + private void ensureValueParameterIsMutable() { + if (!((bitField0_ & 0x00000002) == 0x00000002)) { + valueParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter>(valueParameter_); + bitField0_ |= 0x00000002; + } + } + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> getValueParameterList() { + return java.util.Collections.unmodifiableList(valueParameter_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public int getValueParameterCount() { + return valueParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getValueParameter(int index) { + return valueParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder setValueParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.set(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder setValueParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.Builder builderForValue) { + ensureValueParameterIsMutable(); + valueParameter_.set(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addValueParameter(org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.add(value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addValueParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addValueParameter( + org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.Builder builderForValue) { + ensureValueParameterIsMutable(); + valueParameter_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addValueParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.Builder builderForValue) { + ensureValueParameterIsMutable(); + valueParameter_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder addAllValueParameter( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> values) { + ensureValueParameterIsMutable(); + super.addAll(values, valueParameter_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder clearValueParameter() { + valueParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 2;</code> + */ + public Builder removeValueParameter(int index) { + ensureValueParameterIsMutable(); + valueParameter_.remove(index); + + return this; + } + + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Constructor) + } + + static { + defaultInstance = new Constructor(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Constructor) + } + + public interface FunctionOrBuilder extends + com.google.protobuf.GeneratedMessageLite. + ExtendableMessageOrBuilder<Function> { + + // optional int32 flags = 1; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + boolean hasFlags(); + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + int getFlags(); + + // required int32 name = 2; + /** + * <code>required int32 name = 2;</code> + */ + boolean hasName(); + /** + * <code>required int32 name = 2;</code> + */ + int getName(); + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + boolean hasReturnType(); + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Type getReturnType(); + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> + getTypeParameterList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter getTypeParameter(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + int getTypeParameterCount(); + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + boolean hasReceiverType(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Type getReceiverType(); + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> + getValueParameterList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getValueParameter(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + int getValueParameterCount(); + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Function} + */ + public static final class Function extends + com.google.protobuf.GeneratedMessageLite.ExtendableMessage< + Function> implements FunctionOrBuilder { + // Use Function.newBuilder() to construct. + private Function(com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<org.jetbrains.kotlin.serialization.ProtoBuf.Function, ?> builder) { + super(builder); + + } + private Function(boolean noInit) {} + + private static final Function defaultInstance; + public static Function getDefaultInstance() { + return defaultInstance; + } + + public Function getDefaultInstanceForType() { + return defaultInstance; + } + + private Function( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + flags_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + name_ = input.readInt32(); + break; + } + case 26: { + org.jetbrains.kotlin.serialization.ProtoBuf.Type.Builder subBuilder = null; + if (((bitField0_ & 0x00000004) == 0x00000004)) { + subBuilder = returnType_.toBuilder(); + } + returnType_ = input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Type.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(returnType_); + returnType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000004; + break; + } + case 34: { + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter>(); + mutable_bitField0_ |= 0x00000008; + } + typeParameter_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter.PARSER, extensionRegistry)); + break; + } + case 42: { + org.jetbrains.kotlin.serialization.ProtoBuf.Type.Builder subBuilder = null; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + subBuilder = receiverType_.toBuilder(); + } + receiverType_ = input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Type.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(receiverType_); + receiverType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000008; + break; + } + case 50: { + if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) { + valueParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter>(); + mutable_bitField0_ |= 0x00000020; + } + valueParameter_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.PARSER, extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = java.util.Collections.unmodifiableList(typeParameter_); + } + if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) { + valueParameter_ = java.util.Collections.unmodifiableList(valueParameter_); + } + makeExtensionsImmutable(); + } + } + public static com.google.protobuf.Parser<Function> PARSER = + new com.google.protobuf.AbstractParser<Function>() { + public Function parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Function(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser<Function> getParserForType() { + return PARSER; + } + + private int bitField0_; + // optional int32 flags = 1; + public static final int FLAGS_FIELD_NUMBER = 1; + private int flags_; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public int getFlags() { + return flags_; + } + + // required int32 name = 2; + public static final int NAME_FIELD_NUMBER = 2; + private int name_; + /** + * <code>required int32 name = 2;</code> + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>required int32 name = 2;</code> + */ + public int getName() { + return name_; + } + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + public static final int RETURN_TYPE_FIELD_NUMBER = 3; + private org.jetbrains.kotlin.serialization.ProtoBuf.Type returnType_; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public boolean hasReturnType() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Type getReturnType() { + return returnType_; + } + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + public static final int TYPE_PARAMETER_FIELD_NUMBER = 4; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> typeParameter_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> getTypeParameterList() { + return typeParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameterOrBuilder> + getTypeParameterOrBuilderList() { + return typeParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public int getTypeParameterCount() { + return typeParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter getTypeParameter(int index) { + return typeParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameterOrBuilder getTypeParameterOrBuilder( + int index) { + return typeParameter_.get(index); + } + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + public static final int RECEIVER_TYPE_FIELD_NUMBER = 5; + private org.jetbrains.kotlin.serialization.ProtoBuf.Type receiverType_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public boolean hasReceiverType() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Type getReceiverType() { + return receiverType_; + } + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6; + public static final int VALUE_PARAMETER_FIELD_NUMBER = 6; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> valueParameter_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> getValueParameterList() { + return valueParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameterOrBuilder> + getValueParameterOrBuilderList() { + return valueParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public int getValueParameterCount() { + return valueParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getValueParameter(int index) { + return valueParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameterOrBuilder getValueParameterOrBuilder( + int index) { + return valueParameter_.get(index); + } + + private void initFields() { + flags_ = 0; + name_ = 0; + returnType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + typeParameter_ = java.util.Collections.emptyList(); + receiverType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + valueParameter_ = java.util.Collections.emptyList(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasReturnType()) { + memoizedIsInitialized = 0; + return false; + } + if (!getReturnType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + for (int i = 0; i < getTypeParameterCount(); i++) { + if (!getTypeParameter(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (hasReceiverType()) { + if (!getReceiverType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (int i = 0; i < getValueParameterCount(); i++) { + if (!getValueParameter(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (!extensionsAreInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + com.google.protobuf.GeneratedMessageLite + .ExtendableMessage<org.jetbrains.kotlin.serialization.ProtoBuf.Function>.ExtensionWriter extensionWriter = + newExtensionWriter(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, flags_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeInt32(2, name_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, returnType_); + } + for (int i = 0; i < typeParameter_.size(); i++) { + output.writeMessage(4, typeParameter_.get(i)); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeMessage(5, receiverType_); + } + for (int i = 0; i < valueParameter_.size(); i++) { + output.writeMessage(6, valueParameter_.get(i)); + } + extensionWriter.writeUntil(200, output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, flags_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(2, name_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, returnType_); + } + for (int i = 0; i < typeParameter_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, typeParameter_.get(i)); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, receiverType_); + } + for (int i = 0; i < valueParameter_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, valueParameter_.get(i)); + } + size += extensionsSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Function parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jetbrains.kotlin.serialization.ProtoBuf.Function prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Function} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageLite.ExtendableBuilder< + org.jetbrains.kotlin.serialization.ProtoBuf.Function, Builder> implements org.jetbrains.kotlin.serialization.ProtoBuf.FunctionOrBuilder { + // Construct using org.jetbrains.kotlin.serialization.ProtoBuf.Function.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + flags_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + returnType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + bitField0_ = (bitField0_ & ~0x00000004); + typeParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + receiverType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + bitField0_ = (bitField0_ & ~0x00000010); + valueParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000020); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Function getDefaultInstanceForType() { + return org.jetbrains.kotlin.serialization.ProtoBuf.Function.getDefaultInstance(); + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Function build() { + org.jetbrains.kotlin.serialization.ProtoBuf.Function result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Function buildPartial() { + org.jetbrains.kotlin.serialization.ProtoBuf.Function result = new org.jetbrains.kotlin.serialization.ProtoBuf.Function(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.flags_ = flags_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.returnType_ = returnType_; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = java.util.Collections.unmodifiableList(typeParameter_); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.typeParameter_ = typeParameter_; + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000008; + } + result.receiverType_ = receiverType_; + if (((bitField0_ & 0x00000020) == 0x00000020)) { + valueParameter_ = java.util.Collections.unmodifiableList(valueParameter_); + bitField0_ = (bitField0_ & ~0x00000020); + } + result.valueParameter_ = valueParameter_; + result.bitField0_ = to_bitField0_; + return result; + } + + public Builder mergeFrom(org.jetbrains.kotlin.serialization.ProtoBuf.Function other) { + if (other == org.jetbrains.kotlin.serialization.ProtoBuf.Function.getDefaultInstance()) return this; + if (other.hasFlags()) { + setFlags(other.getFlags()); + } + if (other.hasName()) { + setName(other.getName()); + } + if (other.hasReturnType()) { + mergeReturnType(other.getReturnType()); + } + if (!other.typeParameter_.isEmpty()) { + if (typeParameter_.isEmpty()) { + typeParameter_ = other.typeParameter_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensureTypeParameterIsMutable(); + typeParameter_.addAll(other.typeParameter_); + } + + } + if (other.hasReceiverType()) { + mergeReceiverType(other.getReceiverType()); + } + if (!other.valueParameter_.isEmpty()) { + if (valueParameter_.isEmpty()) { + valueParameter_ = other.valueParameter_; + bitField0_ = (bitField0_ & ~0x00000020); + } else { + ensureValueParameterIsMutable(); + valueParameter_.addAll(other.valueParameter_); + } + + } + this.mergeExtensionFields(other); + return this; + } + + public final boolean isInitialized() { + if (!hasName()) { + + return false; + } + if (!hasReturnType()) { + + return false; + } + if (!getReturnType().isInitialized()) { + + return false; + } + for (int i = 0; i < getTypeParameterCount(); i++) { + if (!getTypeParameter(i).isInitialized()) { + + return false; + } + } + if (hasReceiverType()) { + if (!getReceiverType().isInitialized()) { + + return false; + } + } + for (int i = 0; i < getValueParameterCount(); i++) { + if (!getValueParameter(i).isInitialized()) { + + return false; + } + } + if (!extensionsAreInitialized()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.jetbrains.kotlin.serialization.ProtoBuf.Function parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jetbrains.kotlin.serialization.ProtoBuf.Function) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + // optional int32 flags = 1; + private int flags_ ; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public int getFlags() { + return flags_; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public Builder setFlags(int value) { + bitField0_ |= 0x00000001; + flags_ = value; + + return this; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isOperator + *isInfix + * </pre> + */ + public Builder clearFlags() { + bitField0_ = (bitField0_ & ~0x00000001); + flags_ = 0; + + return this; + } + + // required int32 name = 2; + private int name_ ; + /** + * <code>required int32 name = 2;</code> + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>required int32 name = 2;</code> + */ + public int getName() { + return name_; + } + /** + * <code>required int32 name = 2;</code> + */ + public Builder setName(int value) { + bitField0_ |= 0x00000002; + name_ = value; + + return this; + } + /** + * <code>required int32 name = 2;</code> + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = 0; + + return this; + } + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + private org.jetbrains.kotlin.serialization.ProtoBuf.Type returnType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public boolean hasReturnType() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Type getReturnType() { + return returnType_; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder setReturnType(org.jetbrains.kotlin.serialization.ProtoBuf.Type value) { + if (value == null) { + throw new NullPointerException(); + } + returnType_ = value; + + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder setReturnType( + org.jetbrains.kotlin.serialization.ProtoBuf.Type.Builder builderForValue) { + returnType_ = builderForValue.build(); + + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder mergeReturnType(org.jetbrains.kotlin.serialization.ProtoBuf.Type value) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + returnType_ != org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance()) { + returnType_ = + org.jetbrains.kotlin.serialization.ProtoBuf.Type.newBuilder(returnType_).mergeFrom(value).buildPartial(); + } else { + returnType_ = value; + } + + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder clearReturnType() { + returnType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> typeParameter_ = + java.util.Collections.emptyList(); + private void ensureTypeParameterIsMutable() { + if (!((bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter>(typeParameter_); + bitField0_ |= 0x00000008; + } + } + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> getTypeParameterList() { + return java.util.Collections.unmodifiableList(typeParameter_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public int getTypeParameterCount() { + return typeParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter getTypeParameter(int index) { + return typeParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder setTypeParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.set(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder setTypeParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter.Builder builderForValue) { + ensureTypeParameterIsMutable(); + typeParameter_.set(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter(org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.add(value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter.Builder builderForValue) { + ensureTypeParameterIsMutable(); + typeParameter_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter.Builder builderForValue) { + ensureTypeParameterIsMutable(); + typeParameter_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addAllTypeParameter( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> values) { + ensureTypeParameterIsMutable(); + super.addAll(values, typeParameter_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder clearTypeParameter() { + typeParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder removeTypeParameter(int index) { + ensureTypeParameterIsMutable(); + typeParameter_.remove(index); + + return this; + } + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + private org.jetbrains.kotlin.serialization.ProtoBuf.Type receiverType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public boolean hasReceiverType() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Type getReceiverType() { + return receiverType_; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder setReceiverType(org.jetbrains.kotlin.serialization.ProtoBuf.Type value) { + if (value == null) { + throw new NullPointerException(); + } + receiverType_ = value; + + bitField0_ |= 0x00000010; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder setReceiverType( + org.jetbrains.kotlin.serialization.ProtoBuf.Type.Builder builderForValue) { + receiverType_ = builderForValue.build(); + + bitField0_ |= 0x00000010; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder mergeReceiverType(org.jetbrains.kotlin.serialization.ProtoBuf.Type value) { + if (((bitField0_ & 0x00000010) == 0x00000010) && + receiverType_ != org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance()) { + receiverType_ = + org.jetbrains.kotlin.serialization.ProtoBuf.Type.newBuilder(receiverType_).mergeFrom(value).buildPartial(); + } else { + receiverType_ = value; + } + + bitField0_ |= 0x00000010; + return this; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public Builder clearReceiverType() { + receiverType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + + bitField0_ = (bitField0_ & ~0x00000010); + return this; + } + + // repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> valueParameter_ = + java.util.Collections.emptyList(); + private void ensureValueParameterIsMutable() { + if (!((bitField0_ & 0x00000020) == 0x00000020)) { + valueParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter>(valueParameter_); + bitField0_ |= 0x00000020; + } + } + + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> getValueParameterList() { + return java.util.Collections.unmodifiableList(valueParameter_); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public int getValueParameterCount() { + return valueParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getValueParameter(int index) { + return valueParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder setValueParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.set(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder setValueParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.Builder builderForValue) { + ensureValueParameterIsMutable(); + valueParameter_.set(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addValueParameter(org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.add(value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addValueParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureValueParameterIsMutable(); + valueParameter_.add(index, value); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addValueParameter( + org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.Builder builderForValue) { + ensureValueParameterIsMutable(); + valueParameter_.add(builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addValueParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.Builder builderForValue) { + ensureValueParameterIsMutable(); + valueParameter_.add(index, builderForValue.build()); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder addAllValueParameter( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter> values) { + ensureValueParameterIsMutable(); + super.addAll(values, valueParameter_); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder clearValueParameter() { + valueParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000020); + + return this; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.ValueParameter value_parameter = 6;</code> + */ + public Builder removeValueParameter(int index) { + ensureValueParameterIsMutable(); + valueParameter_.remove(index); + + return this; + } + + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Function) + } + + static { + defaultInstance = new Function(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Function) + } + + public interface PropertyOrBuilder extends + com.google.protobuf.GeneratedMessageLite. + ExtendableMessageOrBuilder<Property> { + + // optional int32 flags = 1; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + boolean hasFlags(); + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + int getFlags(); + + // required int32 name = 2; + /** + * <code>required int32 name = 2;</code> + */ + boolean hasName(); + /** + * <code>required int32 name = 2;</code> + */ + int getName(); + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + boolean hasReturnType(); + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Type getReturnType(); + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> + getTypeParameterList(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter getTypeParameter(int index); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + int getTypeParameterCount(); + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + boolean hasReceiverType(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.Type getReceiverType(); + + // optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6; + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + boolean hasSetterValueParameter(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getSetterValueParameter(); + + // optional int32 getter_flags = 7; + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + boolean hasGetterFlags(); + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + int getGetterFlags(); + + // optional int32 setter_flags = 8; + /** + * <code>optional int32 setter_flags = 8;</code> + */ + boolean hasSetterFlags(); + /** + * <code>optional int32 setter_flags = 8;</code> + */ + int getSetterFlags(); + } + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Property} + */ + public static final class Property extends + com.google.protobuf.GeneratedMessageLite.ExtendableMessage< + Property> implements PropertyOrBuilder { + // Use Property.newBuilder() to construct. + private Property(com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<org.jetbrains.kotlin.serialization.ProtoBuf.Property, ?> builder) { + super(builder); + + } + private Property(boolean noInit) {} + + private static final Property defaultInstance; + public static Property getDefaultInstance() { + return defaultInstance; + } + + public Property getDefaultInstanceForType() { + return defaultInstance; + } + + private Property( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + flags_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + name_ = input.readInt32(); + break; + } + case 26: { + org.jetbrains.kotlin.serialization.ProtoBuf.Type.Builder subBuilder = null; + if (((bitField0_ & 0x00000004) == 0x00000004)) { + subBuilder = returnType_.toBuilder(); + } + returnType_ = input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Type.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(returnType_); + returnType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000004; + break; + } + case 34: { + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter>(); + mutable_bitField0_ |= 0x00000008; + } + typeParameter_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter.PARSER, extensionRegistry)); + break; + } + case 42: { + org.jetbrains.kotlin.serialization.ProtoBuf.Type.Builder subBuilder = null; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + subBuilder = receiverType_.toBuilder(); + } + receiverType_ = input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Type.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(receiverType_); + receiverType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000008; + break; + } + case 50: { + org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.Builder subBuilder = null; + if (((bitField0_ & 0x00000010) == 0x00000010)) { + subBuilder = setterValueParameter_.toBuilder(); + } + setterValueParameter_ = input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.PARSER, extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(setterValueParameter_); + setterValueParameter_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000010; + break; + } + case 56: { + bitField0_ |= 0x00000020; + getterFlags_ = input.readInt32(); + break; + } + case 64: { + bitField0_ |= 0x00000040; + setterFlags_ = input.readInt32(); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = java.util.Collections.unmodifiableList(typeParameter_); + } + makeExtensionsImmutable(); + } + } + public static com.google.protobuf.Parser<Property> PARSER = + new com.google.protobuf.AbstractParser<Property>() { + public Property parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Property(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser<Property> getParserForType() { + return PARSER; + } + + private int bitField0_; + // optional int32 flags = 1; + public static final int FLAGS_FIELD_NUMBER = 1; + private int flags_; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> */ - int getMemberCount(); - } - /** - * Protobuf type {@code org.jetbrains.kotlin.serialization.Package} - */ - public static final class Package extends - com.google.protobuf.GeneratedMessageLite.ExtendableMessage< - Package> implements PackageOrBuilder { - // Use Package.newBuilder() to construct. - private Package(com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<org.jetbrains.kotlin.serialization.ProtoBuf.Package, ?> builder) { - super(builder); + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public int getFlags() { + return flags_; + } + + // required int32 name = 2; + public static final int NAME_FIELD_NUMBER = 2; + private int name_; + /** + * <code>required int32 name = 2;</code> + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * <code>required int32 name = 2;</code> + */ + public int getName() { + return name_; + } + + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + public static final int RETURN_TYPE_FIELD_NUMBER = 3; + private org.jetbrains.kotlin.serialization.ProtoBuf.Type returnType_; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public boolean hasReturnType() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Type getReturnType() { + return returnType_; + } + + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + public static final int TYPE_PARAMETER_FIELD_NUMBER = 4; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> typeParameter_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> getTypeParameterList() { + return typeParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameterOrBuilder> + getTypeParameterOrBuilderList() { + return typeParameter_; + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public int getTypeParameterCount() { + return typeParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter getTypeParameter(int index) { + return typeParameter_.get(index); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameterOrBuilder getTypeParameterOrBuilder( + int index) { + return typeParameter_.get(index); + } + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + public static final int RECEIVER_TYPE_FIELD_NUMBER = 5; + private org.jetbrains.kotlin.serialization.ProtoBuf.Type receiverType_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public boolean hasReceiverType() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Type getReceiverType() { + return receiverType_; + } + + // optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6; + public static final int SETTER_VALUE_PARAMETER_FIELD_NUMBER = 6; + private org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter setterValueParameter_; + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public boolean hasSetterValueParameter() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getSetterValueParameter() { + return setterValueParameter_; + } + + // optional int32 getter_flags = 7; + public static final int GETTER_FLAGS_FIELD_NUMBER = 7; + private int getterFlags_; + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + public boolean hasGetterFlags() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + public int getGetterFlags() { + return getterFlags_; + } + + // optional int32 setter_flags = 8; + public static final int SETTER_FLAGS_FIELD_NUMBER = 8; + private int setterFlags_; + /** + * <code>optional int32 setter_flags = 8;</code> + */ + public boolean hasSetterFlags() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + /** + * <code>optional int32 setter_flags = 8;</code> + */ + public int getSetterFlags() { + return setterFlags_; + } + + private void initFields() { + flags_ = 0; + name_ = 0; + returnType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + typeParameter_ = java.util.Collections.emptyList(); + receiverType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + setterValueParameter_ = org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.getDefaultInstance(); + getterFlags_ = 0; + setterFlags_ = 0; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasReturnType()) { + memoizedIsInitialized = 0; + return false; + } + if (!getReturnType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + for (int i = 0; i < getTypeParameterCount(); i++) { + if (!getTypeParameter(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (hasReceiverType()) { + if (!getReceiverType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (hasSetterValueParameter()) { + if (!getSetterValueParameter().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + if (!extensionsAreInitialized()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + com.google.protobuf.GeneratedMessageLite + .ExtendableMessage<org.jetbrains.kotlin.serialization.ProtoBuf.Property>.ExtensionWriter extensionWriter = + newExtensionWriter(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, flags_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeInt32(2, name_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, returnType_); + } + for (int i = 0; i < typeParameter_.size(); i++) { + output.writeMessage(4, typeParameter_.get(i)); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeMessage(5, receiverType_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeMessage(6, setterValueParameter_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeInt32(7, getterFlags_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeInt32(8, setterFlags_); + } + extensionWriter.writeUntil(200, output); } - private Package(boolean noInit) {} - private static final Package defaultInstance; - public static Package getDefaultInstance() { - return defaultInstance; + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, flags_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(2, name_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, returnType_); + } + for (int i = 0; i < typeParameter_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, typeParameter_.get(i)); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, receiverType_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, setterValueParameter_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(7, getterFlags_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(8, setterFlags_); + } + size += extensionsSerializedSize(); + memoizedSerializedSize = size; + return size; } - public Package getDefaultInstanceForType() { - return defaultInstance; + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.jetbrains.kotlin.serialization.ProtoBuf.Property parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); } - private Package( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - initFields(); - int mutable_bitField0_ = 0; - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField(input, - extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(); - mutable_bitField0_ |= 0x00000001; - } - member_.add(input.readMessage(org.jetbrains.kotlin.serialization.ProtoBuf.Callable.PARSER, extensionRegistry)); - break; - } + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.jetbrains.kotlin.serialization.ProtoBuf.Property prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + /** + * Protobuf type {@code org.jetbrains.kotlin.serialization.Property} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageLite.ExtendableBuilder< + org.jetbrains.kotlin.serialization.ProtoBuf.Property, Builder> implements org.jetbrains.kotlin.serialization.ProtoBuf.PropertyOrBuilder { + // Construct using org.jetbrains.kotlin.serialization.ProtoBuf.Property.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + flags_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + returnType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + bitField0_ = (bitField0_ & ~0x00000004); + typeParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + receiverType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + bitField0_ = (bitField0_ & ~0x00000010); + setterValueParameter_ = org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.getDefaultInstance(); + bitField0_ = (bitField0_ & ~0x00000020); + getterFlags_ = 0; + bitField0_ = (bitField0_ & ~0x00000040); + setterFlags_ = 0; + bitField0_ = (bitField0_ & ~0x00000080); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Property getDefaultInstanceForType() { + return org.jetbrains.kotlin.serialization.ProtoBuf.Property.getDefaultInstance(); + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Property build() { + org.jetbrains.kotlin.serialization.ProtoBuf.Property result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.jetbrains.kotlin.serialization.ProtoBuf.Property buildPartial() { + org.jetbrains.kotlin.serialization.ProtoBuf.Property result = new org.jetbrains.kotlin.serialization.ProtoBuf.Property(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.flags_ = flags_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.returnType_ = returnType_; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = java.util.Collections.unmodifiableList(typeParameter_); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.typeParameter_ = typeParameter_; + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000008; + } + result.receiverType_ = receiverType_; + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000010; + } + result.setterValueParameter_ = setterValueParameter_; + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000020; + } + result.getterFlags_ = getterFlags_; + if (((from_bitField0_ & 0x00000080) == 0x00000080)) { + to_bitField0_ |= 0x00000040; + } + result.setterFlags_ = setterFlags_; + result.bitField0_ = to_bitField0_; + return result; + } + + public Builder mergeFrom(org.jetbrains.kotlin.serialization.ProtoBuf.Property other) { + if (other == org.jetbrains.kotlin.serialization.ProtoBuf.Property.getDefaultInstance()) return this; + if (other.hasFlags()) { + setFlags(other.getFlags()); + } + if (other.hasName()) { + setName(other.getName()); + } + if (other.hasReturnType()) { + mergeReturnType(other.getReturnType()); + } + if (!other.typeParameter_.isEmpty()) { + if (typeParameter_.isEmpty()) { + typeParameter_ = other.typeParameter_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensureTypeParameterIsMutable(); + typeParameter_.addAll(other.typeParameter_); + } + + } + if (other.hasReceiverType()) { + mergeReceiverType(other.getReceiverType()); + } + if (other.hasSetterValueParameter()) { + mergeSetterValueParameter(other.getSetterValueParameter()); + } + if (other.hasGetterFlags()) { + setGetterFlags(other.getGetterFlags()); + } + if (other.hasSetterFlags()) { + setSetterFlags(other.getSetterFlags()); + } + this.mergeExtensionFields(other); + return this; + } + + public final boolean isInitialized() { + if (!hasName()) { + + return false; + } + if (!hasReturnType()) { + + return false; + } + if (!getReturnType().isInitialized()) { + + return false; + } + for (int i = 0; i < getTypeParameterCount(); i++) { + if (!getTypeParameter(i).isInitialized()) { + + return false; } } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - member_ = java.util.Collections.unmodifiableList(member_); + if (hasReceiverType()) { + if (!getReceiverType().isInitialized()) { + + return false; + } } - makeExtensionsImmutable(); + if (hasSetterValueParameter()) { + if (!getSetterValueParameter().isInitialized()) { + + return false; + } + } + if (!extensionsAreInitialized()) { + + return false; + } + return true; } - } - public static com.google.protobuf.Parser<Package> PARSER = - new com.google.protobuf.AbstractParser<Package>() { - public Package parsePartialFrom( + + public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Package(input, extensionRegistry); + throws java.io.IOException { + org.jetbrains.kotlin.serialization.ProtoBuf.Property parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.jetbrains.kotlin.serialization.ProtoBuf.Property) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - }; - - @java.lang.Override - public com.google.protobuf.Parser<Package> getParserForType() { - return PARSER; - } - - // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; - public static final int MEMBER_FIELD_NUMBER = 1; - private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> member_; - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> getMemberList() { - return member_; - } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public java.util.List<? extends org.jetbrains.kotlin.serialization.ProtoBuf.CallableOrBuilder> - getMemberOrBuilderList() { - return member_; - } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public int getMemberCount() { - return member_.size(); - } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public org.jetbrains.kotlin.serialization.ProtoBuf.Callable getMember(int index) { - return member_.get(index); - } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> - */ - public org.jetbrains.kotlin.serialization.ProtoBuf.CallableOrBuilder getMemberOrBuilder( - int index) { - return member_.get(index); - } + private int bitField0_; - private void initFields() { - member_ = java.util.Collections.emptyList(); - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized != -1) return isInitialized == 1; + // optional int32 flags = 1; + private int flags_ ; + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public boolean hasFlags() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public int getFlags() { + return flags_; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public Builder setFlags(int value) { + bitField0_ |= 0x00000001; + flags_ = value; + + return this; + } + /** + * <code>optional int32 flags = 1;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *MemberKind + *isVar + *hasGetter + *hasSetter + *isConst + *lateinit + *hasConstant + * </pre> + */ + public Builder clearFlags() { + bitField0_ = (bitField0_ & ~0x00000001); + flags_ = 0; + + return this; + } - for (int i = 0; i < getMemberCount(); i++) { - if (!getMember(i).isInitialized()) { - memoizedIsInitialized = 0; - return false; - } + // required int32 name = 2; + private int name_ ; + /** + * <code>required int32 name = 2;</code> + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); } - if (!extensionsAreInitialized()) { - memoizedIsInitialized = 0; - return false; + /** + * <code>required int32 name = 2;</code> + */ + public int getName() { + return name_; + } + /** + * <code>required int32 name = 2;</code> + */ + public Builder setName(int value) { + bitField0_ |= 0x00000002; + name_ = value; + + return this; + } + /** + * <code>required int32 name = 2;</code> + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = 0; + + return this; } - memoizedIsInitialized = 1; - return true; - } - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - com.google.protobuf.GeneratedMessageLite - .ExtendableMessage<org.jetbrains.kotlin.serialization.ProtoBuf.Package>.ExtensionWriter extensionWriter = - newExtensionWriter(); - for (int i = 0; i < member_.size(); i++) { - output.writeMessage(1, member_.get(i)); + // required .org.jetbrains.kotlin.serialization.Type return_type = 3; + private org.jetbrains.kotlin.serialization.ProtoBuf.Type returnType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public boolean hasReturnType() { + return ((bitField0_ & 0x00000004) == 0x00000004); } - extensionWriter.writeUntil(200, output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.Type getReturnType() { + return returnType_; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder setReturnType(org.jetbrains.kotlin.serialization.ProtoBuf.Type value) { + if (value == null) { + throw new NullPointerException(); + } + returnType_ = value; - size = 0; - for (int i = 0; i < member_.size(); i++) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(1, member_.get(i)); + bitField0_ |= 0x00000004; + return this; } - size += extensionsSerializedSize(); - memoizedSerializedSize = size; - return size; - } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder setReturnType( + org.jetbrains.kotlin.serialization.ProtoBuf.Type.Builder builderForValue) { + returnType_ = builderForValue.build(); - private static final long serialVersionUID = 0L; - @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); - } + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder mergeReturnType(org.jetbrains.kotlin.serialization.ProtoBuf.Type value) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + returnType_ != org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance()) { + returnType_ = + org.jetbrains.kotlin.serialization.ProtoBuf.Type.newBuilder(returnType_).mergeFrom(value).buildPartial(); + } else { + returnType_ = value; + } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static org.jetbrains.kotlin.serialization.ProtoBuf.Package parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } + bitField0_ |= 0x00000004; + return this; + } + /** + * <code>required .org.jetbrains.kotlin.serialization.Type return_type = 3;</code> + */ + public Builder clearReturnType() { + returnType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(org.jetbrains.kotlin.serialization.ProtoBuf.Package prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } - /** - * Protobuf type {@code org.jetbrains.kotlin.serialization.Package} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageLite.ExtendableBuilder< - org.jetbrains.kotlin.serialization.ProtoBuf.Package, Builder> implements org.jetbrains.kotlin.serialization.ProtoBuf.PackageOrBuilder { - // Construct using org.jetbrains.kotlin.serialization.ProtoBuf.Package.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); + // repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4; + private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> typeParameter_ = + java.util.Collections.emptyList(); + private void ensureTypeParameterIsMutable() { + if (!((bitField0_ & 0x00000008) == 0x00000008)) { + typeParameter_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter>(typeParameter_); + bitField0_ |= 0x00000008; + } } - private void maybeForceBuilderInitialization() { + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> getTypeParameterList() { + return java.util.Collections.unmodifiableList(typeParameter_); } - private static Builder create() { - return new Builder(); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public int getTypeParameterCount() { + return typeParameter_.size(); + } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter getTypeParameter(int index) { + return typeParameter_.get(index); } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder setTypeParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.set(index, value); - public Builder clear() { - super.clear(); - member_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); return this; } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder setTypeParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter.Builder builderForValue) { + ensureTypeParameterIsMutable(); + typeParameter_.set(index, builderForValue.build()); - public Builder clone() { - return create().mergeFrom(buildPartial()); + return this; } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter(org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter value) { + if (value == null) { + throw new NullPointerException(); + } + ensureTypeParameterIsMutable(); + typeParameter_.add(value); - public org.jetbrains.kotlin.serialization.ProtoBuf.Package getDefaultInstanceForType() { - return org.jetbrains.kotlin.serialization.ProtoBuf.Package.getDefaultInstance(); + return this; } - - public org.jetbrains.kotlin.serialization.ProtoBuf.Package build() { - org.jetbrains.kotlin.serialization.ProtoBuf.Package result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter value) { + if (value == null) { + throw new NullPointerException(); } - return result; - } + ensureTypeParameterIsMutable(); + typeParameter_.add(index, value); - public org.jetbrains.kotlin.serialization.ProtoBuf.Package buildPartial() { - org.jetbrains.kotlin.serialization.ProtoBuf.Package result = new org.jetbrains.kotlin.serialization.ProtoBuf.Package(this); - int from_bitField0_ = bitField0_; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - member_ = java.util.Collections.unmodifiableList(member_); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.member_ = member_; - return result; + return this; } - - public Builder mergeFrom(org.jetbrains.kotlin.serialization.ProtoBuf.Package other) { - if (other == org.jetbrains.kotlin.serialization.ProtoBuf.Package.getDefaultInstance()) return this; - if (!other.member_.isEmpty()) { - if (member_.isEmpty()) { - member_ = other.member_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureMemberIsMutable(); - member_.addAll(other.member_); - } - - } - this.mergeExtensionFields(other); + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter.Builder builderForValue) { + ensureTypeParameterIsMutable(); + typeParameter_.add(builderForValue.build()); + return this; } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addTypeParameter( + int index, org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter.Builder builderForValue) { + ensureTypeParameterIsMutable(); + typeParameter_.add(index, builderForValue.build()); - public final boolean isInitialized() { - for (int i = 0; i < getMemberCount(); i++) { - if (!getMember(i).isInitialized()) { - - return false; - } - } - if (!extensionsAreInitialized()) { - - return false; - } - return true; + return this; } + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder addAllTypeParameter( + java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.TypeParameter> values) { + ensureTypeParameterIsMutable(); + super.addAll(values, typeParameter_); - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.jetbrains.kotlin.serialization.ProtoBuf.Package parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.jetbrains.kotlin.serialization.ProtoBuf.Package) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } return this; } - private int bitField0_; + /** + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> + */ + public Builder clearTypeParameter() { + typeParameter_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); - // repeated .org.jetbrains.kotlin.serialization.Callable member = 1; - private java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> member_ = - java.util.Collections.emptyList(); - private void ensureMemberIsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - member_ = new java.util.ArrayList<org.jetbrains.kotlin.serialization.ProtoBuf.Callable>(member_); - bitField0_ |= 0x00000001; - } + return this; } - /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>repeated .org.jetbrains.kotlin.serialization.TypeParameter type_parameter = 4;</code> */ - public java.util.List<org.jetbrains.kotlin.serialization.ProtoBuf.Callable> getMemberList() { - return java.util.Collections.unmodifiableList(member_); + public Builder removeTypeParameter(int index) { + ensureTypeParameterIsMutable(); + typeParameter_.remove(index); + + return this; } + + // optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5; + private org.jetbrains.kotlin.serialization.ProtoBuf.Type receiverType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> */ - public int getMemberCount() { - return member_.size(); + public boolean hasReceiverType() { + return ((bitField0_ & 0x00000010) == 0x00000010); } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> */ - public org.jetbrains.kotlin.serialization.ProtoBuf.Callable getMember(int index) { - return member_.get(index); + public org.jetbrains.kotlin.serialization.ProtoBuf.Type getReceiverType() { + return receiverType_; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> */ - public Builder setMember( - int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + public Builder setReceiverType(org.jetbrains.kotlin.serialization.ProtoBuf.Type value) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.set(index, value); + receiverType_ = value; + bitField0_ |= 0x00000010; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> */ - public Builder setMember( - int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureMemberIsMutable(); - member_.set(index, builderForValue.build()); + public Builder setReceiverType( + org.jetbrains.kotlin.serialization.ProtoBuf.Type.Builder builderForValue) { + receiverType_ = builderForValue.build(); + bitField0_ |= 0x00000010; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> */ - public Builder addMember(org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { - if (value == null) { - throw new NullPointerException(); + public Builder mergeReceiverType(org.jetbrains.kotlin.serialization.ProtoBuf.Type value) { + if (((bitField0_ & 0x00000010) == 0x00000010) && + receiverType_ != org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance()) { + receiverType_ = + org.jetbrains.kotlin.serialization.ProtoBuf.Type.newBuilder(receiverType_).mergeFrom(value).buildPartial(); + } else { + receiverType_ = value; } - ensureMemberIsMutable(); - member_.add(value); + bitField0_ |= 0x00000010; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.Type receiver_type = 5;</code> */ - public Builder addMember( - int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable value) { + public Builder clearReceiverType() { + receiverType_ = org.jetbrains.kotlin.serialization.ProtoBuf.Type.getDefaultInstance(); + + bitField0_ = (bitField0_ & ~0x00000010); + return this; + } + + // optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6; + private org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter setterValueParameter_ = org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.getDefaultInstance(); + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public boolean hasSetterValueParameter() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter getSetterValueParameter() { + return setterValueParameter_; + } + /** + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> + */ + public Builder setSetterValueParameter(org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter value) { if (value == null) { throw new NullPointerException(); } - ensureMemberIsMutable(); - member_.add(index, value); + setterValueParameter_ = value; + bitField0_ |= 0x00000020; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder addMember( - org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureMemberIsMutable(); - member_.add(builderForValue.build()); + public Builder setSetterValueParameter( + org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.Builder builderForValue) { + setterValueParameter_ = builderForValue.build(); + bitField0_ |= 0x00000020; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder addMember( - int index, org.jetbrains.kotlin.serialization.ProtoBuf.Callable.Builder builderForValue) { - ensureMemberIsMutable(); - member_.add(index, builderForValue.build()); + public Builder mergeSetterValueParameter(org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter value) { + if (((bitField0_ & 0x00000020) == 0x00000020) && + setterValueParameter_ != org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.getDefaultInstance()) { + setterValueParameter_ = + org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.newBuilder(setterValueParameter_).mergeFrom(value).buildPartial(); + } else { + setterValueParameter_ = value; + } + bitField0_ |= 0x00000020; return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional .org.jetbrains.kotlin.serialization.ValueParameter setter_value_parameter = 6;</code> */ - public Builder addAllMember( - java.lang.Iterable<? extends org.jetbrains.kotlin.serialization.ProtoBuf.Callable> values) { - ensureMemberIsMutable(); - super.addAll(values, member_); + public Builder clearSetterValueParameter() { + setterValueParameter_ = org.jetbrains.kotlin.serialization.ProtoBuf.ValueParameter.getDefaultInstance(); + bitField0_ = (bitField0_ & ~0x00000020); return this; } + + // optional int32 getter_flags = 7; + private int getterFlags_ ; /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> */ - public Builder clearMember() { - member_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); - + public boolean hasGetterFlags() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + public int getGetterFlags() { + return getterFlags_; + } + /** + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> + */ + public Builder setGetterFlags(int value) { + bitField0_ |= 0x00000040; + getterFlags_ = value; + return this; } /** - * <code>repeated .org.jetbrains.kotlin.serialization.Callable member = 1;</code> + * <code>optional int32 getter_flags = 7;</code> + * + * <pre> + * + *hasAnnotations + *Visibility + *Modality + *isNotDefault + * </pre> */ - public Builder removeMember(int index) { - ensureMemberIsMutable(); - member_.remove(index); + public Builder clearGetterFlags() { + bitField0_ = (bitField0_ & ~0x00000040); + getterFlags_ = 0; + + return this; + } + // optional int32 setter_flags = 8; + private int setterFlags_ ; + /** + * <code>optional int32 setter_flags = 8;</code> + */ + public boolean hasSetterFlags() { + return ((bitField0_ & 0x00000080) == 0x00000080); + } + /** + * <code>optional int32 setter_flags = 8;</code> + */ + public int getSetterFlags() { + return setterFlags_; + } + /** + * <code>optional int32 setter_flags = 8;</code> + */ + public Builder setSetterFlags(int value) { + bitField0_ |= 0x00000080; + setterFlags_ = value; + + return this; + } + /** + * <code>optional int32 setter_flags = 8;</code> + */ + public Builder clearSetterFlags() { + bitField0_ = (bitField0_ & ~0x00000080); + setterFlags_ = 0; + return this; } - // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Package) + // @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.serialization.Property) } static { - defaultInstance = new Package(true); + defaultInstance = new Property(true); defaultInstance.initFields(); } - // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Package) + // @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.serialization.Property) } public interface CallableOrBuilder extends diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/MemberDeserializer.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/MemberDeserializer.kt index 6c11902a307e2..68d61c370f54d 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/MemberDeserializer.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/MemberDeserializer.kt @@ -56,13 +56,13 @@ public class MemberDeserializer(private val c: DeserializationContext) { Deserialization.memberKind(Flags.MEMBER_KIND.get(flags)), proto, c.nameResolver, - Flags.LATE_INIT.get(flags), - Flags.IS_CONST.get(flags) + Flags.OLD_LATE_INIT.get(flags), + Flags.OLD_IS_CONST.get(flags) ) val local = c.childContext(property, proto.getTypeParameterList()) - val hasGetter = Flags.HAS_GETTER.get(flags) + val hasGetter = Flags.OLD_HAS_GETTER.get(flags) val receiverAnnotations = if (hasGetter) getReceiverParameterAnnotations(proto, AnnotatedCallableKind.PROPERTY_GETTER) else @@ -99,7 +99,7 @@ public class MemberDeserializer(private val c: DeserializationContext) { null } - val setter = if (Flags.HAS_SETTER.get(flags)) { + val setter = if (Flags.OLD_HAS_SETTER.get(flags)) { val setterFlags = proto.getSetterFlags() val isNotDefault = proto.hasSetterFlags() && Flags.IS_NOT_DEFAULT.get(setterFlags) if (isNotDefault) { @@ -125,7 +125,7 @@ public class MemberDeserializer(private val c: DeserializationContext) { null } - if (Flags.HAS_CONSTANT.get(flags)) { + if (Flags.OLD_HAS_CONSTANT.get(flags)) { property.setCompileTimeInitializer( c.storageManager.createNullableLazyValue { val container = c.containingDeclaration.asProtoContainer()!! @@ -152,8 +152,8 @@ public class MemberDeserializer(private val c: DeserializationContext) { local.typeDeserializer.type(proto.returnType), Deserialization.modality(Flags.MODALITY.get(proto.flags)), Deserialization.visibility(Flags.VISIBILITY.get(proto.flags)), - Flags.IS_OPERATOR.get(proto.flags), - Flags.IS_INFIX.get(proto.flags) + Flags.OLD_IS_OPERATOR.get(proto.flags), + Flags.OLD_IS_INFIX.get(proto.flags) ) return function } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt index ece8cc1813ae3..4a5de97b9fc62 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt @@ -188,25 +188,25 @@ enum class FlagsToModifiers { CONST { override fun getModifiers(flags: Int): JetModifierKeywordToken? { - return if (Flags.IS_CONST.get(flags)) JetTokens.CONST_KEYWORD else null + return if (Flags.OLD_IS_CONST.get(flags)) JetTokens.CONST_KEYWORD else null } }, LATEINIT { override fun getModifiers(flags: Int): JetModifierKeywordToken? { - return if (Flags.LATE_INIT.get(flags)) JetTokens.LATE_INIT_KEYWORD else null + return if (Flags.OLD_LATE_INIT.get(flags)) JetTokens.LATE_INIT_KEYWORD else null } }, OPERATOR { override fun getModifiers(flags: Int): JetModifierKeywordToken? { - return if (Flags.IS_OPERATOR.get(flags)) JetTokens.OPERATOR_KEYWORD else null + return if (Flags.OLD_IS_OPERATOR.get(flags)) JetTokens.OPERATOR_KEYWORD else null } }, INFIX { override fun getModifiers(flags: Int): JetModifierKeywordToken? { - return if (Flags.IS_INFIX.get(flags)) JetTokens.INFIX_KEYWORD else null + return if (Flags.OLD_IS_INFIX.get(flags)) JetTokens.INFIX_KEYWORD else null } }; diff --git a/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/ProtoCompareGenerated.kt b/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/ProtoCompareGenerated.kt index 2b7e42dfdc8c4..f6ae431add237 100644 --- a/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/ProtoCompareGenerated.kt +++ b/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/ProtoCompareGenerated.kt @@ -37,10 +37,19 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi open fun checkEquals(old: ProtoBuf.Package, new: ProtoBuf.Package): Boolean { if (!checkEqualsPackageMember(old, new)) return false + if (!checkEqualsPackageConstructor(old, new)) return false + + if (!checkEqualsPackageFunction(old, new)) return false + + if (!checkEqualsPackageProperty(old, new)) return false + return true } public enum class ProtoBufPackageKind { - MEMBER_LIST + MEMBER_LIST, + CONSTRUCTOR_LIST, + FUNCTION_LIST, + PROPERTY_LIST } public fun difference(old: ProtoBuf.Package, new: ProtoBuf.Package): EnumSet<ProtoBufPackageKind> { @@ -48,6 +57,12 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi if (!checkEqualsPackageMember(old, new)) result.add(ProtoBufPackageKind.MEMBER_LIST) + if (!checkEqualsPackageConstructor(old, new)) result.add(ProtoBufPackageKind.CONSTRUCTOR_LIST) + + if (!checkEqualsPackageFunction(old, new)) result.add(ProtoBufPackageKind.FUNCTION_LIST) + + if (!checkEqualsPackageProperty(old, new)) result.add(ProtoBufPackageKind.PROPERTY_LIST) + return result } @@ -70,6 +85,12 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi if (!checkEqualsClassNestedClassName(old, new)) return false + if (!checkEqualsClassConstructor(old, new)) return false + + if (!checkEqualsClassFunction(old, new)) return false + + if (!checkEqualsClassProperty(old, new)) return false + if (!checkEqualsClassMember(old, new)) return false if (!checkEqualsClassEnumEntry(old, new)) return false @@ -96,6 +117,9 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi TYPE_PARAMETER_LIST, SUPERTYPE_LIST, NESTED_CLASS_NAME_LIST, + CONSTRUCTOR_LIST, + FUNCTION_LIST, + PROPERTY_LIST, MEMBER_LIST, ENUM_ENTRY_LIST, PRIMARY_CONSTRUCTOR, @@ -124,6 +148,12 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi if (!checkEqualsClassNestedClassName(old, new)) result.add(ProtoBufClassKind.NESTED_CLASS_NAME_LIST) + if (!checkEqualsClassConstructor(old, new)) result.add(ProtoBufClassKind.CONSTRUCTOR_LIST) + + if (!checkEqualsClassFunction(old, new)) result.add(ProtoBufClassKind.FUNCTION_LIST) + + if (!checkEqualsClassProperty(old, new)) result.add(ProtoBufClassKind.PROPERTY_LIST) + if (!checkEqualsClassMember(old, new)) result.add(ProtoBufClassKind.MEMBER_LIST) if (!checkEqualsClassEnumEntry(old, new)) result.add(ProtoBufClassKind.ENUM_ENTRY_LIST) @@ -191,6 +221,74 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi return true } + open fun checkEquals(old: ProtoBuf.Constructor, new: ProtoBuf.Constructor): Boolean { + if (old.hasFlags() != new.hasFlags()) return false + if (old.hasFlags()) { + if (old.flags != new.flags) return false + } + + if (!checkEqualsConstructorValueParameter(old, new)) return false + + return true + } + + open fun checkEquals(old: ProtoBuf.Function, new: ProtoBuf.Function): Boolean { + if (old.hasFlags() != new.hasFlags()) return false + if (old.hasFlags()) { + if (old.flags != new.flags) return false + } + + if (!checkStringEquals(old.name, new.name)) return false + + if (!checkEquals(old.returnType, new.returnType)) return false + + if (!checkEqualsFunctionTypeParameter(old, new)) return false + + if (old.hasReceiverType() != new.hasReceiverType()) return false + if (old.hasReceiverType()) { + if (!checkEquals(old.receiverType, new.receiverType)) return false + } + + if (!checkEqualsFunctionValueParameter(old, new)) return false + + return true + } + + open fun checkEquals(old: ProtoBuf.Property, new: ProtoBuf.Property): Boolean { + if (old.hasFlags() != new.hasFlags()) return false + if (old.hasFlags()) { + if (old.flags != new.flags) return false + } + + if (!checkStringEquals(old.name, new.name)) return false + + if (!checkEquals(old.returnType, new.returnType)) return false + + if (!checkEqualsPropertyTypeParameter(old, new)) return false + + if (old.hasReceiverType() != new.hasReceiverType()) return false + if (old.hasReceiverType()) { + if (!checkEquals(old.receiverType, new.receiverType)) return false + } + + if (old.hasSetterValueParameter() != new.hasSetterValueParameter()) return false + if (old.hasSetterValueParameter()) { + if (!checkEquals(old.setterValueParameter, new.setterValueParameter)) return false + } + + if (old.hasGetterFlags() != new.hasGetterFlags()) return false + if (old.hasGetterFlags()) { + if (old.getterFlags != new.getterFlags) return false + } + + if (old.hasSetterFlags() != new.hasSetterFlags()) return false + if (old.hasSetterFlags()) { + if (old.setterFlags != new.setterFlags) return false + } + + return true + } + open fun checkEquals(old: ProtoBuf.TypeParameter, new: ProtoBuf.TypeParameter): Boolean { if (old.id != new.id) return false @@ -416,6 +514,36 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi return true } + open fun checkEqualsPackageConstructor(old: ProtoBuf.Package, new: ProtoBuf.Package): Boolean { + if (old.constructorCount != new.constructorCount) return false + + for(i in 0..old.constructorCount - 1) { + if (!checkEquals(old.getConstructor(i), new.getConstructor(i))) return false + } + + return true + } + + open fun checkEqualsPackageFunction(old: ProtoBuf.Package, new: ProtoBuf.Package): Boolean { + if (old.functionCount != new.functionCount) return false + + for(i in 0..old.functionCount - 1) { + if (!checkEquals(old.getFunction(i), new.getFunction(i))) return false + } + + return true + } + + open fun checkEqualsPackageProperty(old: ProtoBuf.Package, new: ProtoBuf.Package): Boolean { + if (old.propertyCount != new.propertyCount) return false + + for(i in 0..old.propertyCount - 1) { + if (!checkEquals(old.getProperty(i), new.getProperty(i))) return false + } + + return true + } + open fun checkEqualsClassTypeParameter(old: ProtoBuf.Class, new: ProtoBuf.Class): Boolean { if (old.typeParameterCount != new.typeParameterCount) return false @@ -446,6 +574,36 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi return true } + open fun checkEqualsClassConstructor(old: ProtoBuf.Class, new: ProtoBuf.Class): Boolean { + if (old.constructorCount != new.constructorCount) return false + + for(i in 0..old.constructorCount - 1) { + if (!checkEquals(old.getConstructor(i), new.getConstructor(i))) return false + } + + return true + } + + open fun checkEqualsClassFunction(old: ProtoBuf.Class, new: ProtoBuf.Class): Boolean { + if (old.functionCount != new.functionCount) return false + + for(i in 0..old.functionCount - 1) { + if (!checkEquals(old.getFunction(i), new.getFunction(i))) return false + } + + return true + } + + open fun checkEqualsClassProperty(old: ProtoBuf.Class, new: ProtoBuf.Class): Boolean { + if (old.propertyCount != new.propertyCount) return false + + for(i in 0..old.propertyCount - 1) { + if (!checkEquals(old.getProperty(i), new.getProperty(i))) return false + } + + return true + } + open fun checkEqualsClassMember(old: ProtoBuf.Class, new: ProtoBuf.Class): Boolean { if (old.memberCount != new.memberCount) return false @@ -496,6 +654,46 @@ open class ProtoCompareGenerated(public val oldNameResolver: NameResolver, publi return true } + open fun checkEqualsConstructorValueParameter(old: ProtoBuf.Constructor, new: ProtoBuf.Constructor): Boolean { + if (old.valueParameterCount != new.valueParameterCount) return false + + for(i in 0..old.valueParameterCount - 1) { + if (!checkEquals(old.getValueParameter(i), new.getValueParameter(i))) return false + } + + return true + } + + open fun checkEqualsFunctionTypeParameter(old: ProtoBuf.Function, new: ProtoBuf.Function): Boolean { + if (old.typeParameterCount != new.typeParameterCount) return false + + for(i in 0..old.typeParameterCount - 1) { + if (!checkEquals(old.getTypeParameter(i), new.getTypeParameter(i))) return false + } + + return true + } + + open fun checkEqualsFunctionValueParameter(old: ProtoBuf.Function, new: ProtoBuf.Function): Boolean { + if (old.valueParameterCount != new.valueParameterCount) return false + + for(i in 0..old.valueParameterCount - 1) { + if (!checkEquals(old.getValueParameter(i), new.getValueParameter(i))) return false + } + + return true + } + + open fun checkEqualsPropertyTypeParameter(old: ProtoBuf.Property, new: ProtoBuf.Property): Boolean { + if (old.typeParameterCount != new.typeParameterCount) return false + + for(i in 0..old.typeParameterCount - 1) { + if (!checkEquals(old.getTypeParameter(i), new.getTypeParameter(i))) return false + } + + return true + } + open fun checkEqualsTypeParameterUpperBound(old: ProtoBuf.TypeParameter, new: ProtoBuf.TypeParameter): Boolean { if (old.upperBoundCount != new.upperBoundCount) return false @@ -574,6 +772,18 @@ public fun ProtoBuf.Package.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: hashCode = 31 * hashCode + getMember(i).hashCode(stringIndexes, fqNameIndexes) } + for(i in 0..constructorCount - 1) { + hashCode = 31 * hashCode + getConstructor(i).hashCode(stringIndexes, fqNameIndexes) + } + + for(i in 0..functionCount - 1) { + hashCode = 31 * hashCode + getFunction(i).hashCode(stringIndexes, fqNameIndexes) + } + + for(i in 0..propertyCount - 1) { + hashCode = 31 * hashCode + getProperty(i).hashCode(stringIndexes, fqNameIndexes) + } + return hashCode } @@ -602,6 +812,18 @@ public fun ProtoBuf.Class.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: ( hashCode = 31 * hashCode + stringIndexes(getNestedClassName(i)) } + for(i in 0..constructorCount - 1) { + hashCode = 31 * hashCode + getConstructor(i).hashCode(stringIndexes, fqNameIndexes) + } + + for(i in 0..functionCount - 1) { + hashCode = 31 * hashCode + getFunction(i).hashCode(stringIndexes, fqNameIndexes) + } + + for(i in 0..propertyCount - 1) { + hashCode = 31 * hashCode + getProperty(i).hashCode(stringIndexes, fqNameIndexes) + } + for(i in 0..memberCount - 1) { hashCode = 31 * hashCode + getMember(i).hashCode(stringIndexes, fqNameIndexes) } @@ -671,6 +893,80 @@ public fun ProtoBuf.Callable.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes return hashCode } +public fun ProtoBuf.Constructor.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int { + var hashCode = 1 + + if (hasFlags()) { + hashCode = 31 * hashCode + flags + } + + for(i in 0..valueParameterCount - 1) { + hashCode = 31 * hashCode + getValueParameter(i).hashCode(stringIndexes, fqNameIndexes) + } + + return hashCode +} + +public fun ProtoBuf.Function.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int { + var hashCode = 1 + + if (hasFlags()) { + hashCode = 31 * hashCode + flags + } + + hashCode = 31 * hashCode + stringIndexes(name) + + hashCode = 31 * hashCode + returnType.hashCode(stringIndexes, fqNameIndexes) + + for(i in 0..typeParameterCount - 1) { + hashCode = 31 * hashCode + getTypeParameter(i).hashCode(stringIndexes, fqNameIndexes) + } + + if (hasReceiverType()) { + hashCode = 31 * hashCode + receiverType.hashCode(stringIndexes, fqNameIndexes) + } + + for(i in 0..valueParameterCount - 1) { + hashCode = 31 * hashCode + getValueParameter(i).hashCode(stringIndexes, fqNameIndexes) + } + + return hashCode +} + +public fun ProtoBuf.Property.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int { + var hashCode = 1 + + if (hasFlags()) { + hashCode = 31 * hashCode + flags + } + + hashCode = 31 * hashCode + stringIndexes(name) + + hashCode = 31 * hashCode + returnType.hashCode(stringIndexes, fqNameIndexes) + + for(i in 0..typeParameterCount - 1) { + hashCode = 31 * hashCode + getTypeParameter(i).hashCode(stringIndexes, fqNameIndexes) + } + + if (hasReceiverType()) { + hashCode = 31 * hashCode + receiverType.hashCode(stringIndexes, fqNameIndexes) + } + + if (hasSetterValueParameter()) { + hashCode = 31 * hashCode + setterValueParameter.hashCode(stringIndexes, fqNameIndexes) + } + + if (hasGetterFlags()) { + hashCode = 31 * hashCode + getterFlags + } + + if (hasSetterFlags()) { + hashCode = 31 * hashCode + setterFlags + } + + return hashCode +} + public fun ProtoBuf.TypeParameter.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int { var hashCode = 1 diff --git a/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/protoDifferenceUtils.kt b/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/protoDifferenceUtils.kt index d123201c3e4b5..33b4b30916f32 100644 --- a/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/protoDifferenceUtils.kt +++ b/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/protoDifferenceUtils.kt @@ -16,7 +16,10 @@ package org.jetbrains.kotlin.jps.incremental +import com.google.protobuf.MessageLite import org.jetbrains.kotlin.descriptors.Visibilities +import org.jetbrains.kotlin.jps.incremental.ProtoCompareGenerated.ProtoBufClassKind +import org.jetbrains.kotlin.jps.incremental.ProtoCompareGenerated.ProtoBufPackageKind import org.jetbrains.kotlin.serialization.Flags import org.jetbrains.kotlin.serialization.ProtoBuf import org.jetbrains.kotlin.serialization.deserialization.Deserialization @@ -52,17 +55,16 @@ private abstract class DifferenceCalculator() { protected fun membersOrNone(names: Collection<String>): DifferenceKind = if (names.isEmpty()) DifferenceKind.NONE else DifferenceKind.MEMBERS(names) - protected fun calcDifferenceForMembers( - oldList: List<ProtoBuf.Callable>, - newList: List<ProtoBuf.Callable> - ): Collection<String> { + protected fun calcDifferenceForMembers(oldList: List<MessageLite>, newList: List<MessageLite>): Collection<String> { val result = hashSetOf<String>() - val oldMap = oldList.groupBy { it.hashCode({ compareObject.oldGetIndexOfString(it) }, { compareObject.oldGetIndexOfClassId(it) } )} - val newMap = newList.groupBy { it.hashCode({ compareObject.newGetIndexOfString(it) }, { compareObject.newGetIndexOfClassId(it) } )} + fun List<MessageLite>.names(nameResolver: NameResolver): List<String> = + map { it.name(nameResolver) } - fun List<ProtoBuf.Callable>.names(nameResolver: NameResolver): List<String> = - map { nameResolver.getString(it.name) } + val oldMap = + oldList.groupBy { it.getHashCode({ compareObject.oldGetIndexOfString(it) }, { compareObject.oldGetIndexOfClassId(it) }) } + val newMap = + newList.groupBy { it.getHashCode({ compareObject.newGetIndexOfString(it) }, { compareObject.newGetIndexOfClassId(it) }) } val hashes = oldMap.keySet() + newMap.keySet() for (hash in hashes) { @@ -81,8 +83,8 @@ private abstract class DifferenceCalculator() { } private fun calcDifferenceForEqualHashes( - oldList: List<ProtoBuf.Callable>, - newList: List<ProtoBuf.Callable> + oldList: List<MessageLite>, + newList: List<MessageLite> ): Collection<String> { val result = hashSetOf<String>() val newSet = HashSet(newList) @@ -93,12 +95,12 @@ private abstract class DifferenceCalculator() { newSet.remove(newMember) } else { - result.add(compareObject.oldNameResolver.getString(oldMember.name)) + result.add(oldMember.name(compareObject.oldNameResolver)) } } newSet.forEach { newMember -> - result.add(compareObject.newNameResolver.getString(newMember.name)) + result.add(newMember.name(compareObject.newNameResolver)) } return result @@ -113,8 +115,45 @@ private abstract class DifferenceCalculator() { return HashSetUtil.symmetricDifference(oldNames, newNames) } - protected val ProtoBuf.Callable.isPrivate: Boolean - get() = Visibilities.isPrivate(Deserialization.visibility(Flags.VISIBILITY.get(flags))) + protected val MessageLite.isPrivate: Boolean + get() = Visibilities.isPrivate(Deserialization.visibility( + when (this) { + is ProtoBuf.Callable -> Flags.VISIBILITY.get(flags) + is ProtoBuf.Constructor -> Flags.VISIBILITY.get(flags) + is ProtoBuf.Function -> Flags.VISIBILITY.get(flags) + is ProtoBuf.Property -> Flags.VISIBILITY.get(flags) + else -> error("Unknown message: $this") + })) + + private fun MessageLite.getHashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) -> Int): Int { + return when (this) { + is ProtoBuf.Callable -> hashCode(stringIndexes, fqNameIndexes) + is ProtoBuf.Constructor -> hashCode(stringIndexes, fqNameIndexes) + is ProtoBuf.Function -> hashCode(stringIndexes, fqNameIndexes) + is ProtoBuf.Property -> hashCode(stringIndexes, fqNameIndexes) + else -> error("Unknown message: $this") + } + } + + private fun MessageLite.name(nameResolver: NameResolver): String { + return when (this) { + is ProtoBuf.Callable -> nameResolver.getString(name) + is ProtoBuf.Constructor -> "<init>" + is ProtoBuf.Function -> nameResolver.getString(name) + is ProtoBuf.Property -> nameResolver.getString(name) + else -> error("Unknown message: $this") + } + } + + private fun ProtoCompareGenerated.checkEquals(old: MessageLite, new: MessageLite): Boolean { + return when { + old is ProtoBuf.Callable && new is ProtoBuf.Callable -> checkEquals(old, new) + old is ProtoBuf.Constructor && new is ProtoBuf.Constructor -> checkEquals(old, new) + old is ProtoBuf.Function && new is ProtoBuf.Function -> checkEquals(old, new) + old is ProtoBuf.Property && new is ProtoBuf.Property -> checkEquals(old, new) + else -> error("Unknown message: $this") + } + } } private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: ProtoMapValue) : DifferenceCalculator() { @@ -122,11 +161,11 @@ private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: Prot private val CONSTRUCTOR = "<init>" private val CLASS_SIGNATURE_ENUMS = EnumSet.of( - ProtoCompareGenerated.ProtoBufClassKind.FLAGS, - ProtoCompareGenerated.ProtoBufClassKind.FQ_NAME, - ProtoCompareGenerated.ProtoBufClassKind.TYPE_PARAMETER_LIST, - ProtoCompareGenerated.ProtoBufClassKind.SUPERTYPE_LIST, - ProtoCompareGenerated.ProtoBufClassKind.CLASS_ANNOTATION_LIST + ProtoBufClassKind.FLAGS, + ProtoBufClassKind.FQ_NAME, + ProtoBufClassKind.TYPE_PARAMETER_LIST, + ProtoBufClassKind.SUPERTYPE_LIST, + ProtoBufClassKind.CLASS_ANNOTATION_LIST ) } @@ -155,34 +194,43 @@ private class DifferenceCalculatorForClass(oldData: ProtoMapValue, newData: Prot fun Int.oldToNames() = names.add(oldNameResolver.getString(this)) fun Int.newToNames() = names.add(newNameResolver.getString(this)) + fun calcDifferenceForNonPrivateMembers(members: (ProtoBuf.Class) -> List<MessageLite>): Collection<String> { + val oldMembers = members(oldProto).filterNot { it.isPrivate } + val newMembers = members(newProto).filterNot { it.isPrivate } + return calcDifferenceForMembers(oldMembers, newMembers) + } + for (kind in diff) { when (kind!!) { - ProtoCompareGenerated.ProtoBufClassKind.COMPANION_OBJECT_NAME -> { + ProtoBufClassKind.COMPANION_OBJECT_NAME -> { if (oldProto.hasCompanionObjectName()) oldProto.companionObjectName.oldToNames() if (newProto.hasCompanionObjectName()) newProto.companionObjectName.newToNames() } - ProtoCompareGenerated.ProtoBufClassKind.NESTED_CLASS_NAME_LIST -> + ProtoBufClassKind.NESTED_CLASS_NAME_LIST -> names.addAll(calcDifferenceForNames(oldProto.nestedClassNameList, newProto.nestedClassNameList)) - ProtoCompareGenerated.ProtoBufClassKind.MEMBER_LIST -> { - val oldMembers = oldProto.memberList.filter { !it.isPrivate } - val newMembers = newProto.memberList.filter { !it.isPrivate } - names.addAll(calcDifferenceForMembers(oldMembers, newMembers)) - } - ProtoCompareGenerated.ProtoBufClassKind.ENUM_ENTRY_LIST -> + ProtoBufClassKind.CONSTRUCTOR_LIST -> + names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getConstructorList)) + ProtoBufClassKind.FUNCTION_LIST -> + names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getFunctionList)) + ProtoBufClassKind.PROPERTY_LIST -> + names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getPropertyList)) + ProtoBufClassKind.MEMBER_LIST -> + names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Class::getMemberList)) + ProtoBufClassKind.ENUM_ENTRY_LIST -> names.addAll(calcDifferenceForNames(oldProto.enumEntryList, newProto.enumEntryList)) - ProtoCompareGenerated.ProtoBufClassKind.PRIMARY_CONSTRUCTOR -> + ProtoBufClassKind.PRIMARY_CONSTRUCTOR -> if (areNonPrivatePrimaryConstructorsDifferent()) { names.add(CONSTRUCTOR) } - ProtoCompareGenerated.ProtoBufClassKind.SECONDARY_CONSTRUCTOR_LIST -> + ProtoBufClassKind.SECONDARY_CONSTRUCTOR_LIST -> if (areNonPrivateSecondaryConstructorsDifferent()) { names.add(CONSTRUCTOR) } - ProtoCompareGenerated.ProtoBufClassKind.FLAGS, - ProtoCompareGenerated.ProtoBufClassKind.FQ_NAME, - ProtoCompareGenerated.ProtoBufClassKind.TYPE_PARAMETER_LIST, - ProtoCompareGenerated.ProtoBufClassKind.SUPERTYPE_LIST, - ProtoCompareGenerated.ProtoBufClassKind.CLASS_ANNOTATION_LIST -> + ProtoBufClassKind.FLAGS, + ProtoBufClassKind.FQ_NAME, + ProtoBufClassKind.TYPE_PARAMETER_LIST, + ProtoBufClassKind.SUPERTYPE_LIST, + ProtoBufClassKind.CLASS_ANNOTATION_LIST -> throw IllegalArgumentException("Unexpected kind: $kind") else -> throw IllegalArgumentException("Unsupported kind: $kind") @@ -237,14 +285,27 @@ private class DifferenceCalculatorForPackageFacade(oldData: ProtoMapValue, newDa private fun getChangedMembersNames(): Set<String> { val names = hashSetOf<String>() + fun calcDifferenceForNonPrivateMembers(members: (ProtoBuf.Package) -> List<MessageLite>): Collection<String> { + val oldMembers = members(oldProto).filterNot { it.isPrivate } + val newMembers = members(newProto).filterNot { it.isPrivate } + return calcDifferenceForMembers(oldMembers, newMembers) + } + for (kind in diff) { when (kind!!) { - ProtoCompareGenerated.ProtoBufPackageKind.MEMBER_LIST -> - names.addAll(calcDifferenceForMembers(oldProto.memberList.filter { !it.isPrivate }, newProto.memberList.filter { !it.isPrivate })) + ProtoBufPackageKind.CONSTRUCTOR_LIST -> + names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Package::getConstructorList)) + ProtoBufPackageKind.FUNCTION_LIST -> + names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Package::getFunctionList)) + ProtoBufPackageKind.PROPERTY_LIST -> + names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Package::getPropertyList)) + ProtoBufPackageKind.MEMBER_LIST -> + names.addAll(calcDifferenceForNonPrivateMembers(ProtoBuf.Package::getMemberList)) else -> throw IllegalArgumentException("Unsupported kind: $kind") } } + return names } }
074f83c80b2fcb400e4e7102a882a0bcb4536e7e
hbase
HBASE-11671 TestEndToEndSplitTransaction fails on- master (Mikhail Antonov)--
c
https://github.com/apache/hbase
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestEndToEndSplitTransaction.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestEndToEndSplitTransaction.java index 5cad147faf82..8de605de29d0 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestEndToEndSplitTransaction.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestEndToEndSplitTransaction.java @@ -45,7 +45,6 @@ import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.Stoppable; import org.apache.hadoop.hbase.client.Get; -import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HConnection; import org.apache.hadoop.hbase.client.HConnectionManager; import org.apache.hadoop.hbase.client.HTable; @@ -58,6 +57,7 @@ import org.apache.hadoop.hbase.protobuf.RequestConverter; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest; +import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ConfigUtil; import org.apache.hadoop.hbase.util.Pair; @@ -126,7 +126,15 @@ public void testMasterOpsWhileSplitting() throws Exception { // 3. finish phase II // note that this replicates some code from SplitTransaction // 2nd daughter first - server.postOpenDeployTasks(regions.getSecond()); + if (split.useZKForAssignment) { + server.postOpenDeployTasks(regions.getSecond()); + } else { + server.reportRegionStateTransition( + RegionServerStatusProtos.RegionStateTransition.TransitionCode.SPLIT, + region.getRegionInfo(), regions.getFirst().getRegionInfo(), + regions.getSecond().getRegionInfo()); + } + // Add to online regions server.addToOnlineRegions(regions.getSecond()); // THIS is the crucial point: @@ -136,7 +144,9 @@ public void testMasterOpsWhileSplitting() throws Exception { assertTrue(test(con, tableName, lastRow, server)); // first daughter second - server.postOpenDeployTasks(regions.getFirst()); + if (split.useZKForAssignment) { + server.postOpenDeployTasks(regions.getFirst()); + } // Add to online regions server.addToOnlineRegions(regions.getFirst()); assertTrue(test(con, tableName, firstRow, server));
250ac825075785eef0c544670133eb590aaf1168
orientdb
Fixed problem with LET and context variables--
c
https://github.com/orientechnologies/orientdb
diff --git a/src/main/java/com/orientechnologies/orient/etl/OAbstractETLComponent.java b/src/main/java/com/orientechnologies/orient/etl/OAbstractETLComponent.java index 3479d210f96..35bb3a519ff 100644 --- a/src/main/java/com/orientechnologies/orient/etl/OAbstractETLComponent.java +++ b/src/main/java/com/orientechnologies/orient/etl/OAbstractETLComponent.java @@ -103,7 +103,7 @@ protected Object resolve(final Object iContent) { Object value = null; if (iContent instanceof String) { - if (((String) iContent).startsWith("$")) + if (((String) iContent).startsWith("$") && !((String) iContent).startsWith(OSystemVariableResolver.VAR_BEGIN)) value = context.getVariable(iContent.toString()); else value = OVariableParser.resolveVariables((String) iContent, OSystemVariableResolver.VAR_BEGIN, diff --git a/src/main/java/com/orientechnologies/orient/etl/block/OLetBlock.java b/src/main/java/com/orientechnologies/orient/etl/block/OLetBlock.java index 37bb615cf11..e81888aba56 100644 --- a/src/main/java/com/orientechnologies/orient/etl/block/OLetBlock.java +++ b/src/main/java/com/orientechnologies/orient/etl/block/OLetBlock.java @@ -26,18 +26,27 @@ public class OLetBlock extends OAbstractBlock { protected String name; protected OSQLFilter expression; + protected Object value; @Override public ODocument getConfiguration() { return new ODocument().fromJSON("{parameters:[{name:{optional:false,description:'Variable name'}}," - + "{value:{optional:false,description:'Variable value'}}]}"); + + "{value:{optional:true,description:'Variable value'}}" + + "{expression:{optional:true,description:'Expression to evaluate'}}" + "]}"); } @Override - public void configure(OETLProcessor iProcessor, final ODocument iConfiguration, OBasicCommandContext iContext) { + public void configure(OETLProcessor iProcessor, final ODocument iConfiguration, final OBasicCommandContext iContext) { super.configure(iProcessor, iConfiguration, iContext); + name = iConfiguration.field("name"); - expression = new OSQLFilter((String) iConfiguration.field("value"), iContext, null); + if (iConfiguration.containsField("value")) { + value = iConfiguration.field("value"); + } else + expression = new OSQLFilter((String) iConfiguration.field("expression"), iContext, null); + + if (value == null && expression == null) + throw new IllegalArgumentException("'value' or 'expression' parameter are mandatory in Let Transformer"); } @Override @@ -47,6 +56,9 @@ public String getName() { @Override public void executeBlock() { - context.setVariable(name, expression.evaluate(null, null, context)); + if (expression != null) + context.setVariable(name, expression.evaluate(null, null, context)); + else + context.setVariable(name, resolve(value)); } } diff --git a/src/main/resources/config-dbpedia.json b/src/main/resources/config-dbpedia.json index c122848a1f5..217d8f313cb 100644 --- a/src/main/resources/config-dbpedia.json +++ b/src/main/resources/config-dbpedia.json @@ -6,8 +6,8 @@ parallel: true }, begin: [ - { let: { name: "$filePath", value: "$fileDirectory.append( $fileName )"} }, - { let: { name: "$className", value: "$fileName.substring( 0, $fileName.indexOf('.') )"} } + { let: { name: "$filePath", expression: "$fileDirectory.append( $fileName )"} }, + { let: { name: "$className", expression: "$fileName.substring( 0, $fileName.indexOf('.') )"} } ], source : { file: { path: "$filePath", lock : true }
614faccf1d353c3b4835e6df0e6902839d54b5f6
hadoop
YARN-1910. Fixed a race condition in TestAMRMTokens- that causes the test to fail more often on Windows. Contributed by Xuan Gong.- svn merge --ignore-ancestry -c 1586192 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1586193 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 2abb35dfa9b02..188a80035ac85 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -79,6 +79,9 @@ Release 2.4.1 - UNRELEASED YARN-1908. Fixed DistributedShell to not fail in secure clusters. (Vinod Kumar Vavilapalli and Jian He via vinodkv) + YARN-1910. Fixed a race condition in TestAMRMTokens that causes the test to + fail more often on Windows. (Xuan Gong via vinodkv) + Release 2.4.0 - 2014-04-07 INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java index aa894c5f6a920..64602bd888e27 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java @@ -48,6 +48,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MyContainerManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; +import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptContainerFinishedEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; @@ -63,6 +64,7 @@ public class TestAMRMTokens { private static final Log LOG = LogFactory.getLog(TestAMRMTokens.class); private final Configuration conf; + private static final int maxWaitAttempts = 50; @Parameters public static Collection<Object[]> configs() { @@ -153,6 +155,16 @@ public void testTokenExpiry() throws Exception { new RMAppAttemptContainerFinishedEvent(applicationAttemptId, containerStatus)); + // Make sure the RMAppAttempt is at Finished State. + // Both AMRMToken and ClientToAMToken have been removed. + int count = 0; + while (attempt.getState() != RMAppAttemptState.FINISHED + && count < maxWaitAttempts) { + Thread.sleep(100); + count++; + } + Assert.assertTrue(attempt.getState() == RMAppAttemptState.FINISHED); + // Now simulate trying to allocate. RPC call itself should throw auth // exception. rpc.stopProxy(rmClient, conf); // To avoid using cached client
e477c143bca83b8ec8e10c65a0e8ef526e24482e
hbase
HBASE-15354 Use same criteria for clearing meta- cache for all operations (addendum) (Ashu Pachauri)--
p
https://github.com/apache/hbase
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestMetaCache.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestMetaCache.java index 5738be9045ac..23b9eedc549a 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestMetaCache.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestMetaCache.java @@ -19,8 +19,6 @@ import com.google.protobuf.RpcController; import com.google.protobuf.ServiceException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; @@ -34,6 +32,7 @@ import org.apache.hadoop.hbase.testclassification.ClientTests; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.util.Bytes; +import org.apache.hadoop.hbase.util.JVMClusterUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -45,17 +44,19 @@ import java.util.ArrayList; import java.util.List; +import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; @Category({MediumTests.class, ClientTests.class}) public class TestMetaCache { - private static final Log LOG = LogFactory.getLog(TestMetaCache.class); private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private static final TableName TABLE_NAME = TableName.valueOf("test_table"); private static final byte[] FAMILY = Bytes.toBytes("fam1"); private static final byte[] QUALIFIER = Bytes.toBytes("qual"); private ConnectionImplementation conn; + private HRegionServer badRS; /** * @throws java.lang.Exception @@ -64,8 +65,9 @@ public class TestMetaCache { public static void setUpBeforeClass() throws Exception { Configuration conf = TEST_UTIL.getConfiguration(); conf.set("hbase.client.retries.number", "1"); - conf.setStrings(HConstants.REGION_SERVER_IMPL, RegionServerWithFakeRpcServices.class.getName()); TEST_UTIL.startMiniCluster(1); + TEST_UTIL.getHBaseCluster().waitForActiveAndReadyMaster(); + TEST_UTIL.waitUntilAllRegionsAssigned(TABLE_NAME.META_TABLE_NAME); } @@ -82,8 +84,21 @@ public static void tearDownAfterClass() throws Exception { */ @Before public void setup() throws Exception { - conn = (ConnectionImplementation)ConnectionFactory.createConnection( - TEST_UTIL.getConfiguration()); + MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); + + cluster.getConfiguration().setStrings(HConstants.REGION_SERVER_IMPL, + RegionServerWithFakeRpcServices.class.getName()); + JVMClusterUtil.RegionServerThread rsThread = cluster.startRegionServer(); + rsThread.waitForServerOnline(); + badRS = rsThread.getRegionServer(); + assertTrue(badRS.getRSRpcServices() instanceof FakeRSRpcServices); + cluster.getConfiguration().setStrings(HConstants.REGION_SERVER_IMPL, + HRegionServer.class.getName()); + + assertEquals(2, cluster.getRegionServerThreads().size()); + + conn = (ConnectionImplementation) ConnectionFactory.createConnection( + TEST_UTIL.getConfiguration()); HTableDescriptor table = new HTableDescriptor(TABLE_NAME); HColumnDescriptor fam = new HColumnDescriptor(FAMILY); fam.setMaxVersions(2); @@ -105,7 +120,7 @@ public void tearDown() throws Exception { @Test public void testPreserveMetaCacheOnException() throws Exception { Table table = conn.getTable(TABLE_NAME); - byte [] row = HBaseTestingUtility.KEYS[2]; + byte[] row = badRS.getOnlineRegions().get(0).getRegionInfo().getStartKey(); Put put = new Put(row); put.addColumn(FAMILY, QUALIFIER, Bytes.toBytes(10)); @@ -151,19 +166,19 @@ public void testPreserveMetaCacheOnException() throws Exception { public static List<Throwable> metaCachePreservingExceptions() { return new ArrayList<Throwable>() {{ - add(new RegionOpeningException(" ")); - add(new RegionTooBusyException()); - add(new ThrottlingException(" ")); - add(new MultiActionResultTooLarge(" ")); - add(new RetryImmediatelyException(" ")); - add(new CallQueueTooBigException()); + add(new RegionOpeningException(" ")); + add(new RegionTooBusyException()); + add(new ThrottlingException(" ")); + add(new MultiActionResultTooLarge(" ")); + add(new RetryImmediatelyException(" ")); + add(new CallQueueTooBigException()); }}; } protected static class RegionServerWithFakeRpcServices extends HRegionServer { public RegionServerWithFakeRpcServices(Configuration conf, CoordinatedStateManager cp) - throws IOException, InterruptedException { + throws IOException, InterruptedException { super(conf, cp); } @@ -185,7 +200,7 @@ public FakeRSRpcServices(HRegionServer rs) throws IOException { @Override public GetResponse get(final RpcController controller, - final ClientProtos.GetRequest request) throws ServiceException { + final ClientProtos.GetRequest request) throws ServiceException { throwSomeExceptions(); return super.get(controller, request); } @@ -224,8 +239,8 @@ private void throwSomeExceptions() throws ServiceException { // single Gets. expCount++; Throwable t = metaCachePreservingExceptions.get( - expCount % metaCachePreservingExceptions.size()); + expCount % metaCachePreservingExceptions.size()); throw new ServiceException(t); } } -} +} \ No newline at end of file
990ddf5896045704ec43ac0e5a3e2df7022fed12
drools
JBRULES-1641: ForEach node - initial core- implementation of a for each node JBRULES-1551: Workflow human tasks - human- task node with swimlane integration--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@20429 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/drools/xml/ProcessSemanticModule.java b/drools-compiler/src/main/java/org/drools/xml/ProcessSemanticModule.java index f9d4407309d..4969dd5a685 100644 --- a/drools-compiler/src/main/java/org/drools/xml/ProcessSemanticModule.java +++ b/drools-compiler/src/main/java/org/drools/xml/ProcessSemanticModule.java @@ -6,6 +6,7 @@ import org.drools.xml.processes.ConstraintHandler; import org.drools.xml.processes.EndNodeHandler; import org.drools.xml.processes.GlobalHandler; +import org.drools.xml.processes.HumanTaskNodeHandler; import org.drools.xml.processes.ImportHandler; import org.drools.xml.processes.InPortHandler; import org.drools.xml.processes.JoinNodeHandler; @@ -18,6 +19,7 @@ import org.drools.xml.processes.SplitNodeHandler; import org.drools.xml.processes.StartNodeHandler; import org.drools.xml.processes.SubProcessNodeHandler; +import org.drools.xml.processes.SwimlaneHandler; import org.drools.xml.processes.TimerNodeHandler; import org.drools.xml.processes.TypeHandler; import org.drools.xml.processes.ValueHandler; @@ -51,6 +53,8 @@ public ProcessSemanticModule() { new MilestoneNodeHandler() ); addHandler( "timer", new TimerNodeHandler() ); + addHandler( "humanTask", + new HumanTaskNodeHandler() ); addHandler( "composite", new CompositeNodeHandler() ); addHandler( "connection", @@ -61,6 +65,8 @@ public ProcessSemanticModule() { new GlobalHandler() ); addHandler( "variable", new VariableHandler() ); + addHandler( "swimlane", + new SwimlaneHandler() ); addHandler( "type", new TypeHandler() ); addHandler( "value", diff --git a/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java b/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java index 12bccde50e9..bd4272c12b6 100644 --- a/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java +++ b/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java @@ -1,9 +1,12 @@ package org.drools.xml; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; +import org.drools.process.core.context.swimlane.Swimlane; +import org.drools.process.core.context.swimlane.SwimlaneContext; import org.drools.process.core.context.variable.Variable; import org.drools.process.core.context.variable.VariableScope; import org.drools.process.core.datatype.DataType; @@ -78,6 +81,10 @@ private void visitHeader(WorkflowProcess process, StringBuffer xmlDump, boolean if (variableScope != null) { visitVariables(variableScope.getVariables(), xmlDump); } + SwimlaneContext swimlaneContext = (SwimlaneContext) process.getDefaultContext(SwimlaneContext.SWIMLANE_SCOPE); + if (swimlaneContext != null) { + visitSwimlanes(swimlaneContext.getSwimlanes(), xmlDump); + } xmlDump.append(" </header>" + EOL + EOL); } @@ -117,6 +124,16 @@ private void visitVariables(List<Variable> variables, StringBuffer xmlDump) { } } + private void visitSwimlanes(Collection<Swimlane> swimlanes, StringBuffer xmlDump) { + if (swimlanes != null && swimlanes.size() > 0) { + xmlDump.append(" <swimlanes>" + EOL); + for (Swimlane swimlane: swimlanes) { + xmlDump.append(" <swimlane name=\"" + swimlane.getName() + "\" />" + EOL); + } + xmlDump.append(" </swimlanes>" + EOL); + } + } + private void visitDataType(DataType dataType, StringBuffer xmlDump) { xmlDump.append(" <type name=\"" + dataType.getClass().getName() + "\" />" + EOL); } diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/HumanTaskNodeHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/HumanTaskNodeHandler.java new file mode 100644 index 00000000000..0f0cd843707 --- /dev/null +++ b/drools-compiler/src/main/java/org/drools/xml/processes/HumanTaskNodeHandler.java @@ -0,0 +1,53 @@ +package org.drools.xml.processes; + +import org.drools.process.core.Work; +import org.drools.workflow.core.Node; +import org.drools.workflow.core.node.HumanTaskNode; +import org.drools.workflow.core.node.WorkItemNode; +import org.drools.xml.ExtensibleXmlParser; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +public class HumanTaskNodeHandler extends WorkItemNodeHandler { + + public void handleNode(final Node node, final Element element, final String uri, + final String localName, final ExtensibleXmlParser parser) + throws SAXException { + super.handleNode(node, element, uri, localName, parser); + HumanTaskNode humanTaskNode = (HumanTaskNode) node; + final String swimlane = element.getAttribute("swimlane"); + if (swimlane != null && !"".equals(swimlane)) { + humanTaskNode.setSwimlane(swimlane); + } + } + + protected Node createNode() { + return new HumanTaskNode(); + } + + public Class generateNodeFor() { + return HumanTaskNode.class; + } + + public void writeNode(Node node, StringBuffer xmlDump, boolean includeMeta) { + WorkItemNode workItemNode = (WorkItemNode) node; + writeNode("humanTask", workItemNode, xmlDump, includeMeta); + visitParameters(workItemNode, xmlDump); + xmlDump.append(">" + EOL); + Work work = workItemNode.getWork(); + visitWork(work, xmlDump, includeMeta); + visitInMappings(workItemNode.getInMappings(), xmlDump); + visitOutMappings(workItemNode.getOutMappings(), xmlDump); + endNode("humanTask", xmlDump); + } + + protected void visitParameters(WorkItemNode workItemNode, StringBuffer xmlDump) { + super.visitParameters(workItemNode, xmlDump); + HumanTaskNode humanTaskNode = (HumanTaskNode) workItemNode; + String swimlane = humanTaskNode.getSwimlane(); + if (swimlane != null) { + xmlDump.append("swimlane=\"" + swimlane + "\" "); + } + } + +} diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/SwimlaneHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/SwimlaneHandler.java new file mode 100644 index 00000000000..9ad5da8d546 --- /dev/null +++ b/drools-compiler/src/main/java/org/drools/xml/processes/SwimlaneHandler.java @@ -0,0 +1,67 @@ +package org.drools.xml.processes; + +import java.util.HashSet; + +import org.drools.process.core.Process; +import org.drools.process.core.context.swimlane.Swimlane; +import org.drools.process.core.context.swimlane.SwimlaneContext; +import org.drools.workflow.core.impl.WorkflowProcessImpl; +import org.drools.xml.BaseAbstractHandler; +import org.drools.xml.ExtensibleXmlParser; +import org.drools.xml.Handler; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class SwimlaneHandler extends BaseAbstractHandler + implements + Handler { + public SwimlaneHandler() { + if ( (this.validParents == null) && (this.validPeers == null) ) { + this.validParents = new HashSet(); + this.validParents.add( Process.class ); + + this.validPeers = new HashSet(); + this.validPeers.add( null ); + + this.allowNesting = false; + } + } + + + + public Object start(final String uri, + final String localName, + final Attributes attrs, + final ExtensibleXmlParser parser) throws SAXException { + parser.startElementBuilder( localName, + attrs ); + WorkflowProcessImpl process = (WorkflowProcessImpl) parser.getParent(); + final String name = attrs.getValue("name"); + emptyAttributeCheck(localName, "name", name, parser); + + SwimlaneContext swimlaneContext = (SwimlaneContext) + process.getDefaultContext(SwimlaneContext.SWIMLANE_SCOPE); + if (swimlaneContext != null) { + Swimlane swimlane = new Swimlane(name); + swimlaneContext.addSwimlane(swimlane); + } else { + throw new SAXParseException( + "Could not find default swimlane context.", parser.getLocator()); + } + + return null; + } + + public Object end(final String uri, + final String localName, + final ExtensibleXmlParser parser) throws SAXException { + parser.endElementBuilder(); + return null; + } + + public Class generateNodeFor() { + return Swimlane.class; + } + +} diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java index 91ad673494c..f4628f3df5a 100644 --- a/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java +++ b/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java @@ -32,48 +32,58 @@ public Class generateNodeFor() { public void writeNode(Node node, StringBuffer xmlDump, boolean includeMeta) { WorkItemNode workItemNode = (WorkItemNode) node; writeNode("workItem", workItemNode, xmlDump, includeMeta); - if (!workItemNode.isWaitForCompletion()) { - xmlDump.append("waitForCompletion=\"false\" "); - } + visitParameters(workItemNode, xmlDump); xmlDump.append(">" + EOL); Work work = workItemNode.getWork(); - if (work != null) { - visitWork(work, xmlDump, includeMeta); + visitWork(work, xmlDump, includeMeta); + visitInMappings(workItemNode.getInMappings(), xmlDump); + visitOutMappings(workItemNode.getOutMappings(), xmlDump); + endNode("workItem", xmlDump); + } + + protected void visitParameters(WorkItemNode workItemNode, StringBuffer xmlDump) { + if (!workItemNode.isWaitForCompletion()) { + xmlDump.append("waitForCompletion=\"false\" "); } - Map<String, String> inMappings = workItemNode.getInMappings(); + } + + protected void visitInMappings(Map<String, String> inMappings, StringBuffer xmlDump) { for (Map.Entry<String, String> inMapping: inMappings.entrySet()) { xmlDump.append( " <mapping type=\"in\" " + "from=\"" + inMapping.getValue() + "\" " + "to=\"" + inMapping.getKey() + "\" />" + EOL); } - Map<String, String> outMappings = workItemNode.getOutMappings(); + } + + protected void visitOutMappings(Map<String, String> outMappings, StringBuffer xmlDump) { for (Map.Entry<String, String> outMapping: outMappings.entrySet()) { xmlDump.append( " <mapping type=\"out\" " + "from=\"" + outMapping.getKey() + "\" " + "to=\"" + outMapping.getValue() + "\" />" + EOL); } - endNode("workItem", xmlDump); } - private void visitWork(Work work, StringBuffer xmlDump, boolean includeMeta) { - xmlDump.append(" <work name=\"" + work.getName() + "\" >" + EOL); - for (ParameterDefinition paramDefinition: work.getParameterDefinitions()) { - if (paramDefinition == null) { - throw new IllegalArgumentException( - "Could not find parameter definition " + paramDefinition.getName() - + " for work " + work.getName()); - } - xmlDump.append(" <parameter name=\"" + paramDefinition.getName() + "\" " + - "type=\"" + paramDefinition.getType().getClass().getName() + "\" "); - Object value = work.getParameter(paramDefinition.getName()); - if (value == null) { - xmlDump.append("/>" + EOL); - } else { - xmlDump.append(">" + value + "</parameter>" + EOL); + protected void visitWork(Work work, StringBuffer xmlDump, boolean includeMeta) { + if (work != null) { + xmlDump.append(" <work name=\"" + work.getName() + "\" >" + EOL); + for (ParameterDefinition paramDefinition: work.getParameterDefinitions()) { + if (paramDefinition == null) { + throw new IllegalArgumentException( + "Could not find parameter definition " + paramDefinition.getName() + + " for work " + work.getName()); + } + xmlDump.append(" <parameter name=\"" + paramDefinition.getName() + "\" " + + "type=\"" + paramDefinition.getType().getClass().getName() + "\" "); + Object value = work.getParameter(paramDefinition.getName()); + if (value == null) { + xmlDump.append("/>" + EOL); + } else { + xmlDump.append(">" + value + "</parameter>" + EOL); + } } + xmlDump.append(" </work>" + EOL); } - xmlDump.append(" </work>" + EOL); } } diff --git a/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd b/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd index 65a1fd188ce..a8fab793d0e 100644 --- a/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd +++ b/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd @@ -21,6 +21,7 @@ <xs:element ref="drools:imports"/> <xs:element ref="drools:globals"/> <xs:element ref="drools:variables"/> + <xs:element ref="drools:swimlanes"/> </xs:choice> </xs:complexType> </xs:element> @@ -77,6 +78,18 @@ </xs:simpleContent> </xs:complexType> </xs:element> + <xs:element name="swimlanes"> + <xs:complexType> + <xs:sequence minOccurs="0" maxOccurs="unbounded"> + <xs:element ref="drools:swimlane"/> + </xs:sequence> + </xs:complexType> + </xs:element> + <xs:element name="swimlane"> + <xs:complexType> + <xs:attribute name="name" type="xs:string" use="required"/> + </xs:complexType> + </xs:element> <xs:element name="nodes"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> @@ -90,6 +103,7 @@ <xs:element ref="drools:subProcess"/> <xs:element ref="drools:workItem"/> <xs:element ref="drools:timer"/> + <xs:element ref="drools:humanTask"/> <xs:element ref="drools:composite"/> </xs:choice> </xs:complexType> @@ -268,6 +282,22 @@ <xs:attribute name="period" type="xs:string"/> </xs:complexType> </xs:element> + <xs:element name="humanTask"> + <xs:complexType> + <xs:choice minOccurs="0" maxOccurs="unbounded"> + <xs:element ref="drools:work"/> + <xs:element ref="drools:mapping"/> + </xs:choice> + <xs:attribute name="id" type="xs:string" use="required"/> + <xs:attribute name="name" type="xs:string"/> + <xs:attribute name="x" type="xs:string"/> + <xs:attribute name="y" type="xs:string"/> + <xs:attribute name="width" type="xs:string"/> + <xs:attribute name="height" type="xs:string"/> + <xs:attribute name="waitForCompletion" type="xs:string"/> + <xs:attribute name="swimlane" type="xs:string"/> + </xs:complexType> + </xs:element> <xs:element name="composite"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/ProcessHumanTaskTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/ProcessHumanTaskTest.java new file mode 100644 index 00000000000..3cd48fbd66b --- /dev/null +++ b/drools-compiler/src/test/java/org/drools/integrationtests/ProcessHumanTaskTest.java @@ -0,0 +1,150 @@ +package org.drools.integrationtests; + +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.drools.RuleBase; +import org.drools.RuleBaseFactory; +import org.drools.WorkingMemory; +import org.drools.compiler.PackageBuilder; +import org.drools.process.instance.ProcessInstance; +import org.drools.process.instance.WorkItem; +import org.drools.process.instance.WorkItemHandler; +import org.drools.process.instance.WorkItemManager; +import org.drools.rule.Package; + +import junit.framework.TestCase; + +public class ProcessHumanTaskTest extends TestCase { + + public void testHumanTask() { + PackageBuilder builder = new PackageBuilder(); + Reader source = new StringReader( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<process xmlns=\"http://drools.org/drools-4.0/process\"\n" + + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + + " xs:schemaLocation=\"http://drools.org/drools-4.0/process drools-processes-4.0.xsd\"\n" + + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.humantask\" package-name=\"org.drools\" version=\"1\" >\n" + + "\n" + + " <header>\n" + + " </header>\n" + + "\n" + + " <nodes>\n" + + " <start id=\"1\" name=\"Start\" />\n" + + " <humanTask id=\"2\" name=\"HumanTask\" >\n" + + " <work name=\"Human Task\" >\n" + + " <parameter name=\"ActorId\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >John Doe</parameter>\n" + + " <parameter name=\"TaskName\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >Do something</parameter>\n" + + " <parameter name=\"Priority\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " <parameter name=\"Comment\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " </work>\n" + + " </humanTask>\n" + + " <end id=\"3\" name=\"End\" />\n" + + " </nodes>\n" + + "\n" + + " <connections>\n" + + " <connection from=\"1\" to=\"2\" />\n" + + " <connection from=\"2\" to=\"3\" />\n" + + " </connections>\n" + + "\n" + + "</process>"); + builder.addRuleFlow(source); + Package pkg = builder.getPackage(); + RuleBase ruleBase = RuleBaseFactory.newRuleBase(); + ruleBase.addPackage( pkg ); + WorkingMemory workingMemory = ruleBase.newStatefulSession(); + TestWorkItemHandler handler = new TestWorkItemHandler(); + workingMemory.getWorkItemManager().registerWorkItemHandler("Human Task", handler); + ProcessInstance processInstance = + workingMemory.startProcess("org.drools.humantask"); + assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState()); + WorkItem workItem = handler.getWorkItem(); + assertNotNull(workItem); + workingMemory.getWorkItemManager().completeWorkItem(workItem.getId(), null); + assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState()); + } + + public void testSwimlane() { + PackageBuilder builder = new PackageBuilder(); + Reader source = new StringReader( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<process xmlns=\"http://drools.org/drools-4.0/process\"\n" + + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + + " xs:schemaLocation=\"http://drools.org/drools-4.0/process drools-processes-4.0.xsd\"\n" + + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.humantask\" package-name=\"org.drools\" version=\"1\" >\n" + + "\n" + + " <header>\n" + + " <swimlanes>\n" + + " <swimlane name=\"actor1\" />\n" + + " </swimlanes>\n" + + " </header>\n" + + "\n" + + " <nodes>\n" + + " <start id=\"1\" name=\"Start\" />\n" + + " <humanTask id=\"2\" name=\"HumanTask\" swimlane=\"actor1\" >\n" + + " <work name=\"Human Task\" >\n" + + " <parameter name=\"ActorId\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >John Doe</parameter>\n" + + " <parameter name=\"TaskName\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >Do something</parameter>\n" + + " <parameter name=\"Priority\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " <parameter name=\"Comment\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " </work>\n" + + " </humanTask>\n" + + " <humanTask id=\"3\" name=\"HumanTask\" swimlane=\"actor1\" >\n" + + " <work name=\"Human Task\" >\n" + + " <parameter name=\"ActorId\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " <parameter name=\"TaskName\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >Do something else</parameter>\n" + + " <parameter name=\"Priority\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " <parameter name=\"Comment\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " </work>\n" + + " </humanTask>\n" + + " <end id=\"4\" name=\"End\" />\n" + + " </nodes>\n" + + "\n" + + " <connections>\n" + + " <connection from=\"1\" to=\"2\" />\n" + + " <connection from=\"2\" to=\"3\" />\n" + + " <connection from=\"3\" to=\"4\" />\n" + + " </connections>\n" + + "\n" + + "</process>"); + builder.addRuleFlow(source); + Package pkg = builder.getPackage(); + RuleBase ruleBase = RuleBaseFactory.newRuleBase(); + ruleBase.addPackage( pkg ); + WorkingMemory workingMemory = ruleBase.newStatefulSession(); + TestWorkItemHandler handler = new TestWorkItemHandler(); + workingMemory.getWorkItemManager().registerWorkItemHandler("Human Task", handler); + ProcessInstance processInstance = + workingMemory.startProcess("org.drools.humantask"); + assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState()); + WorkItem workItem = handler.getWorkItem(); + assertNotNull(workItem); + assertEquals("Do something", workItem.getParameter("TaskName")); + assertEquals("John Doe", workItem.getParameter("ActorId")); + Map<String, Object> results = new HashMap<String, Object>(); + results.put("ActorId", "Jane Doe"); + workingMemory.getWorkItemManager().completeWorkItem(workItem.getId(), results); + workItem = handler.getWorkItem(); + assertNotNull(workItem); + assertEquals("Do something else", workItem.getParameter("TaskName")); + assertEquals("Jane Doe", workItem.getParameter("ActorId")); + workingMemory.getWorkItemManager().completeWorkItem(workItem.getId(), null); + assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState()); + } + + private static class TestWorkItemHandler implements WorkItemHandler { + private WorkItem workItem; + public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { + this.workItem = workItem; + } + public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { + } + public WorkItem getWorkItem() { + return workItem; + } + } +} diff --git a/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java b/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java index 63dc64f742b..c1e4e01c26a 100644 --- a/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java +++ b/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java @@ -13,6 +13,7 @@ import org.drools.compiler.PackageBuilderConfiguration; import org.drools.process.core.ParameterDefinition; import org.drools.process.core.Work; +import org.drools.process.core.context.swimlane.Swimlane; import org.drools.process.core.context.variable.Variable; import org.drools.process.core.datatype.impl.type.IntegerDataType; import org.drools.process.core.datatype.impl.type.StringDataType; @@ -28,6 +29,7 @@ import org.drools.workflow.core.impl.DroolsConsequenceAction; import org.drools.workflow.core.node.ActionNode; import org.drools.workflow.core.node.EndNode; +import org.drools.workflow.core.node.HumanTaskNode; import org.drools.workflow.core.node.Join; import org.drools.workflow.core.node.MilestoneNode; import org.drools.workflow.core.node.RuleSetNode; @@ -60,6 +62,7 @@ public void addNode(Node node) { process.addNode(new SubProcessNode()); process.addNode(new WorkItemNode()); process.addNode(new TimerNode()); + process.addNode(new HumanTaskNode()); String xml = XmlRuleFlowProcessDumper.INSTANCE.dump(process, false); if (xml == null) { @@ -76,7 +79,7 @@ public void addNode(Node node) { throw new IllegalArgumentException("Failed to reload process!"); } - assertEquals(10, process.getNodes().length); + assertEquals(11, process.getNodes().length); // System.out.println("************************************"); @@ -124,6 +127,9 @@ public void addNode(Node node) { variables.add(variable); process.getVariableScope().setVariables(variables); + process.getSwimlaneContext().addSwimlane(new Swimlane("actor1")); + process.getSwimlaneContext().addSwimlane(new Swimlane("actor2")); + StartNode startNode = new StartNode(); startNode.setName("start"); startNode.setMetaData("x", 1); @@ -187,7 +193,6 @@ public void addNode(Node node) { process.addNode(join); new ConnectionImpl(actionNode, Node.CONNECTION_DEFAULT_TYPE, join, Node.CONNECTION_DEFAULT_TYPE); new ConnectionImpl(ruleSetNode, Node.CONNECTION_DEFAULT_TYPE, join, Node.CONNECTION_DEFAULT_TYPE); - MilestoneNode milestone = new MilestoneNode(); milestone.setName("milestone"); @@ -234,6 +239,24 @@ public void addNode(Node node) { connection = new ConnectionImpl(subProcess, Node.CONNECTION_DEFAULT_TYPE, workItemNode, Node.CONNECTION_DEFAULT_TYPE); connection.setMetaData("bendpoints", "[]"); + HumanTaskNode humanTaskNode = new HumanTaskNode(); + work = humanTaskNode.getWork(); + parameterDefinitions = new HashSet<ParameterDefinition>(); + parameterDefinition = new ParameterDefinitionImpl("TaskName", new StringDataType()); + parameterDefinitions.add(parameterDefinition); + parameterDefinition = new ParameterDefinitionImpl("ActorId", new StringDataType()); + parameterDefinitions.add(parameterDefinition); + parameterDefinition = new ParameterDefinitionImpl("Priority", new StringDataType()); + parameterDefinitions.add(parameterDefinition); + parameterDefinition = new ParameterDefinitionImpl("Comment", new StringDataType()); + parameterDefinitions.add(parameterDefinition); + work.setParameterDefinitions(parameterDefinitions); + work.setParameter("TaskName", "Do something"); + work.setParameter("ActorId", "John Doe"); + workItemNode.setWaitForCompletion(false); + process.addNode(humanTaskNode); + connection = new ConnectionImpl(workItemNode, Node.CONNECTION_DEFAULT_TYPE, humanTaskNode, Node.CONNECTION_DEFAULT_TYPE); + TimerNode timerNode = new TimerNode(); timerNode.setName("timer"); timerNode.setMetaData("x", 1); @@ -245,7 +268,7 @@ public void addNode(Node node) { timer.setPeriod(1000); timerNode.setTimer(timer); process.addNode(timerNode); - new ConnectionImpl(workItemNode, Node.CONNECTION_DEFAULT_TYPE, timerNode, Node.CONNECTION_DEFAULT_TYPE); + new ConnectionImpl(humanTaskNode, Node.CONNECTION_DEFAULT_TYPE, timerNode, Node.CONNECTION_DEFAULT_TYPE); EndNode endNode = new EndNode(); endNode.setName("end"); @@ -270,7 +293,7 @@ public void addNode(Node node) { throw new IllegalArgumentException("Failed to reload process!"); } - assertEquals(10, process.getNodes().length); + assertEquals(11, process.getNodes().length); // System.out.println("************************************");
d5379b29a2e22e8d994d201fda5526e712f00c33
hadoop
YARN-2132. ZKRMStateStore.ZKAction-runWithRetries- doesn't log the exception it encounters. (Vamsee Yarlagadda via kasha)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1601066 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index c3785e01c95ed..db77633152dff 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -127,6 +127,9 @@ Release 2.5.0 - UNRELEASED YARN-2122. In AllocationFileLoaderService, the reloadThread should be created in init() and started in start(). (Robert Kanter via kasha) + YARN-2132. ZKRMStateStore.ZKAction#runWithRetries doesn't log the exception + it encounters. (Vamsee Yarlagadda via kasha) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java index c5016e1397a38..31c8885d4f2c9 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java @@ -998,13 +998,13 @@ T runWithRetries() throws Exception { throw new StoreFencedException(); } } catch (KeeperException ke) { + LOG.info("Exception while executing a ZK operation.", ke); if (shouldRetry(ke.code()) && ++retry < numRetries) { - LOG.info("Waiting for zookeeper to be connected, retry no. + " - + retry); + LOG.info("Retrying operation on ZK. Retry no. " + retry); Thread.sleep(zkRetryInterval); continue; } - LOG.debug("Error while doing ZK operation.", ke); + LOG.info("Maxed out ZK retries. Giving up!"); throw ke; } }
9e5a33c1b36cae7a7541251509bf032455838fdf
spring-framework
Add a ResourceResolver implementation for WebJars--Prior to this commit, WebJars users needed to use versioned links within-templates for WebJars resources, such as `/jquery/1.2.0/jquery.js`.-This can be rather cumbersome when updating libraries - all references-in templates need to be updated.--One could use version-less links in templates, but needed to add a-specific MVC Handler that uses webjars.org's webjar-locator library.-While this approach makes maintaing templates easier, this makes HTTP-caching strategies less optimal.--This commit adds a new WebJarsResourceResolver that search for resources-located in WebJar locations. This ResourceResolver is automatically-registered if the "org.webjars:webjars-locator" dependency is present.--Registering WebJars resource handling can be done like this:--```java-@Override-protected void addResourceHandlers(ResourceHandlerRegistry registry) {- registry.addResourceHandler("/webjars/**")- .addResourceLocations("classpath:META-INF/resources/webjars")- .resourceChain(true)- .addResolver(new WebJarsResourceResolver());-}-```--Issue: SPR-12323--polish-
a
https://github.com/spring-projects/spring-framework
diff --git a/build.gradle b/build.gradle index d56a60228112..c17f5bd3c188 100644 --- a/build.gradle +++ b/build.gradle @@ -895,6 +895,7 @@ project("spring-webmvc") { exclude group: "org.slf4j", module: "jcl-over-slf4j" exclude group: "org.springframework", module: "spring-web" } + optional 'org.webjars:webjars-locator:0.22' testCompile(project(":spring-aop")) testCompile("rhino:js:1.7R1") testCompile("xmlunit:xmlunit:${xmlunitVersion}") @@ -921,6 +922,7 @@ project("spring-webmvc") { testCompile("org.slf4j:slf4j-jcl:${slf4jVersion}") testCompile("org.jruby:jruby:${jrubyVersion}") testCompile("org.python:jython-standalone:2.5.3") + testCompile("org.webjars:underscorejs:1.8.2") } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java index 9d0001964628..02fbde892201 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java @@ -33,6 +33,7 @@ import org.springframework.beans.factory.xml.ParserContext; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.core.Ordered; +import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; import org.springframework.http.CacheControl; @@ -51,6 +52,7 @@ import org.springframework.web.servlet.resource.ResourceUrlProvider; import org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor; import org.springframework.web.servlet.resource.VersionResourceResolver; +import org.springframework.web.servlet.resource.WebJarsResourceResolver; /** * {@link org.springframework.beans.factory.xml.BeanDefinitionParser} that parses a @@ -78,6 +80,9 @@ class ResourcesBeanDefinitionParser implements BeanDefinitionParser { private static final String RESOURCE_URL_PROVIDER = "mvcResourceUrlProvider"; + private static final boolean isWebJarsAssetLocatorPresent = ClassUtils.isPresent( + "org.webjars.WebJarAssetLocator", ResourcesBeanDefinitionParser.class.getClassLoader()); + @Override public BeanDefinition parse(Element element, ParserContext parserContext) { @@ -302,6 +307,12 @@ private void parseResourceResolversTransformers(boolean isAutoRegistration, } if (isAutoRegistration) { + if(isWebJarsAssetLocatorPresent) { + RootBeanDefinition webJarsResolverDef = new RootBeanDefinition(WebJarsResourceResolver.class); + webJarsResolverDef.setSource(source); + webJarsResolverDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + resourceResolvers.add(webJarsResolverDef); + } RootBeanDefinition pathResolverDef = new RootBeanDefinition(PathResourceResolver.class); pathResolverDef.setSource(source); pathResolverDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java index 7749491f94f5..fea0fd805804 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; import org.springframework.web.servlet.resource.CachingResourceResolver; import org.springframework.web.servlet.resource.CachingResourceTransformer; import org.springframework.web.servlet.resource.CssLinkResourceTransformer; @@ -29,6 +30,7 @@ import org.springframework.web.servlet.resource.ResourceResolver; import org.springframework.web.servlet.resource.ResourceTransformer; import org.springframework.web.servlet.resource.VersionResourceResolver; +import org.springframework.web.servlet.resource.WebJarsResourceResolver; /** * Assists with the registration of resource resolvers and transformers. @@ -40,6 +42,9 @@ public class ResourceChainRegistration { private static final String DEFAULT_CACHE_NAME = "spring-resource-chain-cache"; + private static final boolean isWebJarsAssetLocatorPresent = ClassUtils.isPresent( + "org.webjars.WebJarAssetLocator", ResourceChainRegistration.class.getClassLoader()); + private final List<ResourceResolver> resolvers = new ArrayList<ResourceResolver>(4); private final List<ResourceTransformer> transformers = new ArrayList<ResourceTransformer>(4); @@ -98,6 +103,9 @@ public ResourceChainRegistration addTransformer(ResourceTransformer transformer) protected List<ResourceResolver> getResourceResolvers() { if (!this.hasPathResolver) { List<ResourceResolver> result = new ArrayList<ResourceResolver>(this.resolvers); + if(isWebJarsAssetLocatorPresent) { + result.add(new WebJarsResourceResolver()); + } result.add(new PathResourceResolver()); return result; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/WebJarsResourceResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/WebJarsResourceResolver.java new file mode 100644 index 000000000000..206d3fc271e2 --- /dev/null +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/WebJarsResourceResolver.java @@ -0,0 +1,90 @@ +/* + * Copyright 2002-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.web.servlet.resource; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.webjars.MultipleMatchesException; +import org.webjars.WebJarAssetLocator; + +import org.springframework.core.io.Resource; + +/** + * A {@code ResourceResolver} that delegates to the chain to locate a resource + * and then attempts to find a matching versioned resource contained in a WebJar JAR file. + * + * <p>This allows WabJar users to use version-less paths in their templates, like {@code "/jquery/jquery.min.js"} + * while this path is resolved to the unique version {@code "/jquery/1.2.0/jquery.min.js"}, which is a better fit + * for HTTP caching and version management in applications. + * + * <p>This resolver requires the "org.webjars:webjars-locator" library on classpath, and is automatically + * registered if that library is present. + * + * @author Brian Clozel + * @since 4.2 + * @see <a href="http://www.webjars.org">webjars.org</a> + */ +public class WebJarsResourceResolver extends AbstractResourceResolver { + + private final static String WEBJARS_LOCATION = "META-INF/resources/webjars"; + + private final static int WEBJARS_LOCATION_LENGTH = WEBJARS_LOCATION.length(); + + private final WebJarAssetLocator webJarAssetLocator; + + public WebJarsResourceResolver() { + this.webJarAssetLocator = new WebJarAssetLocator(); + } + + @Override + protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath, + List<? extends Resource> locations, ResourceResolverChain chain) { + + return chain.resolveResource(request, requestPath, locations); + } + + @Override + protected String resolveUrlPathInternal(String resourceUrlPath, + List<? extends Resource> locations, ResourceResolverChain chain) { + + String path = chain.resolveUrlPath(resourceUrlPath, locations); + if (path == null) { + try { + int startOffset = resourceUrlPath.startsWith("/") ? 1 : 0; + int endOffset = resourceUrlPath.indexOf("/", 1); + if (endOffset != -1) { + String webjar = resourceUrlPath.substring(startOffset, endOffset); + String partialPath = resourceUrlPath.substring(endOffset); + String webJarPath = webJarAssetLocator.getFullPath(webjar, partialPath); + return chain.resolveUrlPath(webJarPath.substring(WEBJARS_LOCATION_LENGTH), locations); + } + } + catch (MultipleMatchesException ex) { + logger.warn("WebJar version conflict for \"" + resourceUrlPath + "\"", ex); + } + catch (IllegalArgumentException ex) { + if (logger.isTraceEnabled()) { + logger.trace("No WebJar resource found for \"" + resourceUrlPath + "\""); + } + } + } + return path; + } + +} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java index fa3bc94ddfc7..92032a319615 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java @@ -119,6 +119,7 @@ import org.springframework.web.servlet.resource.ResourceUrlProvider; import org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor; import org.springframework.web.servlet.resource.VersionResourceResolver; +import org.springframework.web.servlet.resource.WebJarsResourceResolver; import org.springframework.web.servlet.theme.ThemeChangeInterceptor; import org.springframework.web.servlet.view.BeanNameViewResolver; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; @@ -409,10 +410,11 @@ public void testResourcesWithResolversTransformers() throws Exception { assertNotNull(handler); List<ResourceResolver> resolvers = handler.getResourceResolvers(); - assertThat(resolvers, Matchers.hasSize(3)); + assertThat(resolvers, Matchers.hasSize(4)); assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); assertThat(resolvers.get(1), Matchers.instanceOf(VersionResourceResolver.class)); - assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); + assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); CachingResourceResolver cachingResolver = (CachingResourceResolver) resolvers.get(0); assertThat(cachingResolver.getCache(), Matchers.instanceOf(ConcurrentMapCache.class)); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java index 101a3135e1d9..d1d0df7a447b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java @@ -40,6 +40,7 @@ import org.springframework.web.servlet.resource.ResourceResolver; import org.springframework.web.servlet.resource.ResourceTransformer; import org.springframework.web.servlet.resource.VersionResourceResolver; +import org.springframework.web.servlet.resource.WebJarsResourceResolver; import static org.junit.Assert.*; @@ -125,12 +126,13 @@ public void resourceChain() throws Exception { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List<ResourceResolver> resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(3)); + assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); CachingResourceResolver cachingResolver = (CachingResourceResolver) resolvers.get(0); assertThat(cachingResolver.getCache(), Matchers.instanceOf(ConcurrentMapCache.class)); assertThat(resolvers.get(1), Matchers.equalTo(mockResolver)); - assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); + assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); List<ResourceTransformer> transformers = handler.getResourceTransformers(); assertThat(transformers, Matchers.hasSize(2)); @@ -144,8 +146,9 @@ public void resourceChainWithoutCaching() throws Exception { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List<ResourceResolver> resolvers = handler.getResourceResolvers(); - assertThat(resolvers, Matchers.hasSize(1)); - assertThat(resolvers.get(0), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers, Matchers.hasSize(2)); + assertThat(resolvers.get(0), Matchers.instanceOf(WebJarsResourceResolver.class)); + assertThat(resolvers.get(1), Matchers.instanceOf(PathResourceResolver.class)); List<ResourceTransformer> transformers = handler.getResourceTransformers(); assertThat(transformers, Matchers.hasSize(0)); @@ -162,10 +165,11 @@ public void resourceChainWithVersionResolver() throws Exception { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List<ResourceResolver> resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(3)); + assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver)); - assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); + assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); List<ResourceTransformer> transformers = handler.getResourceTransformers(); assertThat(transformers, Matchers.hasSize(3)); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java new file mode 100644 index 000000000000..3af4aea72cc9 --- /dev/null +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java @@ -0,0 +1,107 @@ +/* + * Copyright 2002-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.web.servlet.resource; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +/** + * Unit tests for + * {@link org.springframework.web.servlet.resource.WebJarsResourceResolver}. + * + * @author Brian Clozel + */ +public class WebJarsResourceResolverTests { + + private List<Resource> locations; + + private WebJarsResourceResolver resolver; + + private ResourceResolverChain chain; + + @Before + public void setup() { + // for this to work, an actual WebJar must be on the test classpath + this.locations = Collections.singletonList(new ClassPathResource("/META-INF/resources/webjars/")); + this.resolver = new WebJarsResourceResolver(); + this.chain = mock(ResourceResolverChain.class); + } + + @Test + public void resolveUrlExisting() { + this.locations = Collections.singletonList(new ClassPathResource("/META-INF/resources/webjars/", getClass())); + String file = "/foo/2.3/foo.txt"; + given(this.chain.resolveUrlPath(file, this.locations)).willReturn(file); + + String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); + + assertEquals(file, actual); + verify(this.chain, times(1)).resolveUrlPath(file, this.locations); + } + + @Test + public void resolveUrlExistingNotInJarFile() { + this.locations = Collections.singletonList(new ClassPathResource("/META-INF/resources/webjars/", getClass())); + String file = "/foo/foo.txt"; + given(this.chain.resolveUrlPath(file, this.locations)).willReturn(null); + + String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); + + assertNull(actual); + verify(this.chain, times(1)).resolveUrlPath(file, this.locations); + verify(this.chain, never()).resolveUrlPath("/foo/2.3/foo.txt", this.locations); + } + + @Test + public void resolveUrlWebJarResource() { + String file = "/underscorejs/underscore.js"; + String expected = "/underscorejs/1.8.2/underscore.js"; + given(this.chain.resolveUrlPath(file, this.locations)).willReturn(null); + given(this.chain.resolveUrlPath(expected, this.locations)).willReturn(expected); + + String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); + + assertEquals(expected, actual); + verify(this.chain, times(1)).resolveUrlPath(file, this.locations); + verify(this.chain, times(1)).resolveUrlPath(expected, this.locations); + } + + @Test + public void resolverUrlWebJarResourceNotFound() { + String file = "/something/something.js"; + given(this.chain.resolveUrlPath(file, this.locations)).willReturn(null); + + String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); + + assertNull(actual); + verify(this.chain, times(1)).resolveUrlPath(file, this.locations); + } + +} diff --git a/spring-webmvc/src/test/resources/org/springframework/web/servlet/resource/META-INF/resources/webjars/foo/2.3/foo.txt b/spring-webmvc/src/test/resources/org/springframework/web/servlet/resource/META-INF/resources/webjars/foo/2.3/foo.txt new file mode 100644 index 000000000000..a9ed77c8dd53 --- /dev/null +++ b/spring-webmvc/src/test/resources/org/springframework/web/servlet/resource/META-INF/resources/webjars/foo/2.3/foo.txt @@ -0,0 +1 @@ +Some text. \ No newline at end of file
a376c8da9d3fa0e8b600b69cdc30c9fb0d303709
hbase
HBASE-12366 Add login code to HBase Canary tool- (Srikanth Srungarapu)--
a
https://github.com/apache/hbase
diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/AuthUtil.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/AuthUtil.java new file mode 100644 index 000000000000..bdc68377659b --- /dev/null +++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/AuthUtil.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.hbase; + +import java.io.IOException; +import java.net.UnknownHostException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.classification.InterfaceAudience; +import org.apache.hadoop.hbase.classification.InterfaceStability; +import org.apache.hadoop.hbase.security.UserProvider; +import org.apache.hadoop.hbase.util.Strings; +import org.apache.hadoop.hbase.util.Threads; +import org.apache.hadoop.net.DNS; +import org.apache.hadoop.security.UserGroupInformation; + +/** + * Utility methods for helping with security tasks. + */ [email protected] [email protected] +public class AuthUtil { + private static final Log LOG = LogFactory.getLog(AuthUtil.class); + /** + * Checks if security is enabled and if so, launches chore for refreshing kerberos ticket. + */ + public static void launchAuthChore(Configuration conf) throws IOException { + UserProvider userProvider = UserProvider.instantiate(conf); + // login the principal (if using secure Hadoop) + boolean securityEnabled = + userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled(); + if (!securityEnabled) return; + String host = null; + try { + host = Strings.domainNamePointerToHostName(DNS.getDefaultHost( + conf.get("hbase.client.dns.interface", "default"), + conf.get("hbase.client.dns.nameserver", "default"))); + userProvider.login("hbase.client.keytab.file", "hbase.client.kerberos.principal", host); + } catch (UnknownHostException e) { + LOG.error("Error resolving host name"); + throw e; + } catch (IOException e) { + LOG.error("Error while trying to perform the initial login"); + throw e; + } + + final UserGroupInformation ugi = userProvider.getCurrent().getUGI(); + Stoppable stoppable = new Stoppable() { + private volatile boolean isStopped = false; + + @Override + public void stop(String why) { + isStopped = true; + } + + @Override + public boolean isStopped() { + return isStopped; + } + }; + + // if you're in debug mode this is useful to avoid getting spammed by the getTGT() + // you can increase this, keeping in mind that the default refresh window is 0.8 + // e.g. 5min tgt * 0.8 = 4min refresh so interval is better be way less than 1min + final int CHECK_TGT_INTERVAL = 30 * 1000; // 30sec + + Chore refreshCredentials = new Chore("RefreshCredentials", CHECK_TGT_INTERVAL, stoppable) { + @Override + protected void chore() { + try { + ugi.checkTGTAndReloginFromKeytab(); + } catch (IOException e) { + LOG.info("Got exception while trying to refresh credentials "); + } + } + }; + // Start the chore for refreshing credentials + Threads.setDaemonThreadRunning(refreshCredentials.getThread()); + } +} diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java index e6e975f165bc..539ba70be2ea 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java @@ -34,6 +34,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.AuthUtil; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; @@ -755,7 +756,9 @@ private Map<String, List<HRegionInfo>> doFilterRegionServerByName( } public static void main(String[] args) throws Exception { - int exitCode = ToolRunner.run(HBaseConfiguration.create(), new Canary(), args); + final Configuration conf = HBaseConfiguration.create(); + AuthUtil.launchAuthChore(conf); + int exitCode = ToolRunner.run(conf, new Canary(), args); System.exit(exitCode); } }
efd0e554ca7e9365ec3880ef10706c9b6eca4394
camel
allow the installed languages to be browsed- restfully for CAMEL-1355--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@752938 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/components/camel-web/src/main/java/org/apache/camel/web/resources/CamelContextResource.java b/components/camel-web/src/main/java/org/apache/camel/web/resources/CamelContextResource.java index f8a72eb002eac..1015e9fd3c4cc 100644 --- a/components/camel-web/src/main/java/org/apache/camel/web/resources/CamelContextResource.java +++ b/components/camel-web/src/main/java/org/apache/camel/web/resources/CamelContextResource.java @@ -122,12 +122,11 @@ public RoutesResource getRoutesResource() { public ConvertersResource getConvertersResource() { return new ConvertersResource(this); } -/* - public List<EndpointLink> getEndpoints() { - return getEndpointsResource().getDTO().getEndpoints(); + @Path("languages") + public LanguagesResource getLanguages() { + return new LanguagesResource(this); } -*/ } diff --git a/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguageResource.java b/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguageResource.java new file mode 100644 index 0000000000000..9c09684852503 --- /dev/null +++ b/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguageResource.java @@ -0,0 +1,46 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.web.resources; + +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +import org.apache.camel.impl.converter.DefaultTypeConverter; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * @version $Revision: 1.1 $ + */ +public class LanguageResource extends CamelChildResourceSupport { + private static final transient Log LOG = LogFactory.getLog(LanguageResource.class); + private String id; + + public LanguageResource(CamelContextResource contextResource, String id) { + super(contextResource); + this.id = id; + } + + + public String getId() { + return id; + } +} \ No newline at end of file diff --git a/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguagesResource.java b/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguagesResource.java new file mode 100644 index 0000000000000..59b1de63c933b --- /dev/null +++ b/components/camel-web/src/main/java/org/apache/camel/web/resources/LanguagesResource.java @@ -0,0 +1,57 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.web.resources; + +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.List; + +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +import org.apache.camel.impl.converter.DefaultTypeConverter; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Represents the list of languages available in the current camel context + * + * @version $Revision: 1.1 $ + */ +public class LanguagesResource extends CamelChildResourceSupport { + private static final transient Log LOG = LogFactory.getLog(LanguagesResource.class); + + public LanguagesResource(CamelContextResource contextResource) { + super(contextResource); + } + + public List<String> getLanguageIds() { + return getCamelContext().getLanguageNames(); + } + + /** + * Returns a specific language + */ + @Path("{id}") + public LanguageResource getLanguage(@PathParam("id") String id) { + if (id == null) { + return null; + } + return new LanguageResource(getContextResource(), id); + } +} \ No newline at end of file diff --git a/components/camel-web/src/main/webapp/org/apache/camel/web/resources/CamelContextResource/index.jsp b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/CamelContextResource/index.jsp index c28f0dcd36d17..fb2f6b1acbcdc 100644 --- a/components/camel-web/src/main/webapp/org/apache/camel/web/resources/CamelContextResource/index.jsp +++ b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/CamelContextResource/index.jsp @@ -26,6 +26,9 @@ </p> <ul> + <li> + <a href="<c:url value='/languages'/>" title="View the available languages you can use with Camel">Languages</a> + </li> <li> <a href="<c:url value='/converters'/>" title="View the available type converters currently registered with Camel">Type Converters</a> </li> diff --git a/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguageResource/index.jsp b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguageResource/index.jsp new file mode 100644 index 0000000000000..e3d53f8863ae0 --- /dev/null +++ b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguageResource/index.jsp @@ -0,0 +1,18 @@ +<html> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + <title>${it.id}</title> +</head> +<body> + +<h1>${it.id}</h1> + +<p> + Welcome to the ${it.id} language. +</p> +<p> + For more information see the <a href="http://camel.apache.org/${it.id}.html">documentation</a> +</p> + +</body> +</html> diff --git a/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguagesResource/index.jsp b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguagesResource/index.jsp new file mode 100644 index 0000000000000..3306818ee7906 --- /dev/null +++ b/components/camel-web/src/main/webapp/org/apache/camel/web/resources/LanguagesResource/index.jsp @@ -0,0 +1,25 @@ +<html> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + <title>Languages</title> +</head> +<body> + +<h1>Languages</h1> + + +<table> + <tr> + <th>Language</th> + <th>Documentation</th> + </tr> + <c:forEach items="${it.languageIds}" var="id"> + <tr> + <td><a href="languages/${id}">${id}</a></td> + <td><a href="http://camel.apache.org/${id}.html">documentation</a></td> + </tr> + </c:forEach> +</table> + +</body> +</html>
50ccd7ec86dc105c4c6030cd152423ec7b1483a2
restlet-framework-java
JAX-RS-Extension: - added javadoc to util methods.--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/Util.java b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/Util.java index 1378510e3c..0df57b574c 100644 --- a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/Util.java +++ b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/Util.java @@ -41,7 +41,6 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; -import java.util.TreeSet; import java.util.logging.Logger; import javax.ws.rs.Path; @@ -334,19 +333,6 @@ public static <A> Set<A> createSet(A... objects) { return set; } - /** - * @param <A> - * @param collection - * @param comparator - * @return - */ - public static <A> Collection<A> createTreeSet(Collection<A> collection, - Comparator<A> comparator) { - Collection<A> coll2 = new TreeSet<A>(comparator); - coll2.addAll(collection); - return coll2; - } - /** * Check if the given objects are equal. Can deal with null references. if * both elements are null, than the result is true. @@ -362,7 +348,7 @@ public static boolean equals(Object object1, Object object2) { } /** - * Converte the given Date into a String. Copied from + * Converts the given Date into a String. Copied from * {@link com.noelios.restlet.HttpCall}. * * @param date @@ -380,16 +366,19 @@ public static String formatDate(Date date, boolean cookie) { } /** + * Returns the first element of the given collection. Throws an exception if + * the collection is empty. + * * @param coll * @param <A> * @return Returns the first Element of the collection - * @throws IndexOutOfBoundsException - * If the list is empty + * @throws NoSuchElementException + * If the collection is empty. */ public static <A> A getFirstElement(Collection<A> coll) - throws IndexOutOfBoundsException { + throws NoSuchElementException { if (coll.isEmpty()) - throw new IndexOutOfBoundsException( + throw new NoSuchElementException( "The Collection is empty; you can't get the first element of it."); if (coll instanceof LinkedList) return ((LinkedList<A>) coll).getFirst(); @@ -399,14 +388,17 @@ public static <A> A getFirstElement(Collection<A> coll) } /** + * Returns the first element of the given {@link Iterable}. Throws an + * exception if the {@link Iterable} is empty. + * * @param coll * @param <A> * @return Returns the first Element of the collection - * @throws IndexOutOfBoundsException - * If the list is empty + * @throws NoSuchElementException + * If the collection is empty */ public static <A> A getFirstElement(Iterable<A> coll) - throws IndexOutOfBoundsException { + throws NoSuchElementException { if (coll instanceof LinkedList) return ((LinkedList<A>) coll).getFirst(); if (coll instanceof List) @@ -415,6 +407,9 @@ public static <A> A getFirstElement(Iterable<A> coll) } /** + * Returns the first element of the {@link List}. Throws an exception if + * the list is empty. + * * @param list * @param <A> * @return Returns the first Element of the collection @@ -432,14 +427,15 @@ public static <A> A getFirstElement(List<A> list) } /** + * Returns the first element of the given {@link Iterable}. Returns null, + * if the {@link Iterable} is empty. + * * @param coll * @param <A> - * @return Returns the first Element of the collection - * @throws IndexOutOfBoundsException - * If the list is empty + * @return the first element of the collection, or null if the iterable is + * empty. */ - public static <A> A getFirstElementOrNull(Iterable<A> coll) - throws IndexOutOfBoundsException { + public static <A> A getFirstElementOrNull(Iterable<A> coll) { if (coll instanceof LinkedList) { LinkedList<A> linkedList = ((LinkedList<A>) coll); if (linkedList.isEmpty()) @@ -460,12 +456,13 @@ public static <A> A getFirstElementOrNull(Iterable<A> coll) } /** + * Returns the first entry of the given {@link Map}. Throws an exception if + * the Map is empty. + * * @param map * @param <K> * @param <V> - * @return Returns the first element, returned by the iterator over the - * map.entrySet() - * + * @return the first entry of the given {@link Map}. * @throws NoSuchElementException * If the map is empty. */ @@ -475,12 +472,13 @@ public static <K, V> Map.Entry<K, V> getFirstEntry(Map<K, V> map) } /** - * @return Returns the first element, returned by the iterator over the - * map.keySet() + * Returns the key of the first entry of the given {@link Map}. Throws an + * exception if the Map is empty. * * @param map * @param <K> * @param <V> + * @return the key of the first entry of the given {@link Map}. * @throws NoSuchElementException * If the map is empty. */ @@ -490,11 +488,13 @@ public static <K, V> K getFirstKey(Map<K, V> map) } /** - * @return Returns the first element, returned by the iterator over the - * map.values() + * Returns the value of the first entry of the given {@link Map}. Throws an + * exception if the Map is empty. + * * @param map * @param <K> * @param <V> + * @return the value of the first entry of the given {@link Map}. * @throws NoSuchElementException * If the map is empty. */ @@ -504,8 +504,10 @@ public static <K, V> V getFirstValue(Map<K, V> map) } /** + * Returns the HTTP headers of the Restlet {@link Request} as {@link Form}. + * * @param request - * @return Returns the HTTP-Headers-Form from the Request. + * @return Returns the HTTP headers of the Request. */ public static Form getHttpHeaders(Request request) { Form headers = (Form) request.getAttributes().get( @@ -518,9 +520,10 @@ public static Form getHttpHeaders(Request request) { } /** + * Returns the HTTP headers of the Restlet {@link Response} as {@link Form}. + * * @param response - * a Restlet response - * @return Returns the HTTP-Headers-Form from the Response. + * @return Returns the HTTP headers of the Response. */ public static Form getHttpHeaders(Response response) { Form headers = (Form) response.getAttributes().get( @@ -553,9 +556,12 @@ public static MultivaluedMap<String, String> getJaxRsHttpHeaders( } /** + * Returns the last element of the given {@link Iterable}. Throws an + * exception if the given iterable is empty. + * * @param iterable * @param <A> - * @return Returns the last Element of the {@link Iterable} + * @return Returns the last element of the {@link Iterable} * @throws IndexOutOfBoundsException * If the {@link Iterable} is a {@link List} and its is * empty. @@ -575,9 +581,12 @@ public static <A> A getLastElement(Iterable<A> iterable) } /** + * Returns the last element of the given {@link Iterator}. Throws an + * exception if the given iterator is empty. + * * @param iter * @param <A> - * @return Returns the last Element of the {@link Iterator}. + * @return Returns the last element of the {@link Iterator}. * @throws NoSuchElementException * If the {@link Iterator} is empty. */ @@ -590,9 +599,12 @@ public static <A> A getLastElement(Iterator<A> iter) } /** + * Returns the last element of the given {@link List}. Throws an exception + * if the given list is empty. + * * @param list * @param <A> - * @return Returns the last Element of the list + * @return Returns the last element of the list * @throws IndexOutOfBoundsException * If the list is empty */ @@ -604,7 +616,8 @@ public static <A> A getLastElement(List<A> list) } /** - * Returns the last element of the given Iterable, or null, if it is empty. + * Returns the last element of the given {@link Iterable}, or null, if the + * iterable is empty. Returns null, if the iterable is empty. * * @param iterable * @param <A> @@ -632,11 +645,12 @@ public static <A> A getLastElementOrNull(Iterable<A> iterable) { } /** + * Returns the last element of the given {@link Iterator}, or null, if the + * iterator is empty. Returns null, if the iterator is empty. + * * @param iter * @param <A> * @return Returns the last Element of the {@link Iterator}. - * @throws NoSuchElementException - * If the {@link Iterator} is empty. */ public static <A> A getLastElementOrNull(Iterator<A> iter) { A e = null; @@ -716,9 +730,13 @@ public static String getOnlyMetadataName(List<? extends Metadata> metadatas) { } /** + * Returns the &#64;{@link Path} annotation of the given root resource + * class. + * * @param jaxRsClass - * @return the path annotation or null, if no is present and requirePath is - * false. + * the root resource class. + * @return the &#64;{@link Path} annotation of the given root resource + * class. * @throws MissingAnnotationException * if the path annotation is missing * @throws IllegalArgumentException @@ -737,9 +755,12 @@ public static Path getPathAnnotation(Class<?> jaxRsClass) } /** + * Returns the &#64;{@link Path} annotation of the given sub resource + * locator. Throws an exception if no &#64;{@link Path} annotation is + * available. + * * @param method * the java method to get the &#64;Path from - * @param pathRequired * @return the &#64;Path annotation. * @throws IllegalArgumentException * if null was given. @@ -759,6 +780,9 @@ public static Path getPathAnnotation(Method method) } /** + * Returns the &#64;{@link Path} annotation of the given sub resource + * locator. Returns null if no &#64;{@link Path} annotation is available. + * * @param method * the java method to get the &#64;Path from * @return the &#64;Path annotation or null, if not present. @@ -774,6 +798,8 @@ public static Path getPathAnnotationOrNull(Method method) } /** + * Returns the perhaps decoded template of the path annotation. + * * @param resource * @return Returns the path template as String. Never returns null. * @throws IllegalPathOnClassException @@ -932,7 +958,7 @@ public Object run() throws Exception { } /** - * Checks, if the list is empty. + * Checks, if the list is empty or null. * * @param list * @return true, if the list is empty or null, or false, if the list @@ -944,7 +970,7 @@ public static boolean isEmpty(List<?> list) { } /** - * Tests, if the given array is empty. Will not throw a + * Tests, if the given array is empty or null. Will not throw a * NullPointerException. * * @param array @@ -959,11 +985,12 @@ public static boolean isEmpty(Object[] array) { } /** - * Tests, if the given String is empty or "/". Will not throw a + * Tests, if the given String is null, empty or "/". Will not throw a * NullPointerException. * * @param string - * @return Returns true, if the given string ist null, empty or equals "/" + * @return Returns true, if the given string ist null, empty or equals "/", + * otherwise false. */ public static boolean isEmptyOrSlash(String string) { return string == null || string.length() == 0 || string.equals("/"); diff --git a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/IntoRrcInjector.java b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/IntoRrcInjector.java index 7020117cc8..6fb83146e9 100644 --- a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/IntoRrcInjector.java +++ b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/IntoRrcInjector.java @@ -179,12 +179,11 @@ protected void inject(ResourceObject resourceObject, } for (Field ppf : this.injectFieldsPathParam) { PathParam headerParam = ppf.getAnnotation(PathParam.class); - DefaultValue defaultValue = ppf.getAnnotation(DefaultValue.class); + // REQUEST forbid @DefaultValue on @PathParam Class<?> convTo = ppf.getType(); Type paramGenericType = ppf.getGenericType(); Object value = WrapperUtil.getPathParamValue(convTo, - paramGenericType, headerParam, leaveEncoded, defaultValue, - callContext); + paramGenericType, headerParam, leaveEncoded, callContext); Util.inject(jaxRsResObj, ppf, value); } for (Field cpf : this.injectFieldsQueryParam) { diff --git a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java index c362ef193e..7b0e25733b 100644 --- a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java +++ b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java @@ -134,6 +134,8 @@ public void remove() { private static final Collection<Class<? extends Annotation>> VALID_ANNOTATIONS = createValidAnnotations(); /** + * Checks, if the given annotation is annotated with at least one JAX-RS + * related annotation. * * @param javaMethod * Java method, class or something like that. @@ -143,7 +145,7 @@ public void remove() { static boolean checkForJaxRsAnnotations(Method javaMethod) { for (Annotation annotation : javaMethod.getAnnotations()) { Class<? extends Annotation> annoType = annotation.annotationType(); - if (annoType.getName().startsWith(WrapperUtil.JAX_RS_PACKAGE_PREFIX)) + if (annoType.getName().startsWith(JAX_RS_PACKAGE_PREFIX)) return true; if (annoType.isAnnotationPresent(HttpMethod.class)) return true; @@ -217,7 +219,7 @@ private static boolean checkParameterAnnotation( } /** - * converts the given value without any decoding. + * Converts the given value without any decoding. * * @param paramClass * @param paramValue @@ -419,8 +421,12 @@ static List<MediaType> convertToMediaTypes(String[] mimes) { } /** + * Creates the collection for the given + * {@link ParameterizedType parametrized Type}.<br> + * If the given type do not represent an collection, null is returned. + * * @param type - * @return + * @return the created collection or null. */ private static <A> Collection<A> createColl(ParameterizedType type) { Type rawType = type.getRawType(); @@ -432,28 +438,37 @@ else if (rawType.equals(SortedSet.class)) return new TreeSet<A>(); else if (rawType.equals(Collection.class)) { Logger logger = Logger.getAnonymousLogger(); - logger.config(WrapperUtil.COLL_PARAM_NOT_DEFAULT); + logger.config(COLL_PARAM_NOT_DEFAULT); return new ArrayList<A>(); } return null; } /** + * Creates a concrete instance of the given {@link Representation} subtype. + * It must contain a constructor with one parameter of type + * {@link Representation}. + * + * @param representationType + * the class to instantiate * @param entity + * the Representation to use for the constructor. + * @param logger + * the logger to use * @return the created representation, or null, if it could not be * converted. - * @throws ConvertParameterException + * @throws ConvertRepresentationException */ private static Object createConcreteRepresentationInstance( - Class<?> paramType, Representation entity, Logger logger) + Class<?> representationType, Representation entity, Logger logger) throws ConvertRepresentationException { - if (paramType.equals(Representation.class)) + if (representationType.equals(Representation.class)) return entity; Constructor<?> constr; try { - constr = paramType.getConstructor(Representation.class); + constr = representationType.getConstructor(Representation.class); } catch (SecurityException e) { - logger.warning("The constructor " + paramType + logger.warning("The constructor " + representationType + "(Representation) is not accessable."); return null; } catch (NoSuchMethodException e) { @@ -462,7 +477,7 @@ private static Object createConcreteRepresentationInstance( try { return constr.newInstance(entity); } catch (Exception e) { - throw ConvertRepresentationException.object(paramType, + throw ConvertRepresentationException.object(representationType, "the message body", e); } } @@ -518,17 +533,14 @@ static Object createInstance(Constructor<?> constructor, try { return constructor.newInstance(args); } catch (IllegalArgumentException e) { - throw new InstantiateException( - "Could not instantiate " + constructor.getDeclaringClass(), - e); + throw new InstantiateException("Could not instantiate " + + constructor.getDeclaringClass(), e); } catch (InstantiationException e) { - throw new InstantiateException( - "Could not instantiate " + constructor.getDeclaringClass(), - e); + throw new InstantiateException("Could not instantiate " + + constructor.getDeclaringClass(), e); } catch (IllegalAccessException e) { - throw new InstantiateException( - "Could not instantiate " + constructor.getDeclaringClass(), - e); + throw new InstantiateException("Could not instantiate " + + constructor.getDeclaringClass(), e); } } @@ -540,11 +552,12 @@ static Collection<Class<? extends Annotation>> createValidAnnotations() { } /** + * Finds the constructor to use by the JAX-RS runtime. + * * @param jaxRsClass * @return Returns the constructor to use for the given root resource class - * (See JSR-311-Spec, section 2.3). If no constructor could be - * found, null is returned. Than try {@link Class#newInstance()} - * @throws IllegalTypeException + * or provider. If no constructor could be found, null is returned. + * Than try {@link Class#newInstance()} */ static Constructor<?> findJaxRsConstructor(Class<?> jaxRsClass) { Constructor<?> constructor = null; @@ -608,6 +621,8 @@ static javax.ws.rs.ext.ContextResolver<?> getContextResolver(Field field, } /** + * Creates the value of a cookie as the given type. + * * @param paramClass * the class to convert to * @param paramGenericType @@ -674,10 +689,10 @@ static Object getCookieParamValue(Class<?> paramClass, return convertParamValuesFromParam(paramClass, paramGenericType, new ParamValueIter((Series) cookies.subList(cookieName)), getValue(cookies.getFirst(cookieName)), defaultValue, true); + // leaveEncoded = true -> not change } catch (ConvertParameterException e) { throw new ConvertCookieParamException(e); } - // leaveEncoded = true -> not change } /** @@ -707,6 +722,12 @@ static Object getHeaderParamValue(Class<?> paramClass, } } + /** + * Returns the HTTP method related to the given java method. + * + * @param javaMethod + * @return + */ static org.restlet.data.Method getHttpMethod(Method javaMethod) { for (Annotation annotation : javaMethod.getAnnotations()) { Class<? extends Annotation> annoType = annotation.annotationType(); @@ -812,8 +833,7 @@ else if (paramClass.equals(Conditions.class)) } if (annoType.equals(PathParam.class)) { return getPathParamValue(paramClass, paramGenericType, - (PathParam) annotation, leaveEncoded, defaultValue, - callContext); + (PathParam) annotation, leaveEncoded, callContext); } if (annoType.equals(MatrixParam.class)) { return getMatrixParamValue(paramClass, paramGenericType, @@ -992,15 +1012,13 @@ private static Object getParamValueForPrimitive(Class<?> paramClass, * the generic type to convert to * @param pathParam * @param leaveEncoded - * @param defaultValue * @param callContext * @param logger * @return * @throws ConvertPathParamException */ static Object getPathParamValue(Class<?> paramClass, Type paramGenericType, - PathParam pathParam, boolean leaveEncoded, - DefaultValue defaultValue, CallContext callContext) + PathParam pathParam, boolean leaveEncoded, CallContext callContext) throws ConvertPathParamException { // LATER testen Path-Param: List<String> (see PathParamTest.testGet3()) // TODO @PathParam("x") PathSegment allowed. @@ -1008,10 +1026,13 @@ static Object getPathParamValue(Class<?> paramClass, Type paramGenericType, String pathParamValue = callContext.getLastPathParamEnc(pathParam); Iterator<String> pathParamValueIter = callContext .pathParamEncIter(pathParam); + // REQUEST What should happens, if no PathParam could be found? + // Internal Server Error? It could be that someone request a qPathParam + // value of a prior @Path, but this is not good IMO. + // perhaps add another attribute to @PathParam, which allows it. try { return convertParamValuesFromParam(paramClass, paramGenericType, - pathParamValueIter, pathParamValue, defaultValue, - leaveEncoded); + pathParamValueIter, pathParamValue, null, leaveEncoded); } catch (ConvertParameterException e) { throw new ConvertPathParamException(e); }
f8a5053d2b51dd72cb46ab32e776957443a3dd88
drools
JBRULES-527: adding primitive support to alpha- hashing code--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@7150 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/base/ValueType.java b/drools-core/src/main/java/org/drools/base/ValueType.java index bd4f9bc24bb..ed7712339f1 100644 --- a/drools-core/src/main/java/org/drools/base/ValueType.java +++ b/drools-core/src/main/java/org/drools/base/ValueType.java @@ -212,8 +212,35 @@ public boolean isBoolean() { } public boolean isNumber() { - return (Number.class.isAssignableFrom( this.classType )) || (this.classType == Byte.TYPE) || (this.classType == Short.TYPE) || (this.classType == Integer.TYPE) || (this.classType == Long.TYPE) || (this.classType == Float.TYPE) - || (this.classType == Double.TYPE); + return (this.classType == Integer.TYPE) || + (this.classType == Long.TYPE) || + (this.classType == Float.TYPE) || + (this.classType == Double.TYPE) || + (this.classType == Byte.TYPE) || + (this.classType == Short.TYPE) || + (this.classType == Character.TYPE) || + (this.classType == Character.class) || + (Number.class.isAssignableFrom( this.classType )); + } + + public boolean isIntegerNumber() { + return (this.classType == Integer.TYPE) || + (this.classType == Long.TYPE) || + (this.classType == Integer.class) || + (this.classType == Long.class) || + (this.classType == Character.class) || + (this.classType == Character.TYPE) || + (this.classType == Byte.TYPE) || + (this.classType == Short.TYPE) || + (this.classType == Byte.class) || + (this.classType == Short.class); + } + + public boolean isFloatNumber() { + return (this.classType == Float.TYPE) || + (this.classType == Double.TYPE) || + (this.classType == Float.class) || + (this.classType == Double.class); } public boolean isChar() { diff --git a/drools-core/src/main/java/org/drools/base/field/BooleanFieldImpl.java b/drools-core/src/main/java/org/drools/base/field/BooleanFieldImpl.java index 11fcbefca1b..33bd1bc15e7 100755 --- a/drools-core/src/main/java/org/drools/base/field/BooleanFieldImpl.java +++ b/drools-core/src/main/java/org/drools/base/field/BooleanFieldImpl.java @@ -90,4 +90,20 @@ public int hashCode() { return this.value ? 1 : 0; } + public boolean isBooleanField() { + return true; + } + + public boolean isFloatNumberField() { + return false; + } + + public boolean isIntegerNumberField() { + return false; + } + + public boolean isObjectField() { + return false; + } + } diff --git a/drools-core/src/main/java/org/drools/base/field/DoubleFieldImpl.java b/drools-core/src/main/java/org/drools/base/field/DoubleFieldImpl.java index a5e9ad8ffe5..86f92fcaea7 100755 --- a/drools-core/src/main/java/org/drools/base/field/DoubleFieldImpl.java +++ b/drools-core/src/main/java/org/drools/base/field/DoubleFieldImpl.java @@ -70,4 +70,20 @@ public int hashCode() { return (int) this.value; } + public boolean isBooleanField() { + return false; + } + + public boolean isFloatNumberField() { + return true; + } + + public boolean isIntegerNumberField() { + return false; + } + + public boolean isObjectField() { + return false; + } + } diff --git a/drools-core/src/main/java/org/drools/base/field/LongFieldImpl.java b/drools-core/src/main/java/org/drools/base/field/LongFieldImpl.java index e29ceb6ab54..4cd2563c166 100755 --- a/drools-core/src/main/java/org/drools/base/field/LongFieldImpl.java +++ b/drools-core/src/main/java/org/drools/base/field/LongFieldImpl.java @@ -69,4 +69,20 @@ public boolean equals(final Object object) { public int hashCode() { return (int) this.value; } + + public boolean isBooleanField() { + return false; + } + + public boolean isFloatNumberField() { + return false; + } + + public boolean isIntegerNumberField() { + return true; + } + + public boolean isObjectField() { + return false; + } } diff --git a/drools-core/src/main/java/org/drools/base/field/ObjectFieldImpl.java b/drools-core/src/main/java/org/drools/base/field/ObjectFieldImpl.java index add6bf9297e..a9ae0922d95 100644 --- a/drools-core/src/main/java/org/drools/base/field/ObjectFieldImpl.java +++ b/drools-core/src/main/java/org/drools/base/field/ObjectFieldImpl.java @@ -113,4 +113,20 @@ public int hashCode() { return 0; } } + + public boolean isBooleanField() { + return false; + } + + public boolean isFloatNumberField() { + return false; + } + + public boolean isIntegerNumberField() { + return false; + } + + public boolean isObjectField() { + return true; + } } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/reteoo/CompositeObjectSinkAdapter.java b/drools-core/src/main/java/org/drools/reteoo/CompositeObjectSinkAdapter.java index 787805080f6..ce63267c935 100644 --- a/drools-core/src/main/java/org/drools/reteoo/CompositeObjectSinkAdapter.java +++ b/drools-core/src/main/java/org/drools/reteoo/CompositeObjectSinkAdapter.java @@ -4,13 +4,16 @@ import java.util.ArrayList; import java.util.List; +import org.drools.base.ValueType; import org.drools.base.evaluators.Operator; import org.drools.common.InternalFactHandle; import org.drools.common.InternalWorkingMemory; import org.drools.rule.LiteralConstraint; import org.drools.spi.AlphaNodeFieldConstraint; import org.drools.spi.Evaluator; +import org.drools.spi.Extractor; import org.drools.spi.FieldExtractor; +import org.drools.spi.FieldValue; import org.drools.spi.PropagationContext; import org.drools.util.Iterator; import org.drools.util.LinkedList; @@ -22,21 +25,20 @@ public class CompositeObjectSinkAdapter implements ObjectSinkPropagator { - - /** You can override this property via a system property (eg -Ddrools.hashThreshold=4) */ public static final String HASH_THRESHOLD_SYSTEM_PROPERTY = "drools.hashThreshold"; /** The threshold for when hashing kicks in */ - public static final int THRESHOLD_TO_HASH = Integer.parseInt( System.getProperty( HASH_THRESHOLD_SYSTEM_PROPERTY, "3" )); - - private static final long serialVersionUID = 2192568791644369227L; - ObjectSinkNodeList otherSinks; - ObjectSinkNodeList hashableSinks; + public static final int THRESHOLD_TO_HASH = Integer.parseInt( System.getProperty( HASH_THRESHOLD_SYSTEM_PROPERTY, + "3" ) ); - LinkedList hashedFieldIndexes; + private static final long serialVersionUID = 2192568791644369227L; + ObjectSinkNodeList otherSinks; + ObjectSinkNodeList hashableSinks; - ObjectHashMap hashedSinkMap; + LinkedList hashedFieldIndexes; + + ObjectHashMap hashedSinkMap; private HashKey hashKey; @@ -56,18 +58,18 @@ public void addObjectSink(final ObjectSink sink) { if ( evaluator.getOperator() == Operator.EQUAL ) { final int index = literalConstraint.getFieldExtractor().getIndex(); final FieldIndex fieldIndex = registerFieldIndex( index, - literalConstraint.getFieldExtractor() ); + literalConstraint.getFieldExtractor() ); if ( fieldIndex.getCount() >= THRESHOLD_TO_HASH ) { if ( !fieldIndex.isHashed() ) { hashSinks( fieldIndex ); } - final Object value = literalConstraint.getField().getValue(); + final FieldValue value = literalConstraint.getField(); // no need to check, we know the sink does not exist this.hashedSinkMap.put( new HashKey( index, - value ), - sink, - false ); + value ), + sink, + false ); } else { if ( this.hashableSinks == null ) { this.hashableSinks = new ObjectSinkNodeList(); @@ -95,15 +97,14 @@ public void removeObjectSink(final ObjectSink sink) { if ( fieldConstraint.getClass() == LiteralConstraint.class ) { final LiteralConstraint literalConstraint = (LiteralConstraint) fieldConstraint; final Evaluator evaluator = literalConstraint.getEvaluator(); - final Object value = literalConstraint.getField().getValue(); + final FieldValue value = literalConstraint.getField(); if ( evaluator.getOperator() == Operator.EQUAL ) { final int index = literalConstraint.getFieldExtractor().getIndex(); final FieldIndex fieldIndex = unregisterFieldIndex( index ); if ( fieldIndex.isHashed() ) { - this.hashKey.setIndex( index ); - this.hashKey.setValue( value ); + this.hashKey.setValue( index, value ); this.hashedSinkMap.remove( this.hashKey ); if ( fieldIndex.getCount() <= THRESHOLD_TO_HASH - 1 ) { // we have less than three so unhash @@ -144,11 +145,11 @@ public void hashSinks(final FieldIndex fieldIndex) { final LiteralConstraint literalConstraint = (LiteralConstraint) fieldConstraint; final Evaluator evaluator = literalConstraint.getEvaluator(); if ( evaluator.getOperator() == Operator.EQUAL && index == literalConstraint.getFieldExtractor().getIndex() ) { - final Object value = literalConstraint.getField().getValue(); + final FieldValue value = literalConstraint.getField(); list.add( sink ); this.hashedSinkMap.put( new HashKey( index, - value ), - sink ); + value ), + sink ); } } @@ -167,17 +168,16 @@ public void hashSinks(final FieldIndex fieldIndex) { public void unHashSinks(final FieldIndex fieldIndex) { final int index = fieldIndex.getIndex(); - List sinks = new ArrayList(); - + //iterate twice as custom iterator is immutable Iterator mapIt = this.hashedSinkMap.iterator(); - for(ObjectHashMap.ObjectEntry e = (ObjectHashMap.ObjectEntry) mapIt.next(); e != null; ) { + for ( ObjectHashMap.ObjectEntry e = (ObjectHashMap.ObjectEntry) mapIt.next(); e != null; ) { sinks.add( e.getValue() ); e = (ObjectHashMap.ObjectEntry) mapIt.next(); } - + for ( java.util.Iterator iter = sinks.iterator(); iter.hasNext(); ) { AlphaNode sink = (AlphaNode) iter.next(); final AlphaNode alphaNode = (AlphaNode) sink; @@ -185,16 +185,15 @@ public void unHashSinks(final FieldIndex fieldIndex) { final LiteralConstraint literalConstraint = (LiteralConstraint) fieldConstraint; final Evaluator evaluator = literalConstraint.getEvaluator(); if ( evaluator.getOperator() == Operator.EQUAL && index == literalConstraint.getFieldExtractor().getIndex() ) { - final Object value = literalConstraint.getField().getValue(); - if (this.hashableSinks == null) { + final FieldValue value = literalConstraint.getField(); + if ( this.hashableSinks == null ) { this.hashableSinks = new ObjectSinkNodeList(); } this.hashableSinks.add( sink ); - this.hashedSinkMap.remove( new HashKey(index, value) ); + this.hashedSinkMap.remove( new HashKey( index, + value ) ); }; } - - if ( this.hashedSinkMap.isEmpty() ) { this.hashedSinkMap = null; @@ -276,14 +275,13 @@ public void propagateAssertObject(final InternalFactHandle handle, if ( this.hashedFieldIndexes != null ) { // Iterate the FieldIndexes to see if any are hashed for ( FieldIndex fieldIndex = (FieldIndex) this.hashedFieldIndexes.getFirst(); fieldIndex != null; fieldIndex = (FieldIndex) fieldIndex.getNext() ) { - if ( !fieldIndex.isHashed() ) { + if ( !fieldIndex.isHashed() ) { continue; } // this field is hashed so set the existing hashKey and see if there is a sink for it final int index = fieldIndex.getIndex(); final FieldExtractor extractor = fieldIndex.getFieldExtactor(); - this.hashKey.setIndex( index ); - this.hashKey.setValue( extractor.getValue( object ) ); + this.hashKey.setValue( index, object, extractor ); final ObjectSink sink = (ObjectSink) this.hashedSinkMap.get( this.hashKey ); if ( sink != null ) { // The sink exists so propagate @@ -324,14 +322,13 @@ public void propagateRetractObject(final InternalFactHandle handle, // Iterate the FieldIndexes to see if any are hashed for ( FieldIndex fieldIndex = (FieldIndex) this.hashedFieldIndexes.getFirst(); fieldIndex != null; fieldIndex = (FieldIndex) fieldIndex.getNext() ) { // this field is hashed so set the existing hashKey and see if there is a sink for it - if ( ! fieldIndex.isHashed() ) { + if ( !fieldIndex.isHashed() ) { continue; } - + final int index = fieldIndex.getIndex(); final FieldExtractor extractor = fieldIndex.getFieldExtactor(); - this.hashKey.setIndex( index ); - this.hashKey.setValue( extractor.getValue( object ) ); + this.hashKey.setValue( index, object, extractor ); final ObjectSink sink = (ObjectSink) this.hashedSinkMap.get( this.hashKey ); if ( sink != null ) { // The sink exists so propagate @@ -397,56 +394,117 @@ public ObjectSink[] getSinks() { } public int size() { - int size = 0; - size += ( ( otherSinks != null ) ? otherSinks.size() : 0); - size += ( ( hashableSinks != null ) ? hashableSinks.size() : 0); - size += ( ( hashedSinkMap != null ) ? hashedSinkMap.size() : 0); + int size = 0; + size += ((otherSinks != null) ? otherSinks.size() : 0); + size += ((hashableSinks != null) ? hashableSinks.size() : 0); + size += ((hashedSinkMap != null) ? hashedSinkMap.size() : 0); return size; } - public static class HashKey implements Serializable { - private int index; - private Object value; + public static class HashKey + implements + Serializable { + private static final long serialVersionUID = 1949191240975565186L; + + private static final byte OBJECT = 1; + private static final byte LONG = 2; + private static final byte DOUBLE = 3; + private static final byte BOOL = 4; + private int index; + + private byte type; + private Object ovalue; + private long lvalue; + private boolean bvalue; + private double dvalue; + + private int hashCode; + public HashKey() { + } + public HashKey(final int index, + final FieldValue value ) { + this.setValue( index, value ); } public HashKey(final int index, - final Object value) { - super(); - this.index = index; - this.value = value; + final Object value, + final Extractor extractor) { + this.setValue( index, value, extractor ); } public int getIndex() { return this.index; } - public void setIndex(final int index) { + public void setValue(final int index, final Object value, final Extractor extractor) { this.index = index; + ValueType vtype = extractor.getValueType(); + if( vtype.isBoolean() ) { + this.bvalue = extractor.getBooleanValue( value ); + this.type = BOOL; + this.setHashCode( this.bvalue ? 1231 : 1237 ); + } else if( vtype.isIntegerNumber() ) { + this.lvalue = extractor.getLongValue( value ); + this.type = LONG; + this.setHashCode( (int) ( this.lvalue ^ ( this.lvalue >>> 32 ) ) ); + } else if( vtype.isFloatNumber() ) { + this.dvalue = extractor.getDoubleValue( value ); + this.type = DOUBLE; + long temp = Double.doubleToLongBits( this.dvalue ); + this.setHashCode( (int) ( temp ^ ( temp >>> 32 ))); + } else { + this.ovalue = extractor.getValue( value ); + this.type = OBJECT; + this.setHashCode( this.ovalue.hashCode() ); + } } - - public Object getValue() { - return this.value; - } - - public void setValue(final Object value) { - this.value = value; + + public void setValue(final int index, final FieldValue value) { + this.index = index; + if( value.isBooleanField() ) { + this.bvalue = value.getBooleanValue(); + this.type = BOOL; + this.setHashCode( this.bvalue ? 1231 : 1237 ); + } else if( value.isIntegerNumberField() ) { + this.lvalue = value.getLongValue(); + this.type = LONG; + this.setHashCode( (int) ( this.lvalue ^ ( this.lvalue >>> 32 ) ) ); + } else if( value.isFloatNumberField() ) { + this.dvalue = value.getDoubleValue(); + this.type = DOUBLE; + long temp = Double.doubleToLongBits( this.dvalue ); + this.setHashCode( (int) ( temp ^ ( temp >>> 32 ))); + } else { + this.ovalue = value.getValue(); + this.type = OBJECT; + this.setHashCode( this.ovalue.hashCode() ); + } } - - public int hashCode() { + + private void setHashCode(int hashSeed) { final int PRIME = 31; int result = 1; + result = PRIME * result + hashSeed; result = PRIME * result + this.index; - result = PRIME * result + ((this.value == null) ? 0 : this.value.hashCode()); - return result; + this.hashCode = result; + } + + public int hashCode() { + return this.hashCode; } public boolean equals(final Object object) { final HashKey other = (HashKey) object; - return this.index == other.index && this.value.equals( other.value ); + return this.index == other.index && + this.type == other.type && + ( ((this.type == BOOL) && (this.bvalue == other.bvalue)) || + ((this.type == LONG) && (this.lvalue == other.lvalue)) || + ((this.type == DOUBLE) && (this.dvalue == other.dvalue)) || + ((this.type == OBJECT) && (this.ovalue.equals( other.ovalue ))) ); } } @@ -455,15 +513,15 @@ public static class FieldIndex implements LinkedListNode { private static final long serialVersionUID = 3853708964744065172L; - private final int index; - private FieldExtractor fieldExtactor; + private final int index; + private FieldExtractor fieldExtactor; - private int count; + private int count; - private boolean hashed; + private boolean hashed; - private LinkedListNode previous; - private LinkedListNode next; + private LinkedListNode previous; + private LinkedListNode next; public FieldIndex(final int index, final FieldExtractor fieldExtractor) { diff --git a/drools-core/src/main/java/org/drools/reteoo/ObjectTypeNode.java b/drools-core/src/main/java/org/drools/reteoo/ObjectTypeNode.java index 02c8f1791a6..8332c509bee 100644 --- a/drools-core/src/main/java/org/drools/reteoo/ObjectTypeNode.java +++ b/drools-core/src/main/java/org/drools/reteoo/ObjectTypeNode.java @@ -19,6 +19,7 @@ import java.io.Serializable; import org.drools.RuleBaseConfiguration; +import org.drools.base.ClassObjectType; import org.drools.base.ShadowProxy; import org.drools.common.BaseNode; import org.drools.common.InternalFactHandle; diff --git a/drools-core/src/main/java/org/drools/spi/FieldValue.java b/drools-core/src/main/java/org/drools/spi/FieldValue.java index 515f9af5ab0..18aeab09583 100644 --- a/drools-core/src/main/java/org/drools/spi/FieldValue.java +++ b/drools-core/src/main/java/org/drools/spi/FieldValue.java @@ -39,5 +39,13 @@ public interface FieldValue public double getDoubleValue(); public boolean getBooleanValue(); + + public boolean isBooleanField(); + + public boolean isIntegerNumberField(); + + public boolean isFloatNumberField(); + + public boolean isObjectField(); } \ No newline at end of file
4bb48156bc3c5c31ac6d93044315b8355f158f34
hbase
HBASE-1404 minor edit of regionserver logging- messages--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@773627 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index 31f690ffc002..c7292b783a3d 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -220,6 +220,7 @@ Release 0.20.0 - Unreleased HBASE-1397 Better distribution in the PerformanceEvaluation MapReduce when rows run to the Billions HBASE-1393 Narrow synchronization in HLog + HBASE-1404 minor edit of regionserver logging messages OPTIMIZATIONS diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HLog.java b/src/java/org/apache/hadoop/hbase/regionserver/HLog.java index 7c3b7733f4be..52748e18152e 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/HLog.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/HLog.java @@ -545,6 +545,11 @@ void optionalSync() { } } } + long took = System.currentTimeMillis() - now; + if (took > 1000) { + LOG.warn(Thread.currentThread().getName() + " took " + took + + "ms optional sync'ing HLog"); + } } } @@ -730,7 +735,7 @@ private static void splitLog(final Path rootDir, final FileStatus [] logfiles, // Check for possibly empty file. With appends, currently Hadoop reports // a zero length even if the file has been sync'd. Revisit if // HADOOP-4751 is committed. - boolean possiblyEmpty = logfiles[i].getLen() <= 0; + long length = logfiles[i].getLen(); HLogKey key = new HLogKey(); HLogEdit val = new HLogEdit(); try { @@ -807,7 +812,8 @@ private static void splitLog(final Path rootDir, final FileStatus [] logfiles, fs.delete(logfiles[i].getPath(), true); } } catch (IOException e) { - if (possiblyEmpty) { + if (length <= 0) { + LOG.warn("Empty log, continuing: " + logfiles[i]); continue; } throw e; diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java index bec6c36dfc08..a93a94cd3252 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java @@ -309,11 +309,6 @@ public void initialize(Path initialFiles, final Progressable reporter) // Add one to the current maximum sequence id so new edits are beyond. this.minSequenceId = maxSeqId + 1; - if (LOG.isDebugEnabled()) { - LOG.debug("Next sequence id for region " + - Bytes.toString(regionInfo.getRegionName()) + " is " + - this.minSequenceId); - } // Get rid of any splits or merges that were lost in-progress FSUtils.deleteDirectory(this.fs, new Path(regiondir, SPLITDIR)); @@ -328,7 +323,7 @@ public void initialize(Path initialFiles, final Progressable reporter) this.writestate.compacting = false; this.lastFlushTime = System.currentTimeMillis(); LOG.info("region " + this + "/" + this.regionInfo.getEncodedName() + - " available"); + " available; sequence id is " + this.minSequenceId); } /* @@ -742,8 +737,8 @@ boolean getForceMajorCompaction() { return splitRow; } } - LOG.info("starting " + (majorCompaction? "major" : "") + - " compaction on region " + this); + LOG.info("Starting" + (majorCompaction? " major " : " ") + + "compaction on region " + this); long startTime = System.currentTimeMillis(); doRegionCompactionPrep(); long maxSize = -1; @@ -1315,8 +1310,9 @@ public void batchUpdate(BatchUpdate b, Integer lockid, boolean writeToWAL) byte [] row = b.getRow(); // If we did not pass an existing row lock, obtain a new one Integer lid = getLock(lockid, row); + long now = System.currentTimeMillis(); long commitTime = b.getTimestamp() == LATEST_TIMESTAMP? - System.currentTimeMillis(): b.getTimestamp(); + now: b.getTimestamp(); Set<byte []> latestTimestampDeletes = null; List<KeyValue> edits = new ArrayList<KeyValue>(); try { diff --git a/src/java/org/apache/hadoop/hbase/regionserver/MemcacheFlusher.java b/src/java/org/apache/hadoop/hbase/regionserver/MemcacheFlusher.java index 881ed63e87e6..18c15f12b057 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/MemcacheFlusher.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/MemcacheFlusher.java @@ -222,16 +222,18 @@ void interruptIfNecessary() { * not flushed. */ private boolean flushRegion(HRegion region, boolean removeFromQueue) { - // Wait until it is safe to flush + // Wait until it is safe to flush. + // TODO: Fix. This block doesn't work if more than one store. int count = 0; boolean triggered = false; while (count++ < (blockingWaitTime / 500)) { for (Store hstore: region.stores.values()) { - if (hstore.getStorefilesCount() > this.blockingStoreFilesNumber) { + int files = hstore.getStorefilesCount(); + if (files > this.blockingStoreFilesNumber) { if (!triggered) { server.compactSplitThread.compactionRequested(region, getName()); - LOG.info("Too many store files for region " + region + ": " + - hstore.getStorefilesCount() + ", waiting"); + LOG.info("Too many store files in store " + hstore + ": " + + files + ", pausing"); triggered = true; } try { @@ -243,8 +245,7 @@ private boolean flushRegion(HRegion region, boolean removeFromQueue) { } } if (triggered) { - LOG.info("Compaction completed on region " + region + - ", proceeding"); + LOG.info("Compaction triggered on region " + region + ", proceeding"); } break; } diff --git a/src/java/org/apache/hadoop/hbase/regionserver/Store.java b/src/java/org/apache/hadoop/hbase/regionserver/Store.java index 07245659859c..041c17cdb690 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/Store.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/Store.java @@ -204,10 +204,6 @@ protected Store(Path basedir, HRegionInfo info, HColumnDescriptor family, // loadStoreFiles calculates this.maxSeqId. as side-effect. this.storefiles.putAll(loadStoreFiles()); - if (LOG.isDebugEnabled() && this.storefiles.size() > 0) { - LOG.debug("Loaded " + this.storefiles.size() + " file(s) in Store " + - Bytes.toString(this.storeName) + ", max sequence id " + this.maxSeqId); - } // Do reconstruction log. runReconstructionLog(reconstructionLog, this.maxSeqId, reporter); @@ -699,9 +695,9 @@ StoreSize compact(final boolean mc) throws IOException { // Move the compaction into place. completeCompaction(filesToCompact, writer); if (LOG.isDebugEnabled()) { - LOG.debug("Completed " + (majorcompaction? "major": "") + - " compaction of " + this.storeNameStr + - " store size is " + StringUtils.humanReadableInt(storeSize)); + LOG.debug("Completed" + (majorcompaction? " major ": " ") + + "compaction of " + this.storeNameStr + + "; store size is " + StringUtils.humanReadableInt(storeSize)); } } return checkSplit(forceSplit);
88a7e673b3ed7e07aa5cf31a1163697808a1f763
orientdb
Changed syntax for "create class" command. Now- wants the keyword "CLUSTER" and also accepts cluster names--
a
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java index 3e2f224a526..4ab42160331 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java +++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java @@ -194,7 +194,8 @@ public OClass createClass(final String iClassName, final OClass iSuperClass, fin cmd.append(iSuperClass.getName()); } - if (iClusterIds != null) + if (iClusterIds != null) { + cmd.append(" cluster "); for (int i = 0; i < iClusterIds.length; ++i) { if (i > 0) cmd.append(','); @@ -203,6 +204,7 @@ public OClass createClass(final String iClassName, final OClass iSuperClass, fin cmd.append(iClusterIds[i]); } + } getDatabase().command(new OCommandSQL(cmd.toString())).execute(); getDatabase().reload(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java index 4c889c6224d..66655e98eac 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java @@ -36,6 +36,7 @@ public class OCommandExecutorSQLCreateClass extends OCommandExecutorSQLPermissio public static final String KEYWORD_CREATE = "CREATE"; public static final String KEYWORD_CLASS = "CLASS"; public static final String KEYWORD_EXTENDS = "EXTENDS"; + public static final String KEYWORD_CLUSTER = "CLUSTER"; private String className; private OClass superClass; @@ -68,46 +69,54 @@ public OCommandExecutorSQLCreateClass parse(final OCommandRequestText iRequest) throw new OCommandSQLParsingException("Class " + className + " already exists", text, oldPos); oldPos = pos; - pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true); - if (pos > -1) { - if (word.toString().equals(KEYWORD_EXTENDS)) { + + while ((pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true)) > -1) { + final String k = word.toString(); + if (k.equals(KEYWORD_EXTENDS)) { oldPos = pos; pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, false); if (pos == -1) throw new OCommandSQLParsingException("Syntax error after EXTENDS for class " + className - + ". Expected the super-class name ", text, oldPos); + + ". Expected the super-class name", text, oldPos); if (!database.getMetadata().getSchema().existsClass(word.toString())) throw new OCommandSQLParsingException("Super-class " + word + " not exists", text, oldPos); superClass = database.getMetadata().getSchema().getClass(word.toString()); - + } else if (k.equals(KEYWORD_CLUSTER)) { oldPos = pos; pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, false); - } + if (pos == -1) + throw new OCommandSQLParsingException("Syntax error after CLUSTER for class " + className + + ". Expected the cluster id or name", text, oldPos); - if (pos > -1) { final String[] clusterIdsAsStrings = word.toString().split(","); if (clusterIdsAsStrings.length > 0) { clusterIds = new int[clusterIdsAsStrings.length]; for (int i = 0; i < clusterIdsAsStrings.length; ++i) { - clusterIds[i] = Integer.parseInt(clusterIdsAsStrings[i]); + if (Character.isDigit(clusterIdsAsStrings[i].charAt(0))) + // GET CLUSTER ID FROM NAME + clusterIds[i] = Integer.parseInt(clusterIdsAsStrings[i]); + else + // GET CLUSTER ID + clusterIds[i] = database.getStorage().getClusterIdByName(clusterIdsAsStrings[i]); + if (database.getStorage().getClusterById(clusterIds[i]) == null) throw new OCommandSQLParsingException("Cluster with id " + clusterIds[i] + " doesn't exists", text, oldPos); } } - } else { - final int clusterId = database.getStorage().getClusterIdByName(className); - if (clusterId > -1) { - clusterIds = new int[] { clusterId }; - } } - } else { + + oldPos = pos; + } + + if (clusterIds == null) { final int clusterId = database.getStorage().getClusterIdByName(className); if (clusterId > -1) { clusterIds = new int[] { clusterId }; } } + return this; }
3ed9f0f35aa82e04798ff4f35a32207787d78074
ReactiveX-RxJava
Added license header to OperationBuffer.--
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/operators/OperationBuffer.java b/rxjava-core/src/main/java/rx/operators/OperationBuffer.java index 55b63c47f0..913a7abe78 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationBuffer.java +++ b/rxjava-core/src/main/java/rx/operators/OperationBuffer.java @@ -1,3 +1,18 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package rx.operators; import java.util.ArrayList; @@ -925,8 +940,8 @@ public Subscription call(Observer<String> observer) { Observable<BufferOpening> openings = Observable.create(new Func1<Observer<BufferOpening>, Subscription>() { @Override public Subscription call(Observer<BufferOpening> observer) { - push(observer, new BufferOpenings(), 50); - push(observer, new BufferOpenings(), 200); + push(observer, BufferOpenings.create(), 50); + push(observer, BufferOpenings.create(), 200); complete(observer, 250); return Subscriptions.empty(); } @@ -938,7 +953,7 @@ public Observable<BufferClosing> call(BufferOpening opening) { return Observable.create(new Func1<Observer<BufferClosing>, Subscription>() { @Override public Subscription call(Observer<BufferClosing> observer) { - push(observer, new BufferClosings(), 100); + push(observer, BufferClosings.create(), 100); complete(observer, 101); return Subscriptions.empty(); } @@ -978,7 +993,7 @@ public Observable<BufferClosing> call() { return Observable.create(new Func1<Observer<BufferClosing>, Subscription>() { @Override public Subscription call(Observer<BufferClosing> observer) { - push(observer, new BufferClosings(), 100); + push(observer, BufferClosings.create(), 100); complete(observer, 101); return Subscriptions.empty(); }
5719e4098bc7fc5401d567284d1187d43304f03e
hbase
HBASE-11865 Result implements CellScannable;- rather it should BE a CellScanner--
p
https://github.com/apache/hbase
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/Result.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/Result.java index 74faab21b9e4..c6adabec86b6 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/Result.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/Result.java @@ -58,20 +58,23 @@ * * To get the latest value for a specific family and qualifier use {@link #getValue(byte[], byte[])}. * - * A Result is backed by an array of {@link KeyValue} objects, each representing + * A Result is backed by an array of {@link Cell} objects, each representing * an HBase cell defined by the row, family, qualifier, timestamp, and value.<p> * - * The underlying {@link KeyValue} objects can be accessed through the method {@link #listCells()}. - * Each KeyValue can then be accessed through - * {@link KeyValue#getRow()}, {@link KeyValue#getFamily()}, {@link KeyValue#getQualifier()}, - * {@link KeyValue#getTimestamp()}, and {@link KeyValue#getValue()}.<p> + * The underlying {@link Cell} objects can be accessed through the method {@link #listCells()}. + * This will create a List from the internal Cell []. Better is to exploit the fact that + * a new Result instance is a primed {@link CellScanner}; just call {@link #advance()} and + * {@link #current()} to iterate over Cells as you would any {@link CellScanner}. + * Call {@link #cellScanner()} to reset should you need to iterate the same Result over again + * ({@link CellScanner}s are one-shot). * - * If you need to overwrite a Result with another Result instance -- as in the old 'mapred' RecordReader next - * invocations -- then create an empty Result with the null constructor and in then use {@link #copyFrom(Result)} + * If you need to overwrite a Result with another Result instance -- as in the old 'mapred' + * RecordReader next invocations -- then create an empty Result with the null constructor and + * in then use {@link #copyFrom(Result)} */ @InterfaceAudience.Public @InterfaceStability.Stable -public class Result implements CellScannable { +public class Result implements CellScannable, CellScanner { private Cell[] cells; private Boolean exists; // if the query was just to check existence. private boolean stale = false; @@ -86,6 +89,13 @@ public class Result implements CellScannable { private static final int PAD_WIDTH = 128; public static final Result EMPTY_RESULT = new Result(); + private final static int INITIAL_CELLSCANNER_INDEX = -1; + + /** + * Index for where we are when Result is acting as a {@link CellScanner}. + */ + private int cellScannerIndex = INITIAL_CELLSCANNER_INDEX; + /** * Creates an empty Result w/ no KeyValue payload; returns null if you call {@link #rawCells()}. * Use this to represent no results if <code>null</code> won't do or in old 'mapred' as oppposed to 'mapreduce' package @@ -827,7 +837,21 @@ public void copyFrom(Result other) { @Override public CellScanner cellScanner() { - return CellUtil.createCellScanner(this.cells); + // Reset + this.cellScannerIndex = INITIAL_CELLSCANNER_INDEX; + return this; + } + + @Override + public Cell current() { + if (cells == null) return null; + return (cellScannerIndex < 0)? null: this.cells[cellScannerIndex]; + } + + @Override + public boolean advance() { + if (cells == null) return false; + return ++cellScannerIndex < this.cells.length; } public Boolean getExists() { @@ -846,5 +870,4 @@ public void setExists(Boolean exists) { public boolean isStale() { return stale; } - -} +} \ No newline at end of file diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestResult.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestResult.java index 74563f0f17ba..a0e1a45718c1 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestResult.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestResult.java @@ -21,6 +21,7 @@ import static org.apache.hadoop.hbase.HBaseTestCase.assertByteEquals; +import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; @@ -30,6 +31,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.CellScanner; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.SmallTests; @@ -60,6 +62,31 @@ static KeyValue[] genKVs(final byte[] row, final byte[] family, static final byte [] family = Bytes.toBytes("family"); static final byte [] value = Bytes.toBytes("value"); + /** + * Run some tests to ensure Result acts like a proper CellScanner. + * @throws IOException + */ + public void testResultAsCellScanner() throws IOException { + Cell [] cells = genKVs(row, family, value, 1, 10); + Arrays.sort(cells, KeyValue.COMPARATOR); + Result r = Result.create(cells); + assertSame(r, cells); + // Assert I run over same result multiple times. + assertSame(r.cellScanner(), cells); + assertSame(r.cellScanner(), cells); + // Assert we are not creating new object when doing cellscanner + assertTrue(r == r.cellScanner()); + } + + private void assertSame(final CellScanner cellScanner, final Cell [] cells) throws IOException { + int count = 0; + while (cellScanner.advance()) { + assertTrue(cells[count].equals(cellScanner.current())); + count++; + } + assertEquals(cells.length, count); + } + public void testBasicGetColumn() throws Exception { KeyValue [] kvs = genKVs(row, family, value, 1, 100);
c2c9352c0ca7e07fc8150f32295f93f667723b8c
restlet-framework-java
- Fixed bug in XstreamRepresentation- failing to use the DOM XML driver. Reported by Florian Georg.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt index 9e6d8e6478..ddbeabe918 100644 --- a/build/tmpl/text/changes.txt +++ b/build/tmpl/text/changes.txt @@ -46,6 +46,8 @@ Changes log Reported by Nicolas Janicaud. - Fixed potential NPE in ComponentHelper#checkVirtualHost. Reported by Matt J. Watson. + - Fixed bug in XstreamRepresentation failing to use the DOM + XML driver. Reported by Florian Georg. - Enhancements - Upgraded Jetty library to version 6.1.18. - SpringServerServlet nows gets its component fully configured, diff --git a/modules/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java b/modules/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java index 40e765e06a..56b9183259 100644 --- a/modules/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java +++ b/modules/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java @@ -118,7 +118,7 @@ protected XStream createXstream(MediaType mediaType) { result = new XStream(getJsonDriverClass().newInstance()); result.setMode(XStream.NO_REFERENCES); } else { - result = new XStream(getJsonDriverClass().newInstance()); + result = new XStream(getXmlDriverClass().newInstance()); } } catch (Exception e) { Context.getCurrentLogger().log(Level.WARNING,
a8806266b898ee71376ce9722de407ece9ed359a
hbase
HBASE-1200 Add bloomfilters--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@946464 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hbase
diff --git a/.gitignore b/.gitignore index 4208d615bea4..7b4653af1990 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ /core/build/ /core/test/ *.iml +*.orig +*~ diff --git a/CHANGES.txt b/CHANGES.txt index c5d529c21c82..f29ce0762193 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -653,6 +653,7 @@ Release 0.21.0 - Unreleased HBASE-2529 Make OldLogsCleaner easier to extend HBASE-2527 Add the ability to easily extend some HLog actions HBASE-2559 Set hbase.hregion.majorcompaction to 0 to disable + HBASE-1200 Add bloomfilters (Nicolas Spiegelberg via Stack) OPTIMIZATIONS HBASE-410 [testing] Speed up the test suite diff --git a/core/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java b/core/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java index 6269e3e57986..8e3bd5361f4e 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java +++ b/core/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java @@ -29,6 +29,8 @@ import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.io.hfile.Compression; import org.apache.hadoop.hbase.io.hfile.HFile; +import org.apache.hadoop.hbase.regionserver.StoreFile; +import org.apache.hadoop.hbase.regionserver.StoreFile.BloomType; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; @@ -50,7 +52,8 @@ public class HColumnDescriptor implements WritableComparable<HColumnDescriptor> // Version 5 was when bloom filter descriptors were removed. // Version 6 adds metadata as a map where keys and values are byte[]. // Version 7 -- add new compression and hfile blocksize to HColumnDescriptor (HBASE-1217) - private static final byte COLUMN_DESCRIPTOR_VERSION = (byte)7; + // Version 8 -- reintroduction of bloom filters, changed from boolean to enum + private static final byte COLUMN_DESCRIPTOR_VERSION = (byte)8; /** * The type of compression. @@ -113,7 +116,7 @@ public static enum CompressionType { /** * Default setting for whether or not to use bloomfilters. */ - public static final boolean DEFAULT_BLOOMFILTER = false; + public static final String DEFAULT_BLOOMFILTER = StoreFile.BloomType.NONE.toString(); /** * Default time to live of cell contents. @@ -166,7 +169,7 @@ public HColumnDescriptor(final byte [] familyName) { this (familyName == null || familyName.length <= 0? HConstants.EMPTY_BYTE_ARRAY: familyName, DEFAULT_VERSIONS, DEFAULT_COMPRESSION, DEFAULT_IN_MEMORY, DEFAULT_BLOCKCACHE, - DEFAULT_TTL, false); + DEFAULT_TTL, DEFAULT_BLOOMFILTER); } /** @@ -195,7 +198,7 @@ public HColumnDescriptor(HColumnDescriptor desc) { * @param blockCacheEnabled If true, MapFile blocks should be cached * @param timeToLive Time-to-live of cell contents, in seconds * (use HConstants.FOREVER for unlimited TTL) - * @param bloomFilter Enable the specified bloom filter for this column + * @param bloomFilter Bloom filter type for this column * * @throws IllegalArgumentException if passed a family name that is made of * other than 'word' characters: i.e. <code>[a-zA-Z_0-9]</code> or contains @@ -205,7 +208,7 @@ public HColumnDescriptor(HColumnDescriptor desc) { public HColumnDescriptor(final byte [] familyName, final int maxVersions, final String compression, final boolean inMemory, final boolean blockCacheEnabled, - final int timeToLive, final boolean bloomFilter) { + final int timeToLive, final String bloomFilter) { this(familyName, maxVersions, compression, inMemory, blockCacheEnabled, DEFAULT_BLOCKSIZE, timeToLive, bloomFilter, DEFAULT_REPLICATION_SCOPE); } @@ -222,7 +225,7 @@ public HColumnDescriptor(final byte [] familyName, final int maxVersions, * @param blocksize * @param timeToLive Time-to-live of cell contents, in seconds * (use HConstants.FOREVER for unlimited TTL) - * @param bloomFilter Enable the specified bloom filter for this column + * @param bloomFilter Bloom filter type for this column * @param scope The scope tag for this column * * @throws IllegalArgumentException if passed a family name that is made of @@ -233,7 +236,7 @@ public HColumnDescriptor(final byte [] familyName, final int maxVersions, public HColumnDescriptor(final byte [] familyName, final int maxVersions, final String compression, final boolean inMemory, final boolean blockCacheEnabled, final int blocksize, - final int timeToLive, final boolean bloomFilter, final int scope) { + final int timeToLive, final String bloomFilter, final int scope) { isLegalFamilyName(familyName); this.name = familyName; @@ -248,7 +251,8 @@ public HColumnDescriptor(final byte [] familyName, final int maxVersions, setTimeToLive(timeToLive); setCompressionType(Compression.Algorithm. valueOf(compression.toUpperCase())); - setBloomfilter(bloomFilter); + setBloomFilterType(StoreFile.BloomType. + valueOf(bloomFilter.toUpperCase())); setBlocksize(blocksize); setScope(scope); } @@ -464,20 +468,21 @@ public void setBlockCacheEnabled(boolean blockCacheEnabled) { } /** - * @return true if a bloom filter is enabled + * @return bloom filter type used for new StoreFiles in ColumnFamily */ - public boolean isBloomfilter() { - String value = getValue(BLOOMFILTER); - if (value != null) - return Boolean.valueOf(value).booleanValue(); - return DEFAULT_BLOOMFILTER; + public StoreFile.BloomType getBloomFilterType() { + String n = getValue(BLOOMFILTER); + if (n == null) { + n = DEFAULT_BLOOMFILTER; + } + return StoreFile.BloomType.valueOf(n.toUpperCase()); } /** - * @param onOff Enable/Disable bloom filter + * @param toggle bloom filter type */ - public void setBloomfilter(final boolean onOff) { - setValue(BLOOMFILTER, Boolean.toString(onOff)); + public void setBloomFilterType(final StoreFile.BloomType bt) { + setValue(BLOOMFILTER, bt.toString()); } /** @@ -513,10 +518,6 @@ public String toString() { values.entrySet()) { String key = Bytes.toString(e.getKey().get()); String value = Bytes.toString(e.getValue().get()); - if (key != null && key.toUpperCase().equals(BLOOMFILTER)) { - // Don't emit bloomfilter. Its not working. - continue; - } s.append(", "); s.append(key); s.append(" => '"); @@ -576,8 +577,8 @@ public void readFields(DataInput in) throws IOException { int ordinal = in.readInt(); setCompressionType(Compression.Algorithm.values()[ordinal]); setInMemory(in.readBoolean()); - setBloomfilter(in.readBoolean()); - if (isBloomfilter() && version < 5) { + setBloomFilterType(in.readBoolean() ? BloomType.ROW : BloomType.NONE); + if (getBloomFilterType() != BloomType.NONE && version < 5) { // If a bloomFilter is enabled and the column descriptor is less than // version 5, we need to skip over it to read the rest of the column // descriptor. There are no BloomFilterDescriptors written to disk for @@ -593,7 +594,7 @@ public void readFields(DataInput in) throws IOException { setTimeToLive(in.readInt()); } } else { - // version 7+ + // version 6+ this.name = Bytes.readByteArray(in); this.values.clear(); int numValues = in.readInt(); @@ -602,6 +603,15 @@ public void readFields(DataInput in) throws IOException { ImmutableBytesWritable value = new ImmutableBytesWritable(); key.readFields(in); value.readFields(in); + + // in version 8, the BloomFilter setting changed from bool to enum + if (version < 8 && Bytes.toString(key.get()).equals(BLOOMFILTER)) { + value.set(Bytes.toBytes( + Boolean.getBoolean(Bytes.toString(value.get())) + ? BloomType.ROW.toString() + : BloomType.NONE.toString())); + } + values.put(key, value); } if (version == 6) { diff --git a/core/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java b/core/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java index d0c220e9f404..0d57270ba040 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java +++ b/core/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java @@ -33,6 +33,7 @@ import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.io.hfile.Compression; +import org.apache.hadoop.hbase.regionserver.StoreFile; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.WritableComparable; @@ -667,7 +668,8 @@ public static Path getTableDir(Path rootdir, final byte [] tableName) { new HColumnDescriptor[] { new HColumnDescriptor(HConstants.CATALOG_FAMILY, 10, // Ten is arbitrary number. Keep versions to help debuggging. Compression.Algorithm.NONE.getName(), true, true, 8 * 1024, - HConstants.FOREVER, false, HConstants.REPLICATION_SCOPE_LOCAL) }); + HConstants.FOREVER, StoreFile.BloomType.NONE.toString(), + HConstants.REPLICATION_SCOPE_LOCAL) }); /** Table descriptor for <code>.META.</code> catalog table */ public static final HTableDescriptor META_TABLEDESC = new HTableDescriptor( @@ -675,9 +677,11 @@ public static Path getTableDir(Path rootdir, final byte [] tableName) { new HColumnDescriptor(HConstants.CATALOG_FAMILY, 10, // Ten is arbitrary number. Keep versions to help debuggging. Compression.Algorithm.NONE.getName(), true, true, 8 * 1024, - HConstants.FOREVER, false, HConstants.REPLICATION_SCOPE_LOCAL), + HConstants.FOREVER, StoreFile.BloomType.NONE.toString(), + HConstants.REPLICATION_SCOPE_LOCAL), new HColumnDescriptor(HConstants.CATALOG_HISTORIAN_FAMILY, HConstants.ALL_VERSIONS, Compression.Algorithm.NONE.getName(), false, false, 8 * 1024, - HConstants.WEEK_IN_SECONDS, false, HConstants.REPLICATION_SCOPE_LOCAL)}); + HConstants.WEEK_IN_SECONDS,StoreFile.BloomType.NONE.toString(), + HConstants.REPLICATION_SCOPE_LOCAL)}); } diff --git a/core/src/main/java/org/apache/hadoop/hbase/KeyValue.java b/core/src/main/java/org/apache/hadoop/hbase/KeyValue.java index 8aac19aa572e..fc5494b4a9eb 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/KeyValue.java +++ b/core/src/main/java/org/apache/hadoop/hbase/KeyValue.java @@ -945,7 +945,7 @@ public boolean isDeleteFamily() { System.arraycopy(this.bytes, o, result, 0, l); return result; } - + //--------------------------------------------------------------------------- // // KeyValue splitter @@ -1371,7 +1371,7 @@ int compareColumns(final KeyValue left, final short lrowlength, } /** - * Compares the row and column of two keyvalues + * Compares the row and column of two keyvalues for equality * @param left * @param right * @return True if same row and column. @@ -1380,10 +1380,10 @@ public boolean matchingRowColumn(final KeyValue left, final KeyValue right) { short lrowlength = left.getRowLength(); short rrowlength = right.getRowLength(); - if (!matchingRows(left, lrowlength, right, rrowlength)) { - return false; - } - return compareColumns(left, lrowlength, right, rrowlength) == 0; + // TsOffset = end of column data. just comparing Row+CF length of each + return left.getTimestampOffset() == right.getTimestampOffset() && + matchingRows(left, lrowlength, right, rrowlength) && + compareColumns(left, lrowlength, right, rrowlength) == 0; } /** @@ -1396,6 +1396,7 @@ public boolean matchingRows(final KeyValue left, final byte [] right) { } /** + * Compares the row of two keyvalues for equality * @param left * @param right * @return True if rows match. @@ -1415,11 +1416,8 @@ public boolean matchingRows(final KeyValue left, final KeyValue right) { */ public boolean matchingRows(final KeyValue left, final short lrowlength, final KeyValue right, final short rrowlength) { - int compare = compareRows(left, lrowlength, right, rrowlength); - if (compare != 0) { - return false; - } - return true; + return lrowlength == rrowlength && + compareRows(left, lrowlength, right, rrowlength) == 0; } public boolean matchingRows(final byte [] left, final int loffset, diff --git a/core/src/main/java/org/apache/hadoop/hbase/io/hfile/HFile.java b/core/src/main/java/org/apache/hadoop/hbase/io/hfile/HFile.java index 4488cccfd3ba..3433811a7eea 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/io/hfile/HFile.java +++ b/core/src/main/java/org/apache/hadoop/hbase/io/hfile/HFile.java @@ -30,6 +30,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.SortedSet; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; @@ -45,6 +46,7 @@ import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; +import org.apache.hadoop.hbase.KeyValue.KeyComparator; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.KeyValue; @@ -55,6 +57,7 @@ import org.apache.hadoop.hbase.util.FSUtils; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.RawComparator; +import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.compress.Compressor; import org.apache.hadoop.io.compress.Decompressor; @@ -209,7 +212,7 @@ public static class Writer implements Closeable { private long valuelength = 0; // Used to ensure we write in order. - private final RawComparator<byte []> comparator; + private final RawComparator<byte []> rawComparator; // A stream made per block written. private DataOutputStream out; @@ -239,7 +242,7 @@ public static class Writer implements Closeable { // Meta block system. private ArrayList<byte []> metaNames = new ArrayList<byte []>(); - private ArrayList<byte []> metaData = new ArrayList<byte[]>(); + private ArrayList<Writable> metaData = new ArrayList<Writable>(); // Used compression. Used even if no compression -- 'none'. private final Compression.Algorithm compressAlgo; @@ -273,7 +276,7 @@ public Writer(FileSystem fs, Path path) * @throws IOException */ public Writer(FileSystem fs, Path path, int blocksize, - String compress, final RawComparator<byte []> comparator) + String compress, final KeyComparator comparator) throws IOException { this(fs, path, blocksize, compress == null? DEFAULT_COMPRESSION_ALGORITHM: @@ -292,7 +295,7 @@ public Writer(FileSystem fs, Path path, int blocksize, */ public Writer(FileSystem fs, Path path, int blocksize, Compression.Algorithm compress, - final RawComparator<byte []> comparator) + final KeyComparator comparator) throws IOException { this(fs.create(path), blocksize, compress, comparator); this.closeOutputStream = true; @@ -309,7 +312,7 @@ public Writer(FileSystem fs, Path path, int blocksize, * @throws IOException */ public Writer(final FSDataOutputStream ostream, final int blocksize, - final String compress, final RawComparator<byte []> c) + final String compress, final KeyComparator c) throws IOException { this(ostream, blocksize, Compression.getCompressionAlgorithmByName(compress), c); @@ -324,12 +327,12 @@ public Writer(final FSDataOutputStream ostream, final int blocksize, * @throws IOException */ public Writer(final FSDataOutputStream ostream, final int blocksize, - final Compression.Algorithm compress, final RawComparator<byte []> c) + final Compression.Algorithm compress, final KeyComparator c) throws IOException { this.outputStream = ostream; this.closeOutputStream = false; this.blocksize = blocksize; - this.comparator = c == null? Bytes.BYTES_RAWCOMPARATOR: c; + this.rawComparator = c == null? Bytes.BYTES_RAWCOMPARATOR: c; this.name = this.outputStream.toString(); this.compressAlgo = compress == null? DEFAULT_COMPRESSION_ALGORITHM: compress; @@ -423,11 +426,21 @@ private int releaseCompressingStream(final DataOutputStream dos) * small, consider adding to file info using * {@link #appendFileInfo(byte[], byte[])} * @param metaBlockName name of the block - * @param bytes uninterpreted bytes of the block. + * @param content will call readFields to get data later (DO NOT REUSE) */ - public void appendMetaBlock(String metaBlockName, byte [] bytes) { - metaNames.add(Bytes.toBytes(metaBlockName)); - metaData.add(bytes); + public void appendMetaBlock(String metaBlockName, Writable content) { + byte[] key = Bytes.toBytes(metaBlockName); + int i; + for (i = 0; i < metaNames.size(); ++i) { + // stop when the current key is greater than our own + byte[] cur = metaNames.get(i); + if (this.rawComparator.compare(cur, 0, cur.length, key, 0, key.length) + > 0) { + break; + } + } + metaNames.add(i, key); + metaData.add(i, content); } /** @@ -508,7 +521,7 @@ public void append(final byte [] key, final byte [] value) * @param vlength * @throws IOException */ - public void append(final byte [] key, final int koffset, final int klength, + private void append(final byte [] key, final int koffset, final int klength, final byte [] value, final int voffset, final int vlength) throws IOException { boolean dupKey = checkKey(key, koffset, klength); @@ -552,7 +565,7 @@ private boolean checkKey(final byte [] key, final int offset, final int length) MAXIMUM_KEY_LENGTH); } if (this.lastKeyBuffer != null) { - int keyComp = this.comparator.compare(this.lastKeyBuffer, this.lastKeyOffset, + int keyComp = this.rawComparator.compare(this.lastKeyBuffer, this.lastKeyOffset, this.lastKeyLength, key, offset, length); if (keyComp > 0) { throw new IOException("Added a key not lexically larger than" + @@ -595,10 +608,16 @@ public void close() throws IOException { metaOffsets = new ArrayList<Long>(metaNames.size()); metaDataSizes = new ArrayList<Integer>(metaNames.size()); for (int i = 0 ; i < metaNames.size() ; ++ i ) { - metaOffsets.add(Long.valueOf(outputStream.getPos())); - metaDataSizes. - add(Integer.valueOf(METABLOCKMAGIC.length + metaData.get(i).length)); - writeMetaBlock(metaData.get(i)); + // store the beginning offset + long curPos = outputStream.getPos(); + metaOffsets.add(curPos); + // write the metadata content + DataOutputStream dos = getCompressingStream(); + dos.write(METABLOCKMAGIC); + metaData.get(i).write(dos); + int size = releaseCompressingStream(dos); + // store the metadata size + metaDataSizes.add(size); } } @@ -632,17 +651,6 @@ public void close() throws IOException { } } - /* Write a metadata block. - * @param metadata - * @throws IOException - */ - private void writeMetaBlock(final byte [] b) throws IOException { - DataOutputStream dos = getCompressingStream(); - dos.write(METABLOCKMAGIC); - dos.write(b); - releaseCompressingStream(dos); - } - /* * Add last bits of metadata to fileinfo and then write it out. * Reader will be expecting to find all below. @@ -668,7 +676,7 @@ private long writeFileInfo(FSDataOutputStream o) throws IOException { appendFileInfo(this.fileinfo, FileInfo.AVG_VALUE_LEN, Bytes.toBytes(avgValueLen), false); appendFileInfo(this.fileinfo, FileInfo.COMPARATOR, - Bytes.toBytes(this.comparator.getClass().getName()), false); + Bytes.toBytes(this.rawComparator.getClass().getName()), false); long pos = o.getPos(); this.fileinfo.write(o); return pos; @@ -710,6 +718,7 @@ public static class Reader implements Closeable { private final BlockCache cache; public int cacheHits = 0; public int blockLoads = 0; + public int metaLoads = 0; // Whether file is from in-memory store private boolean inMemory = false; @@ -717,15 +726,7 @@ public static class Reader implements Closeable { // Name for this object used when logging or in toString. Is either // the result of a toString on the stream or else is toString of passed // file Path plus metadata key/value pairs. - private String name; - - /* - * Do not expose the default constructor. - */ - @SuppressWarnings("unused") - private Reader() throws IOException { - this(null, -1, null, false); - } + protected String name; /** * Opens a HFile. You must load the file info before you can @@ -799,7 +800,8 @@ public boolean inMemory() { * See {@link Writer#appendFileInfo(byte[], byte[])}. * @throws IOException */ - public Map<byte [], byte []> loadFileInfo() throws IOException { + public Map<byte [], byte []> loadFileInfo() + throws IOException { this.trailer = readTrailer(); // Read in the fileinfo and get what we need from it. @@ -889,16 +891,19 @@ protected int blockContainingKey(final byte [] key, int offset, int length) { } /** * @param metaBlockName + * @param cacheBlock Add block to cache, if found * @return Block wrapped in a ByteBuffer * @throws IOException */ - public ByteBuffer getMetaBlock(String metaBlockName) throws IOException { + public ByteBuffer getMetaBlock(String metaBlockName, boolean cacheBlock) + throws IOException { if (trailer.metaIndexCount == 0) { return null; // there are no meta blocks } if (metaIndex == null) { throw new IOException("Meta index not loaded"); } + byte [] mbname = Bytes.toBytes(metaBlockName); int block = metaIndex.blockContainingKey(mbname, 0, mbname.length); if (block == -1) @@ -910,19 +915,45 @@ public ByteBuffer getMetaBlock(String metaBlockName) throws IOException { blockSize = metaIndex.blockOffsets[block+1] - metaIndex.blockOffsets[block]; } - ByteBuffer buf = decompress(metaIndex.blockOffsets[block], - longToInt(blockSize), metaIndex.blockDataSizes[block], true); - byte [] magic = new byte[METABLOCKMAGIC.length]; - buf.get(magic, 0, magic.length); + long now = System.currentTimeMillis(); - if (! Arrays.equals(magic, METABLOCKMAGIC)) { - throw new IOException("Meta magic is bad in block " + block); + // Per meta key from any given file, synchronize reads for said block + synchronized (metaIndex.blockKeys[block]) { + metaLoads++; + // Check cache for block. If found return. + if (cache != null) { + ByteBuffer cachedBuf = cache.getBlock(name + "meta" + block); + if (cachedBuf != null) { + // Return a distinct 'shallow copy' of the block, + // so pos doesnt get messed by the scanner + cacheHits++; + return cachedBuf.duplicate(); + } + // Cache Miss, please load. + } + + ByteBuffer buf = decompress(metaIndex.blockOffsets[block], + longToInt(blockSize), metaIndex.blockDataSizes[block], true); + byte [] magic = new byte[METABLOCKMAGIC.length]; + buf.get(magic, 0, magic.length); + + if (! Arrays.equals(magic, METABLOCKMAGIC)) { + throw new IOException("Meta magic is bad in block " + block); + } + + // Create a new ByteBuffer 'shallow copy' to hide the magic header + buf = buf.slice(); + + readTime += System.currentTimeMillis() - now; + readOps++; + + // Cache the block + if(cacheBlock && cache != null) { + cache.cacheBlock(name + "meta" + block, buf.duplicate(), inMemory); + } + + return buf; } - // Toss the header. May have to remove later due to performance. - buf.compact(); - buf.limit(buf.limit() - METABLOCKMAGIC.length); - buf.rewind(); - return buf; } /** @@ -952,8 +983,8 @@ ByteBuffer readBlock(int block, boolean cacheBlock, final boolean pread) if (cache != null) { ByteBuffer cachedBuf = cache.getBlock(name + block); if (cachedBuf != null) { - // Return a distinct 'copy' of the block, so pos doesnt get messed by - // the scanner + // Return a distinct 'shallow copy' of the block, + // so pos doesnt get messed by the scanner cacheHits++; return cachedBuf.duplicate(); } @@ -982,11 +1013,12 @@ ByteBuffer readBlock(int block, boolean cacheBlock, final boolean pread) if (!Arrays.equals(magic, DATABLOCKMAGIC)) { throw new IOException("Data magic is bad in block " + block); } - // Toss the header. May have to remove later due to performance. - buf.compact(); - buf.limit(buf.limit() - DATABLOCKMAGIC.length); - buf.rewind(); + // 'shallow copy' to hide the header + // NOTE: you WILL GET BIT if you call buf.array() but don't start + // reading at buf.arrayOffset() + buf = buf.slice(); + readTime += System.currentTimeMillis() - now; readOps++; @@ -1045,6 +1077,9 @@ private ByteBuffer decompress(final long offset, final int compressedSize, return this.blockIndex.isEmpty()? null: this.blockIndex.blockKeys[0]; } + /** + * @return number of KV entries in this HFile + */ public int getEntries() { if (!this.isFileInfoLoaded()) { throw new RuntimeException("File info not loaded"); @@ -1061,6 +1096,13 @@ public int getEntries() { } return this.blockIndex.isEmpty()? null: this.lastkey; } + + /** + * @return number of K entries in this HFile's filter. Returns KV count if no filter. + */ + public int getFilterEntries() { + return getEntries(); + } /** * @return Comparator. @@ -1099,7 +1141,7 @@ public void close() throws IOException { /* * Implementation of {@link HFileScanner} interface. */ - private static class Scanner implements HFileScanner { + protected static class Scanner implements HFileScanner { private final Reader reader; private ByteBuffer block; private int currBlock; @@ -1180,6 +1222,11 @@ public boolean next() throws IOException { return true; } + public boolean shouldSeek(final byte[] row, + final SortedSet<byte[]> columns) { + return true; + } + public int seekTo(byte [] key) throws IOException { return seekTo(key, 0, key.length); } @@ -1333,10 +1380,10 @@ public String getTrailerInfo() { * parts of the file. Also includes basic metadata on this file. */ private static class FixedFileTrailer { - // Offset to the data block index. - long dataIndexOffset; // Offset to the fileinfo data, a small block of vitals.. long fileinfoOffset; + // Offset to the data block index. + long dataIndexOffset; // How many index counts are there (aka: block count) int dataIndexCount; // Offset to the meta block index. diff --git a/core/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileScanner.java b/core/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileScanner.java index 9d891c6e68f3..f5a5dc0ce0f0 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileScanner.java +++ b/core/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileScanner.java @@ -21,6 +21,7 @@ import java.io.IOException; import java.nio.ByteBuffer; +import java.util.SortedSet; import org.apache.hadoop.hbase.KeyValue; @@ -64,6 +65,17 @@ public interface HFileScanner { */ public boolean seekBefore(byte [] key) throws IOException; public boolean seekBefore(byte []key, int offset, int length) throws IOException; + /** + * Optimization for single key lookups. If the file has a filter, + * perform a lookup on the key. + * @param row the row to scan + * @param family the column family to scan + * @param columns the array of column qualifiers to scan + * @return False if the key definitely does not exist in this ScanFile + * @throws IOException + */ + public boolean shouldSeek(final byte[] row, + final SortedSet<byte[]> columns); /** * Positions this scanner at the start of the file. * @return False if empty file; i.e. a call to next would return false and diff --git a/core/src/main/java/org/apache/hadoop/hbase/mapreduce/HFileOutputFormat.java b/core/src/main/java/org/apache/hadoop/hbase/mapreduce/HFileOutputFormat.java index 2c81723d365f..9c8e53ef9060 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/mapreduce/HFileOutputFormat.java +++ b/core/src/main/java/org/apache/hadoop/hbase/mapreduce/HFileOutputFormat.java @@ -112,7 +112,10 @@ private HFile.Writer getNewWriter(final HFile.Writer writer, private void close(final HFile.Writer w) throws IOException { if (w != null) { - StoreFile.appendMetadata(w, System.currentTimeMillis(), true); + w.appendFileInfo(StoreFile.MAX_SEQ_ID_KEY, + Bytes.toBytes(System.currentTimeMillis())); + w.appendFileInfo(StoreFile.MAJOR_COMPACTION_KEY, + Bytes.toBytes(true)); w.close(); } } diff --git a/core/src/main/java/org/apache/hadoop/hbase/regionserver/KeyValueHeap.java b/core/src/main/java/org/apache/hadoop/hbase/regionserver/KeyValueHeap.java index 716204ea51b9..70f42dc6fa3e 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/regionserver/KeyValueHeap.java +++ b/core/src/main/java/org/apache/hadoop/hbase/regionserver/KeyValueHeap.java @@ -51,7 +51,7 @@ public class KeyValueHeap implements KeyValueScanner, InternalScanner { * @param scanners * @param comparator */ - public KeyValueHeap(List<KeyValueScanner> scanners, KVComparator comparator) { + public KeyValueHeap(List<? extends KeyValueScanner> scanners, KVComparator comparator) { this.comparator = new KVScannerComparator(comparator); this.heap = new PriorityQueue<KeyValueScanner>(scanners.size(), this.comparator); diff --git a/core/src/main/java/org/apache/hadoop/hbase/regionserver/MinorCompactingStoreScanner.java b/core/src/main/java/org/apache/hadoop/hbase/regionserver/MinorCompactingStoreScanner.java index 2cb68cdd83b1..4b16540328f9 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/regionserver/MinorCompactingStoreScanner.java +++ b/core/src/main/java/org/apache/hadoop/hbase/regionserver/MinorCompactingStoreScanner.java @@ -33,23 +33,20 @@ * and optionally the memstore-snapshot. */ public class MinorCompactingStoreScanner implements KeyValueScanner, InternalScanner { - private KeyValueHeap heap; private KeyValue.KVComparator comparator; - MinorCompactingStoreScanner(Store store, - List<KeyValueScanner> scanners) { + MinorCompactingStoreScanner(Store store, List<? extends KeyValueScanner> scanners) { comparator = store.comparator; KeyValue firstKv = KeyValue.createFirstOnRow(HConstants.EMPTY_START_ROW); for (KeyValueScanner scanner : scanners ) { scanner.seek(firstKv); } - heap = new KeyValueHeap(scanners, store.comparator); } MinorCompactingStoreScanner(String cfName, KeyValue.KVComparator comparator, - List<KeyValueScanner> scanners) { + List<? extends KeyValueScanner> scanners) { this.comparator = comparator; KeyValue firstKv = KeyValue.createFirstOnRow(HConstants.EMPTY_START_ROW); diff --git a/core/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java b/core/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java index db4ae3b496fc..6c3153b7c622 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java +++ b/core/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java @@ -101,7 +101,7 @@ public class Store implements HConstants, HeapSize { private final HRegion region; private final HColumnDescriptor family; final FileSystem fs; - private final Configuration conf; + final Configuration conf; // ttl in milliseconds. protected long ttl; private long majorCompactionTime; @@ -144,7 +144,6 @@ public class Store implements HConstants, HeapSize { // Comparing KeyValues final KeyValue.KVComparator comparator; - final KeyValue.KVComparator comparatorIgnoringType; /** * Constructor @@ -179,7 +178,6 @@ protected Store(Path basedir, HRegion region, HColumnDescriptor family, this.blocksize = family.getBlocksize(); this.compression = family.getCompression(); this.comparator = info.getComparator(); - this.comparatorIgnoringType = this.comparator.getComparatorIgnoringType(); // getTimeToLive returns ttl in seconds. Convert to milliseconds. this.ttl = family.getTimeToLive(); if (ttl == HConstants.FOREVER) { @@ -415,7 +413,9 @@ private Map<Long, StoreFile> loadStoreFiles() } StoreFile curfile = null; try { - curfile = new StoreFile(fs, p, blockcache, this.conf, this.inMemory); + curfile = new StoreFile(fs, p, blockcache, this.conf, + this.family.getBloomFilterType(), this.inMemory); + curfile.createReader(); } catch (IOException ioe) { LOG.warn("Failed open of " + p + "; presumption is that file was " + "corrupted at flush and lost edits picked up by commit log replay. " + @@ -492,7 +492,7 @@ List<StoreFile> close() throws IOException { // Clear so metrics doesn't find them. this.storefiles.clear(); for (StoreFile f: result) { - f.close(); + f.closeReader(); } LOG.debug("closed " + this.storeNameStr); return result; @@ -534,7 +534,7 @@ private StoreFile flushCache(final long logCacheFlushId, private StoreFile internalFlushCache(final SortedSet<KeyValue> set, final long logCacheFlushId) throws IOException { - HFile.Writer writer = null; + StoreFile.Writer writer = null; long flushed = 0; // Don't flush if there are no entries. if (set.size() == 0) { @@ -546,7 +546,7 @@ private StoreFile internalFlushCache(final SortedSet<KeyValue> set, // if we fail. synchronized (flushLock) { // A. Write the map out to the disk - writer = getWriter(); + writer = createWriter(this.homedir, set.size()); int entries = 0; try { for (KeyValue kv: set) { @@ -559,13 +559,13 @@ private StoreFile internalFlushCache(final SortedSet<KeyValue> set, } finally { // Write out the log sequence number that corresponds to this output // hfile. The hfile is current up to and including logCacheFlushId. - StoreFile.appendMetadata(writer, logCacheFlushId); + writer.appendMetadata(logCacheFlushId, false); writer.close(); } } StoreFile sf = new StoreFile(this.fs, writer.getPath(), blockcache, - this.conf, this.inMemory); - Reader r = sf.getReader(); + this.conf, this.family.getBloomFilterType(), this.inMemory); + Reader r = sf.createReader(); this.storeSize += r.length(); if(LOG.isDebugEnabled()) { LOG.debug("Added " + sf + ", entries=" + r.getEntries() + @@ -577,22 +577,16 @@ private StoreFile internalFlushCache(final SortedSet<KeyValue> set, return sf; } - /** - * @return Writer for this store. - * @throws IOException - */ - HFile.Writer getWriter() throws IOException { - return getWriter(this.homedir); - } - /* * @return Writer for this store. * @param basedir Directory to put writer in. * @throws IOException */ - private HFile.Writer getWriter(final Path basedir) throws IOException { - return StoreFile.getWriter(this.fs, basedir, this.blocksize, - this.compression, this.comparator.getRawComparator()); + private StoreFile.Writer createWriter(final Path basedir, int maxKeyCount) + throws IOException { + return StoreFile.createWriter(this.fs, basedir, this.blocksize, + this.compression, this.comparator, this.conf, + this.family.getBloomFilterType(), maxKeyCount); } /* @@ -880,13 +874,25 @@ private boolean isMajorCompaction(final List<StoreFile> filesToCompact) private HFile.Writer compact(final List<StoreFile> filesToCompact, final boolean majorCompaction, final long maxId) throws IOException { + // calculate maximum key count after compaction (for blooms) + int maxKeyCount = 0; + for (StoreFile file : filesToCompact) { + StoreFile.Reader r = file.getReader(); + if (r != null) { + // NOTE: getFilterEntries could cause under-sized blooms if the user + // switches bloom type (e.g. from ROW to ROWCOL) + maxKeyCount += (r.getBloomFilterType() == family.getBloomFilterType()) + ? r.getFilterEntries() : r.getEntries(); + } + } + // For each file, obtain a scanner: - List<KeyValueScanner> scanners = StoreFileScanner.getScannersForStoreFiles( - filesToCompact, false, false); + List<StoreFileScanner> scanners = StoreFileScanner + .getScannersForStoreFiles(filesToCompact, false, false); // Make the instantiation lazy in case compaction produces no product; i.e. // where all source cells are expired or deleted. - HFile.Writer writer = null; + StoreFile.Writer writer = null; try { if (majorCompaction) { InternalScanner scanner = null; @@ -901,7 +907,7 @@ private HFile.Writer compact(final List<StoreFile> filesToCompact, // output to writer: for (KeyValue kv : kvs) { if (writer == null) { - writer = getWriter(this.regionCompactionDir); + writer = createWriter(this.regionCompactionDir, maxKeyCount); } writer.append(kv); } @@ -916,7 +922,7 @@ private HFile.Writer compact(final List<StoreFile> filesToCompact, MinorCompactingStoreScanner scanner = null; try { scanner = new MinorCompactingStoreScanner(this, scanners); - writer = getWriter(this.regionCompactionDir); + writer = createWriter(this.regionCompactionDir, maxKeyCount); while (scanner.next(writer)) { // Nothing to do } @@ -927,7 +933,7 @@ private HFile.Writer compact(final List<StoreFile> filesToCompact, } } finally { if (writer != null) { - StoreFile.appendMetadata(writer, maxId, majorCompaction); + writer.appendMetadata(maxId, majorCompaction); writer.close(); } } @@ -971,7 +977,9 @@ private StoreFile completeCompaction(final List<StoreFile> compactedFiles, LOG.error("Failed move of compacted file " + compactedFile.getPath(), e); return null; } - result = new StoreFile(this.fs, p, blockcache, this.conf, this.inMemory); + result = new StoreFile(this.fs, p, blockcache, this.conf, + this.family.getBloomFilterType(), this.inMemory); + result.createReader(); } this.lock.writeLock().lock(); try { @@ -1001,7 +1009,7 @@ private StoreFile completeCompaction(final List<StoreFile> compactedFiles, notifyChangedReadersObservers(); // Finally, delete old store files. for (StoreFile hsf: compactedFiles) { - hsf.delete(); + hsf.deleteReader(); } } catch (IOException e) { e = RemoteExceptionHandler.checkIOException(e); @@ -1570,7 +1578,7 @@ public boolean hasTooManyStoreFiles() { } public static final long FIXED_OVERHEAD = ClassSize.align( - ClassSize.OBJECT + (17 * ClassSize.REFERENCE) + + ClassSize.OBJECT + (16 * ClassSize.REFERENCE) + (6 * Bytes.SIZEOF_LONG) + (3 * Bytes.SIZEOF_INT) + Bytes.SIZEOF_BOOLEAN + ClassSize.align(ClassSize.ARRAY)); diff --git a/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreFile.java b/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreFile.java index 038c09e4f9cf..80bf09a19ad0 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreFile.java +++ b/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreFile.java @@ -21,26 +21,37 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; -import org.apache.hadoop.hbase.io.HalfHFileReader; +import org.apache.hadoop.hbase.KeyValue.KVComparator; +import org.apache.hadoop.hbase.KeyValue.KeyComparator; +import org.apache.hadoop.hbase.io.HalfStoreFileReader; import org.apache.hadoop.hbase.io.Reference; import org.apache.hadoop.hbase.io.hfile.BlockCache; import org.apache.hadoop.hbase.io.hfile.Compression; import org.apache.hadoop.hbase.io.hfile.HFile; -import org.apache.hadoop.hbase.io.hfile.HFile.Reader; +import org.apache.hadoop.hbase.io.hfile.HFileScanner; import org.apache.hadoop.hbase.io.hfile.LruBlockCache; +import org.apache.hadoop.hbase.util.BloomFilter; +import org.apache.hadoop.hbase.util.ByteBloomFilter; import org.apache.hadoop.hbase.util.Bytes; +import org.apache.hadoop.hbase.util.Hash; import org.apache.hadoop.util.StringUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; +import java.nio.ByteBuffer; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.Arrays; import java.util.Map; +import java.util.SortedSet; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; @@ -49,11 +60,11 @@ /** * A Store data file. Stores usually have one or more of these files. They * are produced by flushing the memstore to disk. To - * create, call {@link #getWriter(FileSystem, Path)} and append data. Be + * create, call {@link #createWriter(FileSystem, Path, int)} and append data. Be * sure to add any metadata before calling close on the Writer * (Use the appendMetadata convenience methods). On close, a StoreFile is * sitting in the Filesystem. To refer to it, create a StoreFile instance - * passing filesystem and path. To read, call {@link #getReader()}. + * passing filesystem and path. To read, call {@link #createReader()}. * <p>StoreFiles may also reference store files in another Store. */ public class StoreFile implements HConstants { @@ -65,7 +76,7 @@ public class StoreFile implements HConstants { // Make default block size for StoreFiles 8k while testing. TODO: FIX! // Need to make it 8k for testing. - private static final int DEFAULT_BLOCKSIZE_SMALL = 8 * 1024; + public static final int DEFAULT_BLOCKSIZE_SMALL = 8 * 1024; private final FileSystem fs; // This file's path. @@ -80,16 +91,23 @@ public class StoreFile implements HConstants { private boolean inMemory; // Keys for metadata stored in backing HFile. - private static final byte [] MAX_SEQ_ID_KEY = Bytes.toBytes("MAX_SEQ_ID_KEY"); + /** Constant for the max sequence ID meta */ + public static final byte [] MAX_SEQ_ID_KEY = Bytes.toBytes("MAX_SEQ_ID_KEY"); // Set when we obtain a Reader. private long sequenceid = -1; - private static final byte [] MAJOR_COMPACTION_KEY = + /** Constant for major compaction meta */ + public static final byte [] MAJOR_COMPACTION_KEY = Bytes.toBytes("MAJOR_COMPACTION_KEY"); // If true, this file was product of a major compaction. Its then set // whenever you get a Reader. private AtomicBoolean majorCompaction = null; + static final String BLOOM_FILTER_META_KEY = "BLOOM_FILTER_META"; + static final String BLOOM_FILTER_DATA_KEY = "BLOOM_FILTER_DATA"; + static final byte[] BLOOM_FILTER_TYPE_KEY = + Bytes.toBytes("BLOOM_FILTER_TYPE"); + /* * Regex that will work for straight filenames and for reference names. * If reference, then the regex has more than just one group. Group 1 is @@ -98,11 +116,12 @@ public class StoreFile implements HConstants { private static final Pattern REF_NAME_PARSER = Pattern.compile("^(\\d+)(?:\\.(.+))?$"); - private volatile HFile.Reader reader; + private volatile StoreFile.Reader reader; // Used making file ids. private final static Random rand = new Random(); private final Configuration conf; + private final BloomType bloomType; /** * Constructor, loads a reader and it's indices, etc. May allocate a @@ -112,10 +131,11 @@ public class StoreFile implements HConstants { * @param p The path of the file. * @param blockcache <code>true</code> if the block cache is enabled. * @param conf The current configuration. + * @param bt The bloom type to use for this store file * @throws IOException When opening the reader fails. */ StoreFile(final FileSystem fs, final Path p, final boolean blockcache, - final Configuration conf, final boolean inMemory) + final Configuration conf, final BloomType bt, final boolean inMemory) throws IOException { this.conf = conf; this.fs = fs; @@ -126,7 +146,14 @@ public class StoreFile implements HConstants { this.reference = Reference.read(fs, p); this.referencePath = getReferredToFile(this.path); } - this.reader = open(); + // ignore if the column family config says "no bloom filter" + // even if there is one in the hfile. + if (conf.getBoolean("io.hfile.bloom.enabled", true)) { + this.bloomType = bt; + } else { + this.bloomType = BloomType.NONE; + LOG.info("Ignoring bloom filter check for file (disabled in config)"); + } } /** @@ -255,18 +282,18 @@ public BlockCache getBlockCache() { * Opens reader on this store file. Called by Constructor. * @return Reader for the store file. * @throws IOException - * @see #close() + * @see #closeReader() */ - protected HFile.Reader open() + private StoreFile.Reader open() throws IOException { if (this.reader != null) { throw new IllegalAccessError("Already open"); } if (isReference()) { - this.reader = new HalfHFileReader(this.fs, this.referencePath, + this.reader = new HalfStoreFileReader(this.fs, this.referencePath, getBlockCache(), this.reference); } else { - this.reader = new Reader(this.fs, this.path, getBlockCache(), + this.reader = new StoreFile.Reader(this.fs, this.path, getBlockCache(), this.inMemory); } // Load up indices and fileinfo. @@ -296,44 +323,59 @@ protected HFile.Reader open() this.majorCompaction.set(mc); } } + + if (this.bloomType != BloomType.NONE) { + this.reader.loadBloomfilter(); + } - // TODO read in bloom filter here, ignore if the column family config says - // "no bloom filter" even if there is one in the hfile. + return this.reader; + } + + /** + * @return Reader for StoreFile. creates if necessary + * @throws IOException + */ + public StoreFile.Reader createReader() throws IOException { + if (this.reader == null) { + this.reader = open(); + } return this.reader; } /** - * @return Current reader. Must call open first else returns null. + * @return Current reader. Must call createReader first else returns null. + * @throws IOException + * @see {@link #createReader()} */ - public HFile.Reader getReader() { + public StoreFile.Reader getReader() { return this.reader; } /** * @throws IOException */ - public synchronized void close() throws IOException { + public synchronized void closeReader() throws IOException { if (this.reader != null) { this.reader.close(); this.reader = null; } } - @Override - public String toString() { - return this.path.toString() + - (isReference()? "-" + this.referencePath + "-" + reference.toString(): ""); - } - /** * Delete this file * @throws IOException */ - public void delete() throws IOException { - close(); + public void deleteReader() throws IOException { + closeReader(); this.fs.delete(getPath(), true); } + @Override + public String toString() { + return this.path.toString() + + (isReference()? "-" + this.referencePath + "-" + reference.toString(): ""); + } + /** * Utility to help with rename. * @param fs @@ -361,38 +403,47 @@ public static Path rename(final FileSystem fs, final Path src, * @param fs * @param dir Path to family directory. Makes the directory if doesn't exist. * Creates a file with a unique name in this directory. + * @param blocksize size per filesystem block * @return HFile.Writer * @throws IOException */ - public static HFile.Writer getWriter(final FileSystem fs, final Path dir) + public static StoreFile.Writer createWriter(final FileSystem fs, final Path dir, + final int blocksize) throws IOException { - return getWriter(fs, dir, DEFAULT_BLOCKSIZE_SMALL, null, null); + return createWriter(fs,dir,blocksize,null,null,null,BloomType.NONE,0); } /** - * Get a store file writer. Client is responsible for closing file when done. - * If metadata, add BEFORE closing using - * {@link #appendMetadata(org.apache.hadoop.hbase.io.hfile.HFile.Writer, long)}. + * Create a store file writer. Client is responsible for closing file when done. + * If metadata, add BEFORE closing using appendMetadata() * @param fs * @param dir Path to family directory. Makes the directory if doesn't exist. * Creates a file with a unique name in this directory. * @param blocksize * @param algorithm Pass null to get default. + * @param conf HBase system configuration. used with bloom filters + * @param bloomType column family setting for bloom filters * @param c Pass null to get default. + * @param maxKeySize peak theoretical entry size (maintains error rate) * @return HFile.Writer * @throws IOException */ - public static HFile.Writer getWriter(final FileSystem fs, final Path dir, - final int blocksize, final Compression.Algorithm algorithm, - final KeyValue.KeyComparator c) + public static StoreFile.Writer createWriter(final FileSystem fs, final Path dir, + final int blocksize, final Compression.Algorithm algorithm, + final KeyValue.KVComparator c, final Configuration conf, + BloomType bloomType, int maxKeySize) throws IOException { if (!fs.exists(dir)) { fs.mkdirs(dir); } Path path = getUniqueFile(fs, dir); - return new HFile.Writer(fs, path, blocksize, - algorithm == null? HFile.DEFAULT_COMPRESSION_ALGORITHM: algorithm, - c == null? KeyValue.KEY_COMPARATOR: c); + if(conf == null || !conf.getBoolean("io.hfile.bloom.enabled", true)) { + bloomType = BloomType.NONE; + } + + return new StoreFile.Writer(fs, path, blocksize, + algorithm == null? HFile.DEFAULT_COMPRESSION_ALGORITHM: algorithm, + conf, c == null? KeyValue.COMPARATOR: c, bloomType, maxKeySize); } /** @@ -442,35 +493,6 @@ static Path getRandomFilename(final FileSystem fs, final Path dir, return p; } - /** - * Write file metadata. - * Call before you call close on the passed <code>w</code> since its written - * as metadata to that file. - * - * @param w hfile writer - * @param maxSequenceId Maximum sequence id. - * @throws IOException - */ - static void appendMetadata(final HFile.Writer w, final long maxSequenceId) - throws IOException { - appendMetadata(w, maxSequenceId, false); - } - - /** - * Writes metadata. - * Call before you call close on the passed <code>w</code> since its written - * as metadata to that file. - * @param maxSequenceId Maximum sequence id. - * @param mc True if this file is product of a major compaction - * @throws IOException - */ - public static void appendMetadata(final HFile.Writer w, final long maxSequenceId, - final boolean mc) - throws IOException { - w.appendFileInfo(MAX_SEQ_ID_KEY, Bytes.toBytes(maxSequenceId)); - w.appendFileInfo(MAJOR_COMPACTION_KEY, Bytes.toBytes(mc)); - } - /* * Write out a split reference. * @param fs @@ -497,4 +519,298 @@ static Path split(final FileSystem fs, final Path splitDir, Path p = new Path(splitDir, f.getPath().getName() + "." + parentRegionName); return r.write(fs, p); } + + public static enum BloomType { + /** + * Bloomfilters disabled + */ + NONE, + /** + * Bloom enabled with Table row as Key + */ + ROW, + /** + * Bloom enabled with Table row & column (family+qualifier) as Key + */ + ROWCOL + } + + /** + * + */ + public static class Reader extends HFile.Reader { + /** Bloom Filter class. Caches only meta, pass in data */ + protected BloomFilter bloomFilter = null; + /** Type of bloom filter (e.g. ROW vs ROWCOL) */ + protected BloomType bloomFilterType; + + public Reader(FileSystem fs, Path path, BlockCache cache, + boolean inMemory) + throws IOException { + super(fs, path, cache, inMemory); + } + + public Reader(final FSDataInputStream fsdis, final long size, + final BlockCache cache, final boolean inMemory) { + super(fsdis,size,cache,inMemory); + bloomFilterType = BloomType.NONE; + } + + @Override + public Map<byte [], byte []> loadFileInfo() + throws IOException { + Map<byte [], byte []> fi = super.loadFileInfo(); + + byte[] b = fi.get(BLOOM_FILTER_TYPE_KEY); + if (b != null) { + bloomFilterType = BloomType.valueOf(Bytes.toString(b)); + } + + return fi; + } + + /** + * Load the bloom filter for this HFile into memory. + * Assumes the HFile has already been loaded + */ + public void loadBloomfilter() { + if (this.bloomFilter != null) { + return; // already loaded + } + + // see if bloom filter information is in the metadata + try { + ByteBuffer b = getMetaBlock(BLOOM_FILTER_META_KEY, false); + if (b != null) { + if (bloomFilterType == BloomType.NONE) { + throw new IOException("valid bloom filter type not found in FileInfo"); + } + this.bloomFilter = new ByteBloomFilter(b); + LOG.info("Loaded " + (bloomFilterType==BloomType.ROW? "row":"col") + + " bloom filter metadata for " + name); + } + } catch (IOException e) { + LOG.error("Error reading bloom filter meta -- proceeding without", e); + this.bloomFilter = null; + } catch (IllegalArgumentException e) { + LOG.error("Bad bloom filter meta -- proceeding without", e); + this.bloomFilter = null; + } + } + + BloomFilter getBloomFilter() { + return this.bloomFilter; + } + + /** + * @return bloom type information associated with this store file + */ + public BloomType getBloomFilterType() { + return this.bloomFilterType; + } + + @Override + public int getFilterEntries() { + return (this.bloomFilter != null) ? this.bloomFilter.getKeyCount() + : super.getFilterEntries(); + } + + @Override + public HFileScanner getScanner(boolean cacheBlocks, final boolean pread) { + return new Scanner(this, cacheBlocks, pread); + } + + protected class Scanner extends HFile.Reader.Scanner { + public Scanner(Reader r, boolean cacheBlocks, final boolean pread) { + super(r, cacheBlocks, pread); + } + + @Override + public boolean shouldSeek(final byte[] row, + final SortedSet<byte[]> columns) { + if (bloomFilter == null) { + return true; + } + + byte[] key; + switch(bloomFilterType) { + case ROW: + key = row; + break; + case ROWCOL: + if (columns.size() == 1) { + byte[] col = columns.first(); + key = Bytes.add(row, col); + break; + } + //$FALL-THROUGH$ + default: + return true; + } + + try { + ByteBuffer bloom = getMetaBlock(BLOOM_FILTER_DATA_KEY, true); + if (bloom != null) { + return bloomFilter.contains(key, bloom); + } + } catch (IOException e) { + LOG.error("Error reading bloom filter data -- proceeding without", + e); + bloomFilter = null; + } catch (IllegalArgumentException e) { + LOG.error("Bad bloom filter data -- proceeding without", e); + bloomFilter = null; + } + + return true; + } + + } + } + + /** + * + */ + public static class Writer extends HFile.Writer { + private final BloomFilter bloomFilter; + private final BloomType bloomType; + private KVComparator kvComparator; + private KeyValue lastKv = null; + private byte[] lastByteArray = null; + + /** + * Creates an HFile.Writer that also write helpful meta data. + * @param fs file system to write to + * @param path file name to create + * @param blocksize HDFS block size + * @param compress HDFS block compression + * @param conf user configuration + * @param comparator key comparator + * @param bloomType bloom filter setting + * @param maxKeys maximum amount of keys to add (for blooms) + * @throws IOException problem writing to FS + */ + public Writer(FileSystem fs, Path path, int blocksize, + Compression.Algorithm compress, final Configuration conf, + final KVComparator comparator, BloomType bloomType, int maxKeys) + throws IOException { + super(fs, path, blocksize, compress, comparator.getRawComparator()); + + this.kvComparator = comparator; + + if (bloomType != BloomType.NONE && conf != null) { + float err = conf.getFloat("io.hfile.bloom.error.rate", (float)0.01); + int maxFold = conf.getInt("io.hfile.bloom.max.fold", 7); + + this.bloomFilter = new ByteBloomFilter(maxKeys, err, + Hash.getHashType(conf), maxFold); + this.bloomFilter.allocBloom(); + this.bloomType = bloomType; + } else { + this.bloomFilter = null; + this.bloomType = BloomType.NONE; + } + } + + /** + * Writes meta data. + * Call before {@link #close()} since its written as meta data to this file. + * @param maxSequenceId Maximum sequence id. + * @param majorCompaction True if this file is product of a major compaction + * @throws IOException problem writing to FS + */ + public void appendMetadata(final long maxSequenceId, + final boolean majorCompaction) + throws IOException { + appendFileInfo(MAX_SEQ_ID_KEY, Bytes.toBytes(maxSequenceId)); + appendFileInfo(MAJOR_COMPACTION_KEY, Bytes.toBytes(majorCompaction)); + } + + @Override + public void append(final KeyValue kv) + throws IOException { + if (this.bloomFilter != null) { + // only add to the bloom filter on a new, unique key + boolean newKey = true; + if (this.lastKv != null) { + switch(bloomType) { + case ROW: + newKey = ! kvComparator.matchingRows(kv, lastKv); + break; + case ROWCOL: + newKey = ! kvComparator.matchingRowColumn(kv, lastKv); + break; + case NONE: + newKey = false; + } + } + if (newKey) { + /* + * http://2.bp.blogspot.com/_Cib_A77V54U/StZMrzaKufI/AAAAAAAAADo/ZhK7bGoJdMQ/s400/KeyValue.png + * Key = RowLen + Row + FamilyLen + Column [Family + Qualifier] + TimeStamp + * + * 2 Types of Filtering: + * 1. Row = Row + * 2. RowCol = Row + Qualifier + */ + switch (bloomType) { + case ROW: + this.bloomFilter.add(kv.getBuffer(), kv.getRowOffset(), + kv.getRowLength()); + break; + case ROWCOL: + // merge(row, qualifier) + int ro = kv.getRowOffset(); + int rl = kv.getRowLength(); + int qo = kv.getQualifierOffset(); + int ql = kv.getQualifierLength(); + byte [] result = new byte[rl + ql]; + System.arraycopy(kv.getBuffer(), ro, result, 0, rl); + System.arraycopy(kv.getBuffer(), qo, result, rl, ql); + + this.bloomFilter.add(result); + break; + default: + } + this.lastKv = kv; + } + } + super.append(kv); + } + + @Override + public void append(final byte [] key, final byte [] value) + throws IOException { + if (this.bloomFilter != null) { + // only add to the bloom filter on a new row + if(this.lastByteArray == null || !Arrays.equals(key, lastByteArray)) { + this.bloomFilter.add(key); + this.lastByteArray = key; + } + } + super.append(key, value); + } + + @Override + public void close() + throws IOException { + // make sure we wrote something to the bloom before adding it + if (this.bloomFilter != null && this.bloomFilter.getKeyCount() > 0) { + bloomFilter.finalize(); + if (this.bloomFilter.getMaxKeys() > 0) { + int b = this.bloomFilter.getByteSize(); + int k = this.bloomFilter.getKeyCount(); + int m = this.bloomFilter.getMaxKeys(); + StoreFile.LOG.info("Bloom added to HFile. " + b + "B, " + + k + "/" + m + " (" + NumberFormat.getPercentInstance().format( + ((double)k) / ((double)m)) + ")"); + } + appendMetaBlock(BLOOM_FILTER_META_KEY, bloomFilter.getMetaWriter()); + appendMetaBlock(BLOOM_FILTER_DATA_KEY, bloomFilter.getDataWriter()); + appendFileInfo(BLOOM_FILTER_TYPE_KEY, Bytes.toBytes(bloomType.toString())); + } + super.close(); + } + + } } diff --git a/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreFileScanner.java b/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreFileScanner.java index d9e866ad4951..52d228bbda80 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreFileScanner.java +++ b/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreFileScanner.java @@ -53,12 +53,12 @@ private StoreFileScanner(HFileScanner hfs) { * Return an array of scanners corresponding to the given * set of store files. */ - public static List<KeyValueScanner> getScannersForStoreFiles( + public static List<StoreFileScanner> getScannersForStoreFiles( Collection<StoreFile> filesToCompact, boolean cacheBlocks, boolean usePread) { - List<KeyValueScanner> scanners = - new ArrayList<KeyValueScanner>(filesToCompact.size()); + List<StoreFileScanner> scanners = + new ArrayList<StoreFileScanner>(filesToCompact.size()); for (StoreFile file : filesToCompact) { Reader r = file.getReader(); if (r == null) { @@ -72,6 +72,10 @@ public static List<KeyValueScanner> getScannersForStoreFiles( return scanners; } + public HFileScanner getHFileScanner() { + return this.hfs; + } + public String toString() { return "StoreFileScanner[" + hfs.toString() + ", cur=" + cur + "]"; } diff --git a/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java b/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java index 32daa7768df9..fde872c54b53 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java +++ b/core/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java @@ -61,10 +61,10 @@ class StoreScanner implements KeyValueScanner, InternalScanner, ChangedReadersOb store.versionsToReturn(scan.getMaxVersions())); this.isGet = scan.isGetScan(); - List<KeyValueScanner> scanners = getScanners(); + // pass columns = try to filter out unnecessary ScanFiles + List<KeyValueScanner> scanners = getScanners(scan, columns); // Seek all scanners to the initial key - // TODO if scan.isGetScan, use bloomfilters to skip seeking for(KeyValueScanner scanner : scanners) { scanner.seek(matcher.getStartKey()); } @@ -83,7 +83,7 @@ class StoreScanner implements KeyValueScanner, InternalScanner, ChangedReadersOb * @param scan the spec * @param scanners ancilliary scanners */ - StoreScanner(Store store, Scan scan, List<KeyValueScanner> scanners) { + StoreScanner(Store store, Scan scan, List<? extends KeyValueScanner> scanners) { this.store = store; this.cacheBlocks = false; this.isGet = false; @@ -124,9 +124,37 @@ class StoreScanner implements KeyValueScanner, InternalScanner, ChangedReadersOb private List<KeyValueScanner> getScanners() { // First the store file scanners Map<Long, StoreFile> map = this.store.getStorefiles().descendingMap(); + List<StoreFileScanner> sfScanners = StoreFileScanner + .getScannersForStoreFiles(map.values(), cacheBlocks, isGet); List<KeyValueScanner> scanners = - StoreFileScanner.getScannersForStoreFiles(map.values(), - cacheBlocks, isGet); + new ArrayList<KeyValueScanner>(sfScanners.size()+1); + scanners.addAll(sfScanners); + // Then the memstore scanners + scanners.addAll(this.store.memstore.getScanners()); + return scanners; + } + + /* + * @return List of scanners to seek, possibly filtered by StoreFile. + */ + private List<KeyValueScanner> getScanners(Scan scan, + final NavigableSet<byte[]> columns) { + // First the store file scanners + Map<Long, StoreFile> map = this.store.getStorefiles().descendingMap(); + List<StoreFileScanner> sfScanners = StoreFileScanner + .getScannersForStoreFiles(map.values(), cacheBlocks, isGet); + List<KeyValueScanner> scanners = + new ArrayList<KeyValueScanner>(sfScanners.size()+1); + + // exclude scan files that have failed file filters + for(StoreFileScanner sfs : sfScanners) { + if (isGet && + !sfs.getHFileScanner().shouldSeek(scan.getStartRow(), columns)) { + continue; // exclude this hfs + } + scanners.add(sfs); + } + // Then the memstore scanners scanners.addAll(this.store.memstore.getScanners()); return scanners; diff --git a/core/src/main/java/org/apache/hadoop/hbase/rest/model/ColumnSchemaModel.java b/core/src/main/java/org/apache/hadoop/hbase/rest/model/ColumnSchemaModel.java index 4547c469c98f..caf53683e95c 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/rest/model/ColumnSchemaModel.java +++ b/core/src/main/java/org/apache/hadoop/hbase/rest/model/ColumnSchemaModel.java @@ -146,16 +146,15 @@ public int __getBlocksize() { } /** - * @return true if the BLOOMFILTER attribute is present and true + * @return the value of the BLOOMFILTER attribute or its default if unset */ - public boolean __getBloomfilter() { + public String __getBloomfilter() { Object o = attrs.get(BLOOMFILTER); - return o != null ? - Boolean.valueOf(o.toString()) : HColumnDescriptor.DEFAULT_BLOOMFILTER; + return o != null ? o.toString() : HColumnDescriptor.DEFAULT_BLOOMFILTER; } /** - * @return the value of the COMPRESSION attribute or its default if it is unset + * @return the value of the COMPRESSION attribute or its default if unset */ public String __getCompression() { Object o = attrs.get(COMPRESSION); @@ -203,8 +202,8 @@ public void __setBlockcache(boolean value) { attrs.put(BLOCKCACHE, Boolean.toString(value)); } - public void __setBloomfilter(boolean value) { - attrs.put(BLOOMFILTER, Boolean.toString(value)); + public void __setBloomfilter(String value) { + attrs.put(BLOOMFILTER, value); } /** diff --git a/core/src/main/java/org/apache/hadoop/hbase/thrift/ThriftUtilities.java b/core/src/main/java/org/apache/hadoop/hbase/thrift/ThriftUtilities.java index 9be58d7d51eb..f319751a5c31 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/thrift/ThriftUtilities.java +++ b/core/src/main/java/org/apache/hadoop/hbase/thrift/ThriftUtilities.java @@ -26,6 +26,8 @@ import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.io.hfile.Compression; +import org.apache.hadoop.hbase.regionserver.StoreFile; +import org.apache.hadoop.hbase.regionserver.StoreFile.BloomType; import org.apache.hadoop.hbase.thrift.generated.ColumnDescriptor; import org.apache.hadoop.hbase.thrift.generated.IllegalArgument; import org.apache.hadoop.hbase.thrift.generated.TCell; @@ -47,10 +49,8 @@ static public HColumnDescriptor colDescFromThrift(ColumnDescriptor in) throws IllegalArgument { Compression.Algorithm comp = Compression.getCompressionAlgorithmByName(in.compression.toLowerCase()); - boolean bloom = false; - if (in.bloomFilterType.compareTo("NONE") != 0) { - bloom = true; - } + StoreFile.BloomType bt = + BloomType.valueOf(in.bloomFilterType); if (in.name == null || in.name.length <= 0) { throw new IllegalArgument("column name is empty"); @@ -58,7 +58,7 @@ static public HColumnDescriptor colDescFromThrift(ColumnDescriptor in) byte [] parsedName = KeyValue.parseColumn(in.name)[0]; HColumnDescriptor col = new HColumnDescriptor(parsedName, in.maxVersions, comp.getName(), in.inMemory, in.blockCacheEnabled, - in.timeToLive, bloom); + in.timeToLive, bt.toString()); return col; } @@ -77,7 +77,7 @@ static public ColumnDescriptor colDescFromHbase(HColumnDescriptor in) { col.compression = in.getCompression().toString(); col.inMemory = in.isInMemory(); col.blockCacheEnabled = in.isBlockCacheEnabled(); - col.bloomFilterType = Boolean.toString(in.isBloomfilter()); + col.bloomFilterType = in.getBloomFilterType().toString(); return col; } @@ -147,4 +147,4 @@ static public List<TRowResult> rowResultFromHBase(Result in) { Result [] result = { in }; return rowResultFromHBase(result); } -} \ No newline at end of file +} diff --git a/core/src/main/java/org/apache/hadoop/hbase/util/Hash.java b/core/src/main/java/org/apache/hadoop/hbase/util/Hash.java index 9e1d9e29fffe..0a533d9f4101 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/util/Hash.java +++ b/core/src/main/java/org/apache/hadoop/hbase/util/Hash.java @@ -106,16 +106,29 @@ public int hash(byte[] bytes) { * @return hash value */ public int hash(byte[] bytes, int initval) { - return hash(bytes, bytes.length, initval); + return hash(bytes, 0, bytes.length, initval); } /** * Calculate a hash using bytes from 0 to <code>length</code>, and * the provided seed value * @param bytes input bytes - * @param length length of the valid bytes to consider + * @param length length of the valid bytes after offset to consider * @param initval seed value * @return hash value */ - public abstract int hash(byte[] bytes, int length, int initval); + public int hash(byte[] bytes, int length, int initval) { + return hash(bytes, 0, length, initval); + } + + /** + * Calculate a hash using bytes from 0 to <code>length</code>, and + * the provided seed value + * @param bytes input bytes + * @param offset the offset into the array to start consideration + * @param length length of the valid bytes after offset to consider + * @param initval seed value + * @return hash value + */ + public abstract int hash(byte[] bytes, int offset, int length, int initval); } diff --git a/core/src/main/java/org/apache/hadoop/hbase/util/JenkinsHash.java b/core/src/main/java/org/apache/hadoop/hbase/util/JenkinsHash.java index 0c6c6070283c..1e673717c9f2 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/util/JenkinsHash.java +++ b/core/src/main/java/org/apache/hadoop/hbase/util/JenkinsHash.java @@ -80,11 +80,11 @@ private static long rot(long val, int pos) { */ @Override @SuppressWarnings("fallthrough") - public int hash(byte[] key, int nbytes, int initval) { + public int hash(byte[] key, int off, int nbytes, int initval) { int length = nbytes; long a, b, c; // We use longs because we don't have unsigned ints a = b = c = (0x00000000deadbeefL + length + initval) & INT_MASK; - int offset = 0; + int offset = off; for (; length > 12; offset += 12, length -= 12) { //noinspection PointlessArithmeticExpression a = (a + (key[offset + 0] & BYTE_MASK)) & INT_MASK; diff --git a/core/src/main/java/org/apache/hadoop/hbase/util/MurmurHash.java b/core/src/main/java/org/apache/hadoop/hbase/util/MurmurHash.java index fcf543e39b77..085bf1e34299 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/util/MurmurHash.java +++ b/core/src/main/java/org/apache/hadoop/hbase/util/MurmurHash.java @@ -35,7 +35,7 @@ public static Hash getInstance() { } @Override - public int hash(byte[] data, int length, int seed) { + public int hash(byte[] data, int offset, int length, int seed) { int m = 0x5bd1e995; int r = 24; @@ -44,7 +44,7 @@ public int hash(byte[] data, int length, int seed) { int len_4 = length >> 2; for (int i = 0; i < len_4; i++) { - int i_4 = i << 2; + int i_4 = (i << 2) + offset; int k = data[i_4 + 3]; k = k << 8; k = k | (data[i_4 + 2] & 0xff); @@ -63,16 +63,17 @@ public int hash(byte[] data, int length, int seed) { // avoid calculating modulo int len_m = len_4 << 2; int left = length - len_m; + int i_m = len_m + offset; if (left != 0) { if (left >= 3) { - h ^= data[len_m + 2] << 16; + h ^= data[i_m + 2] << 16; } if (left >= 2) { - h ^= data[len_m + 1] << 8; + h ^= data[i_m + 1] << 8; } if (left >= 1) { - h ^= data[len_m]; + h ^= data[i_m]; } h *= m; diff --git a/core/src/main/ruby/hbase/admin.rb b/core/src/main/ruby/hbase/admin.rb index 75490b739a9b..04da078aeb02 100644 --- a/core/src/main/ruby/hbase/admin.rb +++ b/core/src/main/ruby/hbase/admin.rb @@ -334,7 +334,7 @@ def hcd(arg) arg[HColumnDescriptor::BLOCKCACHE]? JBoolean.valueOf(arg[HColumnDescriptor::BLOCKCACHE]): HColumnDescriptor::DEFAULT_BLOCKCACHE, arg[HColumnDescriptor::BLOCKSIZE]? JInteger.valueOf(arg[HColumnDescriptor::BLOCKSIZE]): HColumnDescriptor::DEFAULT_BLOCKSIZE, arg[HColumnDescriptor::TTL]? JInteger.new(arg[HColumnDescriptor::TTL]): HColumnDescriptor::DEFAULT_TTL, - arg[HColumnDescriptor::BLOOMFILTER]? JBoolean.valueOf(arg[HColumnDescriptor::BLOOMFILTER]): HColumnDescriptor::DEFAULT_BLOOMFILTER, + arg[HColumnDescriptor::BLOOMFILTER]? arg[HColumnDescriptor::BLOOMFILTER]: HColumnDescriptor::DEFAULT_BLOOMFILTER) arg[HColumnDescriptor::REPLICATION_SCOPE]? JInteger.new(arg[REPLICATION_SCOPE]): HColumnDescriptor::DEFAULT_REPLICATION_SCOPE) end diff --git a/core/src/test/java/org/apache/hadoop/hbase/HBaseTestCase.java b/core/src/test/java/org/apache/hadoop/hbase/HBaseTestCase.java index 83be0974c0dd..e8c1d0cc960c 100644 --- a/core/src/test/java/org/apache/hadoop/hbase/HBaseTestCase.java +++ b/core/src/test/java/org/apache/hadoop/hbase/HBaseTestCase.java @@ -194,14 +194,19 @@ protected HTableDescriptor createTableDescriptor(final String name, HTableDescriptor htd = new HTableDescriptor(name); htd.addFamily(new HColumnDescriptor(fam1, versions, HColumnDescriptor.DEFAULT_COMPRESSION, false, false, - Integer.MAX_VALUE, HConstants.FOREVER, false, HConstants.REPLICATION_SCOPE_LOCAL)); + Integer.MAX_VALUE, HConstants.FOREVER, + HColumnDescriptor.DEFAULT_BLOOMFILTER, + HConstants.REPLICATION_SCOPE_LOCAL)); htd.addFamily(new HColumnDescriptor(fam2, versions, HColumnDescriptor.DEFAULT_COMPRESSION, false, false, - Integer.MAX_VALUE, HConstants.FOREVER, false, HConstants.REPLICATION_SCOPE_LOCAL)); + Integer.MAX_VALUE, HConstants.FOREVER, + HColumnDescriptor.DEFAULT_BLOOMFILTER, + HConstants.REPLICATION_SCOPE_LOCAL)); htd.addFamily(new HColumnDescriptor(fam3, versions, HColumnDescriptor.DEFAULT_COMPRESSION, false, false, Integer.MAX_VALUE, HConstants.FOREVER, - false, HConstants.REPLICATION_SCOPE_LOCAL)); + HColumnDescriptor.DEFAULT_BLOOMFILTER, + HConstants.REPLICATION_SCOPE_LOCAL)); return htd; } diff --git a/core/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java b/core/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java index a6aca1d85bae..f60010458cdd 100644 --- a/core/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java +++ b/core/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java @@ -333,7 +333,8 @@ public HTable createTable(byte[] tableName, byte[][] families, HColumnDescriptor.DEFAULT_IN_MEMORY, HColumnDescriptor.DEFAULT_BLOCKCACHE, Integer.MAX_VALUE, HColumnDescriptor.DEFAULT_TTL, - false, HColumnDescriptor.DEFAULT_REPLICATION_SCOPE); + HColumnDescriptor.DEFAULT_BLOOMFILTER, + HColumnDescriptor.DEFAULT_REPLICATION_SCOPE); desc.addFamily(hcd); } (new HBaseAdmin(getConfiguration())).createTable(desc); @@ -359,7 +360,8 @@ public HTable createTable(byte[] tableName, byte[][] families, HColumnDescriptor.DEFAULT_IN_MEMORY, HColumnDescriptor.DEFAULT_BLOCKCACHE, Integer.MAX_VALUE, HColumnDescriptor.DEFAULT_TTL, - false, HColumnDescriptor.DEFAULT_REPLICATION_SCOPE); + HColumnDescriptor.DEFAULT_BLOOMFILTER, + HColumnDescriptor.DEFAULT_REPLICATION_SCOPE); desc.addFamily(hcd); i++; } diff --git a/core/src/test/java/org/apache/hadoop/hbase/io/hfile/TestHFile.java b/core/src/test/java/org/apache/hadoop/hbase/io/hfile/TestHFile.java index 6b32b258878c..acb4fdc0455b 100644 --- a/core/src/test/java/org/apache/hadoop/hbase/io/hfile/TestHFile.java +++ b/core/src/test/java/org/apache/hadoop/hbase/io/hfile/TestHFile.java @@ -19,6 +19,8 @@ */ package org.apache.hadoop.hbase.io.hfile; +import java.io.DataInput; +import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; @@ -29,12 +31,14 @@ import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseTestCase; +import org.apache.hadoop.hbase.KeyValue.KeyComparator; import org.apache.hadoop.hbase.io.hfile.HFile.BlockIndex; import org.apache.hadoop.hbase.io.hfile.HFile.Reader; import org.apache.hadoop.hbase.io.hfile.HFile.Writer; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ClassSize; import org.apache.hadoop.io.RawComparator; +import org.apache.hadoop.io.Writable; /** * test hfile features. @@ -170,7 +174,18 @@ public void testTFileFeatures() throws IOException { private void writeNumMetablocks(Writer writer, int n) { for (int i = 0; i < n; i++) { - writer.appendMetaBlock("HFileMeta" + i, ("something to test" + i).getBytes()); + writer.appendMetaBlock("HFileMeta" + i, new Writable() { + private int val; + public Writable setVal(int val) { this.val = val; return this; } + + @Override + public void write(DataOutput out) throws IOException { + out.write(("something to test" + val).getBytes()); + } + + @Override + public void readFields(DataInput in) throws IOException { } + }.setVal(i)); } } @@ -180,10 +195,10 @@ private void someTestingWithMetaBlock(Writer writer) { private void readNumMetablocks(Reader reader, int n) throws IOException { for (int i = 0; i < n; i++) { - ByteBuffer b = reader.getMetaBlock("HFileMeta" + i); - byte [] found = Bytes.toBytes(b); - assertTrue("failed to match metadata", Arrays.equals( - ("something to test" + i).getBytes(), found)); + ByteBuffer actual = reader.getMetaBlock("HFileMeta" + i, false); + ByteBuffer expected = + ByteBuffer.wrap(("something to test" + i).getBytes()); + assertTrue("failed to match metadata", actual.compareTo(expected) == 0); } } @@ -227,7 +242,7 @@ public void testNullMetaBlocks() throws Exception { fout.close(); Reader reader = new Reader(fs, mFile, null, false); reader.loadFileInfo(); - assertNull(reader.getMetaBlock("non-existant")); + assertNull(reader.getMetaBlock("non-existant", false)); } /** @@ -244,7 +259,7 @@ public void testComparator() throws IOException { Path mFile = new Path(ROOT_DIR, "meta.tfile"); FSDataOutputStream fout = createFSOutput(mFile); Writer writer = new Writer(fout, minBlockSize, (Compression.Algorithm) null, - new RawComparator<byte []>() { + new KeyComparator() { @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { diff --git a/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestScanner.java b/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestScanner.java index 142c14511832..7ff6a2e6c6c3 100644 --- a/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestScanner.java +++ b/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestScanner.java @@ -68,7 +68,8 @@ public class TestScanner extends HBaseTestCase { TESTTABLEDESC.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY, 10, // Ten is arbitrary number. Keep versions to help debuggging. Compression.Algorithm.NONE.getName(), false, true, 8 * 1024, - HConstants.FOREVER, false, HConstants.REPLICATION_SCOPE_LOCAL)); + HConstants.FOREVER, StoreFile.BloomType.NONE.toString(), + HConstants.REPLICATION_SCOPE_LOCAL)); } /** HRegionInfo for root region */ public static final HRegionInfo REGION_INFO = diff --git a/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestStore.java b/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestStore.java index 9f240f265b5e..d14a27fd1adf 100644 --- a/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestStore.java +++ b/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestStore.java @@ -134,8 +134,9 @@ public void testEmptyStoreFile() throws IOException { long seqid = f.getMaxSequenceId(); HBaseConfiguration c = new HBaseConfiguration(); FileSystem fs = FileSystem.get(c); - Writer w = StoreFile.getWriter(fs, storedir); - StoreFile.appendMetadata(w, seqid + 1); + StoreFile.Writer w = StoreFile.createWriter(fs, storedir, + StoreFile.DEFAULT_BLOCKSIZE_SMALL); + w.appendMetadata(seqid + 1, false); w.close(); this.store.close(); // Reopen it... should pick up two files diff --git a/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestStoreFile.java b/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestStoreFile.java index 0c6efde1bead..dcda84cce701 100644 --- a/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestStoreFile.java +++ b/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestStoreFile.java @@ -21,10 +21,13 @@ import java.io.IOException; import java.nio.ByteBuffer; +import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestCase; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; @@ -69,11 +72,11 @@ public void tearDown() throws Exception { */ public void testBasicHalfMapFile() throws Exception { // Make up a directory hierarchy that has a regiondir and familyname. - HFile.Writer writer = StoreFile.getWriter(this.fs, - new Path(new Path(this.testDir, "regionname"), "familyname"), - 2 * 1024, null, null); + HFile.Writer writer = StoreFile.createWriter(this.fs, + new Path(new Path(this.testDir, "regionname"), "familyname"), 2 * 1024); writeStoreFile(writer); - checkHalfHFile(new StoreFile(this.fs, writer.getPath(), true, conf, false)); + checkHalfHFile(new StoreFile(this.fs, writer.getPath(), true, conf, + StoreFile.BloomType.NONE, false)); } /* @@ -109,11 +112,11 @@ public void testReference() Path storedir = new Path(new Path(this.testDir, "regionname"), "familyname"); Path dir = new Path(storedir, "1234567890"); // Make a store file and write data to it. - HFile.Writer writer = StoreFile.getWriter(this.fs, dir, 8 * 1024, null, - null); + HFile.Writer writer = StoreFile.createWriter(this.fs, dir, 8 * 1024); writeStoreFile(writer); - StoreFile hsf = new StoreFile(this.fs, writer.getPath(), true, conf, false); - HFile.Reader reader = hsf.getReader(); + StoreFile hsf = new StoreFile(this.fs, writer.getPath(), true, conf, + StoreFile.BloomType.NONE, false); + HFile.Reader reader = hsf.createReader(); // Split on a row, not in middle of row. Midkey returned by reader // may be in middle of row. Create new one with empty column and // timestamp. @@ -123,10 +126,11 @@ public void testReference() byte [] finalRow = kv.getRow(); // Make a reference Path refPath = StoreFile.split(fs, dir, hsf, midRow, Range.top); - StoreFile refHsf = new StoreFile(this.fs, refPath, true, conf, false); + StoreFile refHsf = new StoreFile(this.fs, refPath, true, conf, + StoreFile.BloomType.NONE, false); // Now confirm that I can read from the reference and that it only gets // keys from top half of the file. - HFileScanner s = refHsf.getReader().getScanner(false, false); + HFileScanner s = refHsf.createReader().getScanner(false, false); for(boolean first = true; (!s.isSeeked() && s.seekTo()) || s.next();) { ByteBuffer bb = s.getKey(); kv = KeyValue.createKeyValueFromKey(bb); @@ -140,7 +144,7 @@ public void testReference() private void checkHalfHFile(final StoreFile f) throws IOException { - byte [] midkey = f.getReader().midkey(); + byte [] midkey = f.createReader().midkey(); KeyValue midKV = KeyValue.createKeyValueFromKey(midkey); byte [] midRow = midKV.getRow(); // Create top split. @@ -159,8 +163,10 @@ private void checkHalfHFile(final StoreFile f) Path bottomPath = StoreFile.split(this.fs, bottomDir, f, midRow, Range.bottom); // Make readers on top and bottom. - HFile.Reader top = new StoreFile(this.fs, topPath, true, conf, false).getReader(); - HFile.Reader bottom = new StoreFile(this.fs, bottomPath, true, conf, false).getReader(); + HFile.Reader top = new StoreFile(this.fs, topPath, true, conf, + StoreFile.BloomType.NONE, false).createReader(); + HFile.Reader bottom = new StoreFile(this.fs, bottomPath, true, conf, + StoreFile.BloomType.NONE, false).createReader(); ByteBuffer previous = null; LOG.info("Midkey: " + midKV.toString()); ByteBuffer bbMidkeyBytes = ByteBuffer.wrap(midkey); @@ -212,8 +218,10 @@ private void checkHalfHFile(final StoreFile f) topPath = StoreFile.split(this.fs, topDir, f, badmidkey, Range.top); bottomPath = StoreFile.split(this.fs, bottomDir, f, badmidkey, Range.bottom); - top = new StoreFile(this.fs, topPath, true, conf, false).getReader(); - bottom = new StoreFile(this.fs, bottomPath, true, conf, false).getReader(); + top = new StoreFile(this.fs, topPath, true, conf, + StoreFile.BloomType.NONE, false).createReader(); + bottom = new StoreFile(this.fs, bottomPath, true, conf, + StoreFile.BloomType.NONE, false).createReader(); bottomScanner = bottom.getScanner(false, false); int count = 0; while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) || @@ -256,8 +264,10 @@ private void checkHalfHFile(final StoreFile f) topPath = StoreFile.split(this.fs, topDir, f, badmidkey, Range.top); bottomPath = StoreFile.split(this.fs, bottomDir, f, badmidkey, Range.bottom); - top = new StoreFile(this.fs, topPath, true, conf, false).getReader(); - bottom = new StoreFile(this.fs, bottomPath, true, conf, false).getReader(); + top = new StoreFile(this.fs, topPath, true, conf, + StoreFile.BloomType.NONE, false).createReader(); + bottom = new StoreFile(this.fs, bottomPath, true, conf, + StoreFile.BloomType.NONE, false).createReader(); first = true; bottomScanner = bottom.getScanner(false, false); while ((!bottomScanner.isSeeked() && bottomScanner.seekTo()) || @@ -296,4 +306,138 @@ private void checkHalfHFile(final StoreFile f) fs.delete(f.getPath(), true); } } -} \ No newline at end of file + + private static String ROOT_DIR = + System.getProperty("test.build.data", "/tmp/TestStoreFile"); + private static String localFormatter = "%010d"; + + public void testBloomFilter() throws Exception { + FileSystem fs = FileSystem.getLocal(conf); + conf.setFloat("io.hfile.bloom.error.rate", (float)0.01); + conf.setBoolean("io.hfile.bloom.enabled", true); + + // write the file + Path f = new Path(ROOT_DIR, getName()); + StoreFile.Writer writer = new StoreFile.Writer(fs, f, + StoreFile.DEFAULT_BLOCKSIZE_SMALL, HFile.DEFAULT_COMPRESSION_ALGORITHM, + conf, KeyValue.COMPARATOR, StoreFile.BloomType.ROW, 2000); + + long now = System.currentTimeMillis(); + for (int i = 0; i < 2000; i += 2) { + String row = String.format(localFormatter, Integer.valueOf(i)); + KeyValue kv = new KeyValue(row.getBytes(), "family".getBytes(), + "col".getBytes(), now, "value".getBytes()); + writer.append(kv); + } + writer.close(); + + StoreFile.Reader reader = new StoreFile.Reader(fs, f, null, false); + reader.loadFileInfo(); + reader.loadBloomfilter(); + HFileScanner scanner = reader.getScanner(false, false); + + // check false positives rate + int falsePos = 0; + int falseNeg = 0; + for (int i = 0; i < 2000; i++) { + String row = String.format(localFormatter, Integer.valueOf(i)); + TreeSet<byte[]> columns = new TreeSet<byte[]>(); + columns.add("family:col".getBytes()); + + boolean exists = scanner.shouldSeek(row.getBytes(), columns); + if (i % 2 == 0) { + if (!exists) falseNeg++; + } else { + if (exists) falsePos++; + } + } + reader.close(); + fs.delete(f, true); + System.out.println("False negatives: " + falseNeg); + assertEquals(0, falseNeg); + System.out.println("False positives: " + falsePos); + assertTrue(falsePos < 2); + } + + public void testBloomTypes() throws Exception { + float err = (float) 0.01; + FileSystem fs = FileSystem.getLocal(conf); + conf.setFloat("io.hfile.bloom.error.rate", err); + conf.setBoolean("io.hfile.bloom.enabled", true); + + int rowCount = 50; + int colCount = 10; + int versions = 2; + + // run once using columns and once using rows + StoreFile.BloomType[] bt = + {StoreFile.BloomType.ROWCOL, StoreFile.BloomType.ROW}; + int[] expKeys = {rowCount*colCount, rowCount}; + // below line deserves commentary. it is expected bloom false positives + // column = rowCount*2*colCount inserts + // row-level = only rowCount*2 inserts, but failures will be magnified by + // 2nd for loop for every column (2*colCount) + float[] expErr = {2*rowCount*colCount*err, 2*rowCount*2*colCount*err}; + + for (int x : new int[]{0,1}) { + // write the file + Path f = new Path(ROOT_DIR, getName()); + StoreFile.Writer writer = new StoreFile.Writer(fs, f, + StoreFile.DEFAULT_BLOCKSIZE_SMALL, + HFile.DEFAULT_COMPRESSION_ALGORITHM, + conf, KeyValue.COMPARATOR, bt[x], expKeys[x]); + + long now = System.currentTimeMillis(); + for (int i = 0; i < rowCount*2; i += 2) { // rows + for (int j = 0; j < colCount*2; j += 2) { // column qualifiers + String row = String.format(localFormatter, Integer.valueOf(i)); + String col = String.format(localFormatter, Integer.valueOf(j)); + for (int k= 0; k < versions; ++k) { // versions + KeyValue kv = new KeyValue(row.getBytes(), + "family".getBytes(), ("col" + col).getBytes(), + now-k, Bytes.toBytes((long)-1)); + writer.append(kv); + } + } + } + writer.close(); + + StoreFile.Reader reader = new StoreFile.Reader(fs, f, null, false); + reader.loadFileInfo(); + reader.loadBloomfilter(); + HFileScanner scanner = reader.getScanner(false, false); + assertEquals(expKeys[x], reader.getBloomFilter().getKeyCount()); + + // check false positives rate + int falsePos = 0; + int falseNeg = 0; + for (int i = 0; i < rowCount*2; ++i) { // rows + for (int j = 0; j < colCount*2; ++j) { // column qualifiers + String row = String.format(localFormatter, Integer.valueOf(i)); + String col = String.format(localFormatter, Integer.valueOf(j)); + TreeSet<byte[]> columns = new TreeSet<byte[]>(); + columns.add(("col" + col).getBytes()); + + boolean exists = scanner.shouldSeek(row.getBytes(), columns); + boolean shouldRowExist = i % 2 == 0; + boolean shouldColExist = j % 2 == 0; + shouldColExist = shouldColExist || bt[x] == StoreFile.BloomType.ROW; + if (shouldRowExist && shouldColExist) { + if (!exists) falseNeg++; + } else { + if (exists) falsePos++; + } + } + } + reader.close(); + fs.delete(f, true); + System.out.println(bt[x].toString()); + System.out.println(" False negatives: " + falseNeg); + System.out.println(" False positives: " + falsePos); + assertEquals(0, falseNeg); + assertTrue(falsePos < 2*expErr[x]); + } + + } + +} diff --git a/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestWideScanner.java b/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestWideScanner.java index 7a7ec331a7d0..0d5a17a55ed9 100644 --- a/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestWideScanner.java +++ b/core/src/test/java/org/apache/hadoop/hbase/regionserver/TestWideScanner.java @@ -52,7 +52,8 @@ public class TestWideScanner extends HBaseTestCase { TESTTABLEDESC.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY, 10, // Ten is arbitrary number. Keep versions to help debuggging. Compression.Algorithm.NONE.getName(), false, true, 8 * 1024, - HConstants.FOREVER, false, HColumnDescriptor.DEFAULT_REPLICATION_SCOPE)); + HConstants.FOREVER, StoreFile.BloomType.NONE.toString(), + HColumnDescriptor.DEFAULT_REPLICATION_SCOPE)); } /** HRegionInfo for root region */ public static final HRegionInfo REGION_INFO = diff --git a/core/src/test/java/org/apache/hadoop/hbase/rest/model/TestColumnSchemaModel.java b/core/src/test/java/org/apache/hadoop/hbase/rest/model/TestColumnSchemaModel.java index 2c2ccc20ebd9..517b1421cef0 100644 --- a/core/src/test/java/org/apache/hadoop/hbase/rest/model/TestColumnSchemaModel.java +++ b/core/src/test/java/org/apache/hadoop/hbase/rest/model/TestColumnSchemaModel.java @@ -33,7 +33,7 @@ public class TestColumnSchemaModel extends TestCase { protected static final String COLUMN_NAME = "testcolumn"; protected static final boolean BLOCKCACHE = true; protected static final int BLOCKSIZE = 16384; - protected static final boolean BLOOMFILTER = false; + protected static final String BLOOMFILTER = "none"; protected static final String COMPRESSION = "GZ"; protected static final boolean IN_MEMORY = false; protected static final int TTL = 86400; @@ -42,7 +42,7 @@ public class TestColumnSchemaModel extends TestCase { protected static final String AS_XML = "<ColumnSchema name=\"testcolumn\"" + " BLOCKSIZE=\"16384\"" + - " BLOOMFILTER=\"false\"" + + " BLOOMFILTER=\"none\"" + " BLOCKCACHE=\"true\"" + " COMPRESSION=\"GZ\"" + " VERSIONS=\"1\"" +
4f19dccda7d8779636f6cc4752552d5b80cce8bb
intellij-community
implement open hash addressing in index leaf- page to avoid large moves--
p
https://github.com/JetBrains/intellij-community
diff --git a/platform/util/src/com/intellij/util/io/IntToIntBtree.java b/platform/util/src/com/intellij/util/io/IntToIntBtree.java index f918cf1e532ba..d836016675035 100644 --- a/platform/util/src/com/intellij/util/io/IntToIntBtree.java +++ b/platform/util/src/com/intellij/util/io/IntToIntBtree.java @@ -1,7 +1,10 @@ package com.intellij.util.io; +import gnu.trove.TIntIntHashMap; import org.jetbrains.annotations.Nullable; +import java.util.Arrays; + /** * Created by IntelliJ IDEA. * User: maximmossienko @@ -14,8 +17,12 @@ abstract class IntToIntBtree { final int pageSize; private final short maxInteriorNodes; + private final short maxLeafNodes; final BtreeIndexNodeView root; private int maxStepsSearched; + private int maxStepsSearchedInHash; + private int totalHashStepsSearched; + private int hashSearchRequests; private int pagesCount; private int count; private int movedMembersCount; @@ -23,7 +30,10 @@ abstract class IntToIntBtree { private final byte[] buffer; private boolean isLarge = true; private final ISimpleStorage storage; - private boolean offloadToSiblingsBeforeSplit = false; // TODO till effective insertion to page + private final boolean offloadToSiblingsBeforeSplit = false; // TODO till effective insertion to page + private final boolean indexNodeIsHashTable = true; + final int metaDataLeafPageLength; + final int hashPageCapacity; public IntToIntBtree(int _pageSize, int rootAddress, ISimpleStorage _storage, boolean initial) { pageSize = _pageSize; @@ -33,9 +43,34 @@ public IntToIntBtree(int _pageSize, int rootAddress, ISimpleStorage _storage, bo root = new BtreeIndexNodeView(this); root.setAddress(rootAddress); - int i = (pageSize - BtreePage.META_PAGE_LEN) / BtreeIndexNodeView.INTERIOR_SIZE - 1; + int i = (pageSize - BtreePage.RESERVED_META_PAGE_LEN) / BtreeIndexNodeView.INTERIOR_SIZE - 1; assert i < Short.MAX_VALUE && i % 2 == 0; maxInteriorNodes = (short)i; + + int metaPageLen = BtreePage.RESERVED_META_PAGE_LEN; + + if (indexNodeIsHashTable) { + ++i; + final double bitsPerState = BtreeIndexNodeView.haveDeleteState? 2d:1d; + while(Math.ceil(bitsPerState * i / 8) + i * BtreeIndexNodeView.INTERIOR_SIZE + BtreePage.RESERVED_META_PAGE_LEN > pageSize || + !isPrime(i) + ) { + i -= 2; + } + + hashPageCapacity = i; + metaPageLen = BtreePage.RESERVED_META_PAGE_LEN + (int)Math.ceil(bitsPerState * hashPageCapacity / 8); + i = (int)(hashPageCapacity * 0.8); + if ((i & 1) == 1) ++i; + } else { + hashPageCapacity = -1; + } + + metaDataLeafPageLength = metaPageLen; + + assert i > 0 && i % 2 == 0; + maxLeafNodes = (short) i; + pagesCount = 1; ((BtreePage)root).load(); @@ -45,6 +80,29 @@ public IntToIntBtree(int _pageSize, int rootAddress, ISimpleStorage _storage, bo } } + public void persistVars(BtreeDataStorage storage, boolean toDisk) { + maxStepsSearched = storage.persistInt(0, maxStepsSearched, toDisk); + pagesCount = storage.persistInt(4, pagesCount, toDisk); + movedMembersCount = storage.persistInt(8, movedMembersCount, toDisk); + maxStepsSearchedInHash = storage.persistInt(12, maxStepsSearchedInHash, toDisk); + count = storage.persistInt(16, count, toDisk); + hashSearchRequests = storage.persistInt(20, hashSearchRequests, toDisk); + totalHashStepsSearched = storage.persistInt(24, totalHashStepsSearched, toDisk); + } + + interface BtreeDataStorage { + int persistInt(int offset, int value, boolean toDisk); + } + + private static boolean isPrime(int val) { + if (val % 2 == 0) return false; + int maxDivisor = (int)Math.sqrt(val); + for(int i = 3; i <= maxDivisor; i+=2) { + if (val % i == 0) return false; + } + return true; + } + protected abstract int allocEmptyPage(); private int nextPage() { @@ -69,7 +127,7 @@ public void put(int key, int value) { if (index < 0) { ++count; - currentIndexNode.insert(key, value, -index - 1); + currentIndexNode.insert(key, value); } else { currentIndexNode.setAddressAt(index, value); } @@ -80,6 +138,7 @@ public int remove(int key) { //BtreeIndexNodeView currentIndexNode = new BtreeIndexNodeView(this); //currentIndexNode.setAddress(root.address); //int index = currentIndexNode.locate(key, false); + myAssert(BtreeIndexNodeView.haveDeleteState); throw new UnsupportedOperationException("Remove does not work yet "+key); } @@ -87,36 +146,12 @@ void setRootAddress(int newRootAddress) { root.setAddress(newRootAddress); } - public int getMaxStepsSearched() { - return maxStepsSearched; - } - - public void setMaxStepsSearched(int _maxStepsSearched) { - maxStepsSearched = _maxStepsSearched; - } - - public int getPageCount() { - return pagesCount; - } - - public void setPagesCount(int pagesCount) { - this.pagesCount = pagesCount; - } - - public int getMovedMembersCount() { - return movedMembersCount; - } - - public void setMovedMembersCount(int movedMembersCount) { - this.movedMembersCount = movedMembersCount; - } - void dumpStatistics() { - IOStatistics.dump("pagecount:" + pagesCount + ", height:" + maxStepsSearched + ", movedMembers:"+movedMembersCount); + IOStatistics.dump("pagecount:" + pagesCount + ", height:" + maxStepsSearched + ", movedMembers:"+movedMembersCount + + ", hash steps:" + maxStepsSearchedInHash + ", avg search in hash:" + (totalHashStepsSearched / hashSearchRequests)); } void doFlush() { - //pagesCache.clear(); } static void myAssert(boolean b) { @@ -127,12 +162,11 @@ static void myAssert(boolean b) { } static class BtreePage { + static final int RESERVED_META_PAGE_LEN = 8; + protected final IntToIntBtree btree; protected int address; private short myChildrenCount; - private byte[] buffer; - - // TODO link pages of the same height public BtreePage(IntToIntBtree btree) { this.btree = btree; @@ -143,89 +177,76 @@ void setAddress(int _address) { if (doSanityCheck) myAssert(_address % btree.pageSize == 0); address = _address; myChildrenCount = -1; - buffer = null; } - final short getChildrenCount() { + protected final boolean getFlag(int mask) { + return (btree.storage.get(address) & mask) == mask; + } + + protected final void setFlag(int mask, boolean flag) { + byte b = btree.storage.get(address); + if (flag) b |= mask; + else b &= ~mask; + btree.storage.put(address, b); + } + + protected final short getChildrenCount() { if (myChildrenCount == -1) { - myChildrenCount = (short)(((getByte(address + 1) & 0xFF) << 8) + (getByte(address + 2) & 0xFF)); + myChildrenCount = (short)(((btree.storage.get(address + 1) & 0xFF) << 8) + (btree.storage.get(address + 2) & 0xFF)); } return myChildrenCount; } - final void setChildrenCount(short value) { + protected final void setChildrenCount(short value) { myChildrenCount = value; - putByte(address + 1, (byte)((value >> 8) & 0xFF)); - putByte(address + 2, (byte)(value & 0xFF)); + btree.storage.put(address + 1, (byte)((value >> 8) & 0xFF)); + btree.storage.put(address + 2, (byte)(value & 0xFF)); } - protected final int getInt(int address) { - //getBytes(address, btree.typedBuffer, 0, 4); - //return Bits.getInt(btree.typedBuffer, 0); - return btree.storage.getInt(address); + protected final void setNextPage(int nextPage) { + putInt(address + 3, nextPage); } - protected final void putInt(int offset, int value) { - //Bits.putInt(btree.typedBuffer, 0, value); - //putBytes(offset, btree.typedBuffer, 0, 4); - btree.storage.putInt(offset, value); + // TODO: use it + protected final int getNextPage() { + return getInt(address + 3); } - protected final byte getByte(int address) { - return btree.storage.get(address); - //getBytes(address, btree.typedBuffer, 0, 1); - //return btree.typedBuffer[0]; + protected final int getInt(int address) { + return btree.storage.getInt(address); } - protected final void putByte(int address, byte b) { - btree.storage.put(address, b); - //btree.typedBuffer[0] = b; - //putBytes(address, btree.typedBuffer, 0, 1); + protected final void putInt(int offset, int value) { + btree.storage.putInt(offset, value); } protected final void getBytes(int address, byte[] dst, int offset, int length) { btree.storage.get(address, dst, offset, length); - //if (buffer == null) load(); - // - //int base = address - this.address; - //for(int i = 0; i < length; ++i) { - // dst[offset + i] = buffer[base + i]; - //} } private void load() { - //if (address == btree.root.address && btree.root != this) { - // buffer = ((BtreePage)btree.root).buffer; - //} else { - // buffer = btree.loadPage(address); - //} } protected final void putBytes(int address, byte[] src, int offset, int length) { btree.storage.put(address, src, offset, length); - //if (buffer == null) load(); - //int base = address - this.address; - //for(int i = 0; i < length; ++i) { - // buffer[base + i] = src[offset + i]; - //} } void sync() { - if (buffer != null) { - //btree.savePage(address, buffer); - } } - - static int META_PAGE_LEN = 8; - } +} // Leaf index node // (value_address {<0 if address in duplicates segment}, hash key) {getChildrenCount()} // (|next_node {<0} , hash key|) {getChildrenCount()} , next_node {<0} // next_node[i] is pointer to all less than hash_key[i] except for the last static class BtreeIndexNodeView extends BtreePage { + static final int INTERIOR_SIZE = 8; + static final int KEY_OFFSET = 4; + private boolean isIndexLeaf; private boolean isIndexLeafSet; + private boolean isHashedLeaf; + private boolean isHashedLeafSet; private static final int LARGE_MOVE_THRESHOLD = 5; BtreeIndexNodeView(IntToIntBtree btree) { @@ -236,34 +257,42 @@ static class BtreeIndexNodeView extends BtreePage { void setAddress(int _address) { super.setAddress(_address); isIndexLeafSet = false; + isHashedLeafSet = false; } - static int INTERIOR_SIZE = 8; + static final int HASH_FREE = 0; + static final int HASH_FULL = 1; + static final int HASH_REMOVED = 2; - // binary search with negative result means insertion index int search(int value) { - int hi = getChildrenCount() - 1; - int lo = 0; - - while(lo <= hi) { - int mid = lo + (hi - lo) / 2; - int keyAtMid = keyAt(mid); - - if (value > keyAtMid) { - lo = mid + 1; - } else if (value < keyAtMid) { - hi = mid - 1; - } else { - return mid; + if (isIndexLeaf() && isHashedLeaf()) { + return hashIndex(value); + } + else { + int hi = getChildrenCount() - 1; + int lo = 0; + + while(lo <= hi) { + int mid = lo + (hi - lo) / 2; + int keyAtMid = keyAt(mid); + + if (value > keyAtMid) { + lo = mid + 1; + } else if (value < keyAtMid) { + hi = mid - 1; + } else { + return mid; + } } + return -(lo + 1); } - return -(lo + 1); } final int addressAt(int i) { if (doSanityCheck) { short childrenCount = getChildrenCount(); - myAssert(i < childrenCount || (!isIndexLeaf() && i == childrenCount)); + if (isHashedLeaf()) myAssert(i < btree.hashPageCapacity); + else myAssert(i < childrenCount || (!isIndexLeaf() && i == childrenCount)); } return getInt(indexToOffset(i)); } @@ -272,38 +301,58 @@ private void setAddressAt(int i, int value) { int offset = indexToOffset(i); if (doSanityCheck) { short childrenCount = getChildrenCount(); - myAssert(i < childrenCount || (!isIndexLeaf() && i == childrenCount)); - myAssert(offset + 4 < address + btree.pageSize); - myAssert(offset >= address + META_PAGE_LEN); + final int metaPageLen; + + if (isHashedLeaf()) { + myAssert(i < btree.hashPageCapacity); + metaPageLen = btree.metaDataLeafPageLength; + } + else { + myAssert(i < childrenCount || (!isIndexLeaf() && i == childrenCount)); + metaPageLen = RESERVED_META_PAGE_LEN; + } + myAssert(offset + 4 <= address + btree.pageSize); + myAssert(offset >= address + metaPageLen); } putInt(offset, value); } private final int indexToOffset(int i) { - return address + i * INTERIOR_SIZE + META_PAGE_LEN; + return address + i * INTERIOR_SIZE + (isHashedLeaf() ? btree.metaDataLeafPageLength:RESERVED_META_PAGE_LEN); } - final int keyAt(int i) { - if (doSanityCheck) myAssert(i < getChildrenCount()); - return getInt(indexToOffset(i) + 4); + private final int keyAt(int i) { + if (doSanityCheck) { + if (isHashedLeaf()) myAssert(i < btree.hashPageCapacity); + else myAssert(i < getChildrenCount()); + } + return getInt(indexToOffset(i) + KEY_OFFSET); } private void setKeyAt(int i, int value) { - int offset = indexToOffset(i) + 4; + final int offset = indexToOffset(i) + KEY_OFFSET; if (doSanityCheck) { - myAssert(i < getChildrenCount()); - myAssert(offset + 4 < address + btree.pageSize); - myAssert(offset >= address + META_PAGE_LEN); + final int metaPageLen; + if (isHashedLeaf()) { + myAssert(i < btree.hashPageCapacity); + metaPageLen = btree.metaDataLeafPageLength; + } + else { + myAssert(i < getChildrenCount()); + metaPageLen = RESERVED_META_PAGE_LEN; + } + myAssert(offset + 4 <= address + btree.pageSize); + myAssert(offset >= address + metaPageLen); } putInt(offset, value); } - static int INDEX_LEAF_MASK = 0x1; + static final int INDEX_LEAF_MASK = 0x1; + static final int HASHED_LEAF_MASK = 0x2; - boolean isIndexLeaf() { + final boolean isIndexLeaf() { if (!isIndexLeafSet) { - byte b = getByte(address); - isIndexLeaf = (b & INDEX_LEAF_MASK) == INDEX_LEAF_MASK; + isIndexLeaf = getFlag(INDEX_LEAF_MASK); isIndexLeafSet = true; } return isIndexLeaf; @@ -311,14 +360,24 @@ boolean isIndexLeaf() { void setIndexLeaf(boolean value) { isIndexLeaf = value; - byte b = getByte(address); - if (value) b |= INDEX_LEAF_MASK; - else b &= ~INDEX_LEAF_MASK; - putByte(address, b); + setFlag(INDEX_LEAF_MASK, value); + } + + final boolean isHashedLeaf() { + if (!isHashedLeafSet) { + isHashedLeaf = getFlag(HASHED_LEAF_MASK); + isHashedLeafSet = true; + } + return isHashedLeaf; + } + + void setHashedLeaf(boolean value) { + isHashedLeaf = value; + setFlag(HASHED_LEAF_MASK, value); } final short getMaxChildrenCount() { - return btree.maxInteriorNodes; + return isIndexLeaf() ? btree.maxLeafNodes:btree.maxInteriorNodes; } final boolean isFull() { @@ -329,6 +388,29 @@ final boolean isFull() { return childrenCount == getMaxChildrenCount(); } + int[] exportKeys() { + assert isIndexLeaf(); + short childrenCount = getChildrenCount(); + int[] keys = new int[childrenCount]; + + if (isHashedLeaf()) { + getBytes(indexToOffset(0), btree.buffer, 0, btree.pageSize - btree.metaDataLeafPageLength); + int keyNumber = 0; + + for(int i = 0; i < btree.hashPageCapacity; ++i) { + if (hashGetState(i) == HASH_FULL) { + int key = Bits.getInt(btree.buffer, i * INTERIOR_SIZE + KEY_OFFSET); + keys[keyNumber++] = key; + } + } + } else { + for(int i = 0; i < childrenCount; ++i) { + keys[i] = keyAt(i); + } + } + return keys; + } + private int splitNode(int parentAddress) { if (doSanityCheck) { myAssert(isFull()); @@ -353,33 +435,64 @@ private int splitNode(int parentAddress) { boolean indexLeaf = isIndexLeaf(); newIndexNode.setIndexLeaf(indexLeaf); - short recordCount = getChildrenCount(); + int nextPage = getNextPage(); + setNextPage(newIndexNode.address); + newIndexNode.setNextPage(nextPage); + + final short recordCount = getChildrenCount(); - short recordCountInNewNode = (short)(recordCount - maxIndex); - newIndexNode.setChildrenCount(recordCountInNewNode); int medianKey; - if (btree.isLarge) { - final int bytesToMove = recordCountInNewNode * INTERIOR_SIZE; - getBytes(indexToOffset(maxIndex), btree.buffer, 0, bytesToMove); - newIndexNode.putBytes(newIndexNode.indexToOffset(0), btree.buffer, 0, bytesToMove); - } else { - for(int i = 0; i < recordCountInNewNode; ++i) { - newIndexNode.setAddressAt(i, addressAt(i + maxIndex)); - newIndexNode.setKeyAt(i, keyAt(i + maxIndex)); + if (indexLeaf && isHashedLeaf()) { + TIntIntHashMap map = new TIntIntHashMap(recordCount); + getBytes(indexToOffset(0), btree.buffer, 0, btree.pageSize - btree.metaDataLeafPageLength); + int[] keys = new int[recordCount]; + int keyNumber = 0; + + for(int i = 0; i < btree.hashPageCapacity; ++i) { + if (hashGetState(i) == HASH_FULL) { + int key = Bits.getInt(btree.buffer, i * INTERIOR_SIZE + KEY_OFFSET); + keys[keyNumber++] = key; + map.put(key, Bits.getInt(btree.buffer, i * INTERIOR_SIZE)); + hashSetState(i, HASH_FREE); + } } - } - if (indexLeaf) { - medianKey = newIndexNode.keyAt(0); + setChildrenCount((short)0); + newIndexNode.setChildrenCount((short)0); + + Arrays.sort(keys); + final int avg = keys.length / 2; + medianKey = keys[avg]; + + for(int i = 0; i < avg; ++i) { + insert(keys[i], map.get(keys[i])); + newIndexNode.insert(keys[avg + i], map.get(keys[avg + i])); + } } else { - newIndexNode.setAddressAt(recordCountInNewNode, addressAt(recordCount)); - --maxIndex; - medianKey = keyAt(maxIndex); // key count is odd (since children count is even) and middle key goes to parent + short recordCountInNewNode = (short)(recordCount - maxIndex); + newIndexNode.setChildrenCount(recordCountInNewNode); + + if (btree.isLarge) { + final int bytesToMove = recordCountInNewNode * INTERIOR_SIZE; + getBytes(indexToOffset(maxIndex), btree.buffer, 0, bytesToMove); + newIndexNode.putBytes(newIndexNode.indexToOffset(0), btree.buffer, 0, bytesToMove); + } else { + for(int i = 0; i < recordCountInNewNode; ++i) { + newIndexNode.setAddressAt(i, addressAt(i + maxIndex)); + newIndexNode.setKeyAt(i, keyAt(i + maxIndex)); + } + } + if (indexLeaf) { + medianKey = newIndexNode.keyAt(0); + } else { + newIndexNode.setAddressAt(recordCountInNewNode, addressAt(recordCount)); + --maxIndex; + medianKey = keyAt(maxIndex); // key count is odd (since children count is even) and middle key goes to parent + } + setChildrenCount(maxIndex); } - setChildrenCount(maxIndex); - if (parent != null) { if (doSanityCheck) { int medianKeyInParent = parent.search(medianKey); @@ -451,7 +564,7 @@ private boolean doOffloadToSiblings(BtreeIndexNodeView parent) { parent.dump("parent before"); } - sibling.insert(keyAt(0), addressAt(0), sibling.getChildrenCount()); + sibling.insert(keyAt(0), addressAt(0)); if (doSanityCheck) { sibling.dump("Left sibling after"); } @@ -508,7 +621,7 @@ private void insertToRightSibling(BtreeIndexNodeView parent, int indexInParent, } int lastChildIndex = getChildrenCount() - 1; - sibling.insert(keyAt(lastChildIndex), addressAt(lastChildIndex), 0); + sibling.insert(keyAt(lastChildIndex), addressAt(lastChildIndex)); if (doSanityCheck) { sibling.dump("Right sibling after"); } @@ -562,26 +675,42 @@ private int locate(int valueHC, boolean split) { } private void insert(int valueHC, int newValueId) { - int medianKeyInParent = search(valueHC); - myAssert(medianKeyInParent < 0); - insert(valueHC, newValueId, -medianKeyInParent - 1); - } - - private void insert(int valueHC, int newValueId, int index) { if (doSanityCheck) myAssert(!isFull()); - insertToNotFull(valueHC, newValueId, index); - } - - private void insertToNotFull(int valueHC, int newValueId, int index) { short recordCount = getChildrenCount(); if (doSanityCheck) myAssert(recordCount < getMaxChildrenCount()); + + final boolean indexLeaf = isIndexLeaf(); + + if (indexLeaf) { + if (recordCount == 0 && btree.indexNodeIsHashTable) { + setHashedLeaf(true); + } + + if (isHashedLeaf()) { + int index = hashInsertionIndex(valueHC); + + if (index < 0) { + index = -index - 1; + } + + setKeyAt(index, valueHC); + hashSetState(index, HASH_FULL); + setAddressAt(index, newValueId); + setChildrenCount((short)(recordCount + 1)); + sync(); + return; + } + } + + int medianKeyInParent = search(valueHC); + if (doSanityCheck) myAssert(medianKeyInParent < 0); + int index = -medianKeyInParent - 1; setChildrenCount((short)(recordCount + 1)); final int itemsToMove = recordCount - index; btree.movedMembersCount += itemsToMove; - // TODO Clever books tell us to use Btree for cheaper elements shifting within page - if (isIndexLeaf()) { + if (indexLeaf) { if (btree.isLarge && itemsToMove > LARGE_MOVE_THRESHOLD) { final int bytesToMove = itemsToMove * INTERIOR_SIZE; getBytes(indexToOffset(index), btree.buffer, 0, bytesToMove); @@ -625,5 +754,151 @@ private void insertToNotFull(int valueHC, int newValueId, int index) { sync(); } + + private int hashIndex(int value) { + int hash, probe, index; + + final int length = btree.hashPageCapacity; + hash = hash(value) & 0x7fffffff; + index = hash % length; + int state = hashGetState(index); + int total = 0; + + btree.hashSearchRequests++; + + if (state != HASH_FREE && + (state == HASH_REMOVED || keyAt(index) != value)) { + // see Knuth, p. 529 + probe = 1 + (hash % (length - 2)); + + do { + index -= probe; + if (index < 0) { + index += length; + } + state = hashGetState(index); + ++total; + } + while (state != HASH_FREE && + (state == HASH_REMOVED || keyAt(index) != value)); + } + + btree.maxStepsSearchedInHash = Math.max(btree.maxStepsSearchedInHash, total); + btree.totalHashStepsSearched += total; + + return state == HASH_FREE ? -1 : index; + } + + protected int hashInsertionIndex(int val) { + int hash, probe, index; + + final int length = btree.hashPageCapacity; + hash = hash(val) & 0x7fffffff; + index = hash % length; + btree.hashSearchRequests++; + + int state = hashGetState(index); + if (state == HASH_FREE) { + return index; // empty, all done + } + else if (state == HASH_FULL && keyAt(index) == val) { + return -index - 1; // already stored + } + else { // already FULL or REMOVED, must probe + // compute the double hash + probe = 1 + (hash % (length - 2)); + int total = 0; + + // starting at the natural offset, probe until we find an + // offset that isn't full. + do { + index -= probe; + if (index < 0) { + index += length; + } + + ++total; + state = hashGetState(index); + } + while (state == HASH_FULL && keyAt(index) != val); + + // if the index we found was removed: continue probing until we + // locate a free location or an element which equal()s the + // one we have. + if (state == HASH_REMOVED) { + int firstRemoved = index; + while (state != HASH_FREE && + (state == HASH_REMOVED || keyAt(index) != val)) { + index -= probe; + if (index < 0) { + index += length; + } + state = hashGetState(index); + ++total; + } + return state == HASH_FULL ? -index - 1 : firstRemoved; + } + + btree.maxStepsSearchedInHash = Math.max(btree.maxStepsSearchedInHash, total); + btree.totalHashStepsSearched += total; + + // if it's full, the key is already stored + return state == HASH_FULL ? -index - 1 : index; + } + } + + private final int hash(int val) { + return val * 0x278DDE6D; + } + + static final int STATE_MASK = 0x3; + static final int STATE_MASK_WITHOUT_DELETE = 0x1; + + private final int hashGetState(int index) { + byte b = btree.storage.get(hashOccupiedStatusByteOffset(index)); + if (haveDeleteState) { + return ((b & 0xFF) >> hashOccupiedStatusShift(index)) & STATE_MASK; + } else { + return ((b & 0xFF) >> hashOccupiedStatusShift(index)) & STATE_MASK_WITHOUT_DELETE; + } + } + + private final int hashOccupiedStatusShift(int index) { + if (haveDeleteState) { + return 6 - ((index & 0x3) << 1); + } else { + return 7 - (index & 0x7); + } + } + + private final int hashOccupiedStatusByteOffset(int index) { + if (haveDeleteState) { + return address + BtreePage.RESERVED_META_PAGE_LEN + (index >> 2); + } else { + return address + BtreePage.RESERVED_META_PAGE_LEN + (index >> 3); + } + } + + private static final boolean haveDeleteState = false; + + private void hashSetState(int index, int value) { + if (doSanityCheck) { + if (haveDeleteState) myAssert(value >= HASH_FREE && value <= HASH_REMOVED); + else myAssert(value >= HASH_FREE && value < HASH_REMOVED); + } + + int hashOccupiedStatusOffset = hashOccupiedStatusByteOffset(index); + byte b = btree.storage.get(hashOccupiedStatusOffset); + int shift = hashOccupiedStatusShift(index); + + if (haveDeleteState) { + b = (byte)(((b & 0xFF) & ~(STATE_MASK << shift)) | (value << shift)); + } else { + b = (byte)(((b & 0xFF) & ~(STATE_MASK_WITHOUT_DELETE << shift)) | (value << shift)); + } + btree.storage.put(hashOccupiedStatusOffset, b); + + if (doSanityCheck) myAssert(hashGetState(index) == value); + } } } diff --git a/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java b/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java index 8421f284b49d2..30f4a58734edf 100644 --- a/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java +++ b/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java @@ -27,7 +27,7 @@ public class PersistentBTreeEnumerator<Data> extends PersistentEnumeratorBase<Data> { private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.PersistentEnumerator"); protected static final int NULL_ID = 0; - private static final int PAGE_SIZE = IntToIntBtree.doSanityCheck ? 64:2048; + private static final int PAGE_SIZE = /*IntToIntBtree.doSanityCheck ? 64:*/2048; private static final int RECORD_SIZE = 4; private final byte[] myBuffer; @@ -101,13 +101,19 @@ private void storeVars(boolean toDisk) { private void storeBTreeVars(boolean toDisk) { if (btree != null) { - btree.setMaxStepsSearched(store(DATA_START + 36, btree.getMaxStepsSearched(), toDisk)); - btree.setPagesCount(store(DATA_START + 40, btree.getPageCount(), toDisk)); - btree.setMovedMembersCount(store(DATA_START + 44, btree.getMovedMembersCount(), toDisk)); + final int BTREE_DATA_START = DATA_START + 36; + btree.persistVars(new IntToIntBtree.BtreeDataStorage() { + @Override + public int persistInt(int offset, int value, boolean toDisk) { + return store(BTREE_DATA_START + offset, value, toDisk); + } + }, toDisk); } } private int store(int offset, int value, boolean toDisk) { + assert offset + 4 < PAGE_SIZE; + if (toDisk) { myStorage.putInt(offset, value); } else { @@ -170,9 +176,8 @@ public boolean traverseAllRecords(RecordsProcessor p) throws IOException { collectLeafPages(btree.root, leafPages); out: - for(IntToIntBtree.BtreeIndexNodeView value:leafPages) { - for(int i = 0; i < value.getChildrenCount(); ++i) { - int key = value.keyAt(i); + for(IntToIntBtree.BtreeIndexNodeView page:leafPages) { + for(int key:page.exportKeys()) { Integer record = btree.get(key); p.setCurrentKey(key); assert record != null; @@ -277,7 +282,7 @@ protected int enumerateImpl(final Data value, final boolean saveNewValue) throws int newValueId = writeData(value, valueHC); ++valuesCount; - if (valuesCount % 10000 == 0 && IOStatistics.DEBUG) { + if (valuesCount % 20000 == 0 && IOStatistics.DEBUG) { IOStatistics.dump("Index " + myFile + ", values " + diff --git a/platform/util/src/com/intellij/util/io/PersistentEnumerator.java b/platform/util/src/com/intellij/util/io/PersistentEnumerator.java index e8cc6cd927524..d6ed9b8f43fbe 100644 --- a/platform/util/src/com/intellij/util/io/PersistentEnumerator.java +++ b/platform/util/src/com/intellij/util/io/PersistentEnumerator.java @@ -182,7 +182,7 @@ protected int writeData(final Data value, int hashCode) { int id = super.writeData(value, hashCode); ++valuesCount; - if (valuesCount % 10000 == 0 && IOStatistics.DEBUG) { + if (valuesCount % 20000 == 0 && IOStatistics.DEBUG) { IOStatistics.dump("Index " + myFile + ", values " + valuesCount + ", storage size:" + myStorage.length()); } return id;
eef90a46040c6b4018b699dfc96cb4bc8bc4e82e
hbase
HBASE-5927 SSH and DisableTableHandler happening- together does not clear the znode of the region and RIT map (Rajesh)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1339913 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java b/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java index bf93970186ed..e6796174cfd7 100644 --- a/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java +++ b/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java @@ -2124,7 +2124,11 @@ public void unassign(HRegionInfo region, boolean force){ unassign(region, force, null); } - private void deleteClosingOrClosedNode(HRegionInfo region) { + /** + * + * @param region regioninfo of znode to be deleted. + */ + public void deleteClosingOrClosedNode(HRegionInfo region) { try { if (!ZKAssign.deleteNode(master.getZooKeeper(), region.getEncodedName(), EventHandler.EventType.M_ZK_REGION_CLOSING)) { diff --git a/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java b/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java index 06da2ce679e3..dde71b225688 100644 --- a/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java +++ b/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java @@ -288,10 +288,10 @@ public void process() throws IOException { if (hris != null) { List<HRegionInfo> toAssignRegions = new ArrayList<HRegionInfo>(); for (Map.Entry<HRegionInfo, Result> e: hris.entrySet()) { + RegionState rit = this.services.getAssignmentManager().isRegionInTransition(e.getKey()); if (processDeadRegion(e.getKey(), e.getValue(), this.services.getAssignmentManager(), this.server.getCatalogTracker())) { - RegionState rit = this.services.getAssignmentManager().isRegionInTransition(e.getKey()); ServerName addressFromAM = this.services.getAssignmentManager() .getRegionServerOfRegion(e.getKey()); if (rit != null && !rit.isClosing() && !rit.isPendingClose()) { @@ -308,6 +308,22 @@ public void process() throws IOException { toAssignRegions.add(e.getKey()); } } + // If the table was partially disabled and the RS went down, we should clear the RIT + // and remove the node for the region. + // The rit that we use may be stale in case the table was in DISABLING state + // but though we did assign we will not be clearing the znode in CLOSING state. + // Doing this will have no harm. See HBASE-5927 + if (rit != null + && (rit.isClosing() || rit.isPendingClose()) + && this.services.getAssignmentManager().getZKTable() + .isDisablingOrDisabledTable(rit.getRegion().getTableNameAsString())) { + HRegionInfo hri = rit.getRegion(); + AssignmentManager am = this.services.getAssignmentManager(); + am.deleteClosingOrClosedNode(hri); + am.regionOffline(hri); + // To avoid region assignment if table is in disabling or disabled state. + toAssignRegions.remove(hri); + } } // Get all available servers List<ServerName> availableServers = services.getServerManager() diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManager.java b/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManager.java index 32c3009b7e18..36be722b4c6b 100644 --- a/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManager.java +++ b/src/test/java/org/apache/hadoop/hbase/master/TestAssignmentManager.java @@ -35,6 +35,8 @@ import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.ServerLoad; +import org.apache.hadoop.hbase.master.AssignmentManager.RegionState; +import org.apache.hadoop.hbase.master.AssignmentManager.RegionState.State; import org.apache.hadoop.hbase.MediumTests; import org.apache.hadoop.hbase.RegionTransition; import org.apache.hadoop.hbase.Server; @@ -53,6 +55,7 @@ import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetResponse; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest; +import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.Table; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse; import org.apache.hadoop.hbase.regionserver.RegionOpeningState; import org.apache.hadoop.hbase.util.Bytes; @@ -399,44 +402,72 @@ public void testShutdownHandler() AssignmentManager am = new AssignmentManager(this.server, this.serverManager, ct, balancer, executor, null); try { - // Make sure our new AM gets callbacks; once registered, can't unregister. - // Thats ok because we make a new zk watcher for each test. - this.watcher.registerListenerFirst(am); + processServerShutdownHandler(ct, am); + } finally { + executor.shutdown(); + am.shutdown(); + // Clean up all znodes + ZKAssign.deleteAllNodes(this.watcher); + } + } - // Need to set up a fake scan of meta for the servershutdown handler - // Make an RS Interface implementation. Make it so a scanner can go against it. - ClientProtocol implementation = Mockito.mock(ClientProtocol.class); - // Get a meta row result that has region up on SERVERNAME_A - Result r = Mocking.getMetaTableRowResult(REGIONINFO, SERVERNAME_A); - ScanResponse.Builder builder = ScanResponse.newBuilder(); - builder.setMoreResults(false); - builder.addResult(ProtobufUtil.toResult(r)); - Mockito.when(implementation.scan( - (RpcController)Mockito.any(), (ScanRequest)Mockito.any())). - thenReturn(builder.build()); - - // Get a connection w/ mocked up common methods. - HConnection connection = - HConnectionTestingUtility.getMockedConnectionAndDecorate(HTU.getConfiguration(), - null, implementation, SERVERNAME_B, REGIONINFO); - - // Make it so we can get a catalogtracker from servermanager.. .needed - // down in guts of server shutdown handler. - Mockito.when(ct.getConnection()).thenReturn(connection); - Mockito.when(this.server.getCatalogTracker()).thenReturn(ct); - - // Now make a server shutdown handler instance and invoke process. - // Have it that SERVERNAME_A died. - DeadServer deadServers = new DeadServer(); - deadServers.add(SERVERNAME_A); - // I need a services instance that will return the AM - MasterServices services = Mockito.mock(MasterServices.class); - Mockito.when(services.getAssignmentManager()).thenReturn(am); - Mockito.when(services.getServerManager()).thenReturn(this.serverManager); - ServerShutdownHandler handler = new ServerShutdownHandler(this.server, - services, deadServers, SERVERNAME_A, false); - handler.process(); - // The region in r will have been assigned. It'll be up in zk as unassigned. + /** + * To test closed region handler to remove rit and delete corresponding znode + * if region in pending close or closing while processing shutdown of a region + * server.(HBASE-5927). + * + * @throws KeeperException + * @throws IOException + * @throws ServiceException + */ + @Test + public void testSSHWhenDisableTableInProgress() throws KeeperException, IOException, + ServiceException { + testCaseWithPartiallyDisabledState(Table.State.DISABLING); + testCaseWithPartiallyDisabledState(Table.State.DISABLED); + } + + private void testCaseWithPartiallyDisabledState(Table.State state) throws KeeperException, + IOException, NodeExistsException, ServiceException { + // Create and startup an executor. This is used by AssignmentManager + // handling zk callbacks. + ExecutorService executor = startupMasterExecutor("testSSHWhenDisableTableInProgress"); + // We need a mocked catalog tracker. + CatalogTracker ct = Mockito.mock(CatalogTracker.class); + LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(server.getConfiguration()); + // Create an AM. + AssignmentManager am = new AssignmentManager(this.server, this.serverManager, ct, balancer, + executor, null); + // adding region to regions and servers maps. + am.regionOnline(REGIONINFO, SERVERNAME_A); + // adding region in pending close. + am.regionsInTransition.put(REGIONINFO.getEncodedName(), new RegionState(REGIONINFO, + State.PENDING_CLOSE)); + if (state == Table.State.DISABLING) { + am.getZKTable().setDisablingTable(REGIONINFO.getTableNameAsString()); + } else { + am.getZKTable().setDisabledTable(REGIONINFO.getTableNameAsString()); + } + RegionTransition data = RegionTransition.createRegionTransition(EventType.M_ZK_REGION_CLOSING, + REGIONINFO.getRegionName(), SERVERNAME_A); + // RegionTransitionData data = new + // RegionTransitionData(EventType.M_ZK_REGION_CLOSING, + // REGIONINFO.getRegionName(), SERVERNAME_A); + String node = ZKAssign.getNodeName(this.watcher, REGIONINFO.getEncodedName()); + // create znode in M_ZK_REGION_CLOSING state. + ZKUtil.createAndWatch(this.watcher, node, data.toByteArray()); + try { + processServerShutdownHandler(ct, am); + // check znode deleted or not. + // In both cases the znode should be deleted. + assertTrue("The znode should be deleted.", ZKUtil.checkExists(this.watcher, node) == -1); + // check whether in rit or not. In the DISABLING case also the below + // assert will be true but the piece of code added for HBASE-5927 will not + // do that. + if (state == Table.State.DISABLED) { + assertTrue("Region state of region in pending close should be removed from rit.", + am.regionsInTransition.isEmpty()); + } } finally { executor.shutdown(); am.shutdown(); @@ -444,6 +475,48 @@ public void testShutdownHandler() ZKAssign.deleteAllNodes(this.watcher); } } + + private void processServerShutdownHandler(CatalogTracker ct, AssignmentManager am) + throws IOException, ServiceException { + // Make sure our new AM gets callbacks; once registered, can't unregister. + // Thats ok because we make a new zk watcher for each test. + this.watcher.registerListenerFirst(am); + + // Need to set up a fake scan of meta for the servershutdown handler + // Make an RS Interface implementation. Make it so a scanner can go against it. + ClientProtocol implementation = Mockito.mock(ClientProtocol.class); + // Get a meta row result that has region up on SERVERNAME_A + Result r = Mocking.getMetaTableRowResult(REGIONINFO, SERVERNAME_A); + ScanResponse.Builder builder = ScanResponse.newBuilder(); + builder.setMoreResults(true); + builder.addResult(ProtobufUtil.toResult(r)); + Mockito.when(implementation.scan( + (RpcController)Mockito.any(), (ScanRequest)Mockito.any())). + thenReturn(builder.build()); + + // Get a connection w/ mocked up common methods. + HConnection connection = + HConnectionTestingUtility.getMockedConnectionAndDecorate(HTU.getConfiguration(), + null, implementation, SERVERNAME_B, REGIONINFO); + + // Make it so we can get a catalogtracker from servermanager.. .needed + // down in guts of server shutdown handler. + Mockito.when(ct.getConnection()).thenReturn(connection); + Mockito.when(this.server.getCatalogTracker()).thenReturn(ct); + + // Now make a server shutdown handler instance and invoke process. + // Have it that SERVERNAME_A died. + DeadServer deadServers = new DeadServer(); + deadServers.add(SERVERNAME_A); + // I need a services instance that will return the AM + MasterServices services = Mockito.mock(MasterServices.class); + Mockito.when(services.getAssignmentManager()).thenReturn(am); + Mockito.when(services.getServerManager()).thenReturn(this.serverManager); + ServerShutdownHandler handler = new ServerShutdownHandler(this.server, + services, deadServers, SERVERNAME_A, false); + handler.process(); + // The region in r will have been assigned. It'll be up in zk as unassigned. + } /** * Create and startup executor pools. Start same set as master does (just
2e0bf34ee31beda97f21430ab4869f1e842d22e9
restlet-framework-java
Fixed javadocs.--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.android/src/org/restlet/Component.java b/modules/org.restlet.android/src/org/restlet/Component.java index 5ef02ce292..1c6e964505 100644 --- a/modules/org.restlet.android/src/org/restlet/Component.java +++ b/modules/org.restlet.android/src/org/restlet/Component.java @@ -336,11 +336,6 @@ public List<VirtualHost> getHosts() { * {@link Context#getServerDispatcher()} method, but the internal router is * easily addressable via an URI scheme and can be fully private to the * current Component.<br> - * <br> - * The second use case is the composition/mash-up of several representations - * via the {@link org.restlet.routing.Transformer} class for example. For - * this you can leverage the XPath's document() function or the XSLT's - * include and import elements with RIAP URIs. * * @return The private internal router. */ diff --git a/modules/org.restlet.android/src/org/restlet/representation/XmlRepresentation.java b/modules/org.restlet.android/src/org/restlet/representation/XmlRepresentation.java index c8f24f7996..c3ec6e7339 100644 --- a/modules/org.restlet.android/src/org/restlet/representation/XmlRepresentation.java +++ b/modules/org.restlet.android/src/org/restlet/representation/XmlRepresentation.java @@ -179,7 +179,7 @@ private Map<String, String> getNamespaces() { * TODO Seems unused. * * @param prefix - * @return + * @return result */ public String getNamespaceURI(String prefix) { return this.namespaces.get(prefix); @@ -189,7 +189,7 @@ public String getNamespaceURI(String prefix) { * TODO Seems unused. * * @param namespaceURI - * @return + * @return result */ public String getPrefix(String namespaceURI) { String result = null; @@ -212,7 +212,7 @@ public String getPrefix(String namespaceURI) { * TODO Seems unused. * * @param namespaceURI - * @return + * @return result */ public Iterator<String> getPrefixes(String namespaceURI) { final List<String> result = new ArrayList<String>(); diff --git a/modules/org.restlet.gae/src/org/restlet/ext/net/HttpClientHelper.java b/modules/org.restlet.gae/src/org/restlet/ext/net/HttpClientHelper.java index c981078aa3..292e3baa85 100644 --- a/modules/org.restlet.gae/src/org/restlet/ext/net/HttpClientHelper.java +++ b/modules/org.restlet.gae/src/org/restlet/ext/net/HttpClientHelper.java @@ -87,9 +87,6 @@ * </tr> * </table> * - * It is also possible to specify a hostname verifier for HTTPS connections. See - * the {@link #getHostnameVerifier()} method for details. - * * Note that by default, the {@link HttpURLConnection} class as implemented by * Sun will retry a request if an IO exception is caught, for example due to a * connection reset by the server. This can be annoying, especially because the diff --git a/modules/org.restlet/src/org/restlet/resource/ServerResource.java b/modules/org.restlet/src/org/restlet/resource/ServerResource.java index 3d090dffd8..7ab66ade01 100644 --- a/modules/org.restlet/src/org/restlet/resource/ServerResource.java +++ b/modules/org.restlet/src/org/restlet/resource/ServerResource.java @@ -161,7 +161,7 @@ protected Representation delete() throws ResourceException { * The variant of the response entity. * @return The optional response entity. * @throws ResourceException - * @see {@link ServerResource#get(Variant)} + * @see #get(Variant) * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7" * >HTTP DELETE method</a> @@ -630,7 +630,7 @@ protected Representation get() throws ResourceException { * @param variant * The variant whose full representation must be returned. * @return The resource's representation. - * @see {@link ServerResource#get(Variant)} + * @see #get(Variant) * @throws ResourceException */ protected Representation get(Variant variant) throws ResourceException { @@ -981,7 +981,7 @@ protected Representation head() throws ResourceException { * @param variant * The variant whose full representation must be returned. * @return The resource's representation. - * @see {@link ServerResource#get(Variant)} + * @see #get(Variant) * @throws ResourceException */ protected Representation head(Variant variant) throws ResourceException { @@ -1066,7 +1066,7 @@ protected Representation options() throws ResourceException { * @param variant * The variant of the response entity. * @return The optional response entity. - * @see {@link ServerResource#get(Variant)} + * @see #get(Variant) */ protected Representation options(Variant variant) throws ResourceException { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); @@ -1082,7 +1082,7 @@ protected Representation options(Variant variant) throws ResourceException { * The posted entity. * @return The optional response entity. * @throws ResourceException - * @see {@link ServerResource#get(Variant)} + * @see #get(Variant) * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5">HTTP * POST method</a> @@ -1144,7 +1144,7 @@ protected Representation put(Representation representation) * The variant of the response entity. * @return The optional result entity. * @throws ResourceException - * @see {@link ServerResource#get(Variant)} + * @see #get(Variant) * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6" * >HTTP PUT method</a>
7b7fc7b788066529daa177873c28f4f9013a9c9e
hadoop
YARN-254. Update fair scheduler web UI for- hierarchical queues. (sandyr via tucu)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1423743 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index dc762a56a1a39..16c8cb338a15a 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -56,6 +56,9 @@ Release 2.0.3-alpha - Unreleased YARN-129. Simplify classpath construction for mini YARN tests. (tomwhite) + YARN-254. Update fair scheduler web UI for hierarchical queues. + (sandyr via tucu) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/FairSchedulerPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/FairSchedulerPage.java index 8872fab097a17..b36fd9a4c2d52 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/FairSchedulerPage.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/FairSchedulerPage.java @@ -20,21 +20,21 @@ import static org.apache.hadoop.yarn.util.StringHelper.join; -import java.util.List; +import java.util.Collection; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.FairSchedulerInfo; +import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.FairSchedulerLeafQueueInfo; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.FairSchedulerQueueInfo; import org.apache.hadoop.yarn.webapp.ResponseInfo; import org.apache.hadoop.yarn.webapp.SubView; import org.apache.hadoop.yarn.webapp.hamlet.Hamlet; import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.DIV; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.LI; import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.UL; import org.apache.hadoop.yarn.webapp.view.HtmlBlock; import org.apache.hadoop.yarn.webapp.view.InfoBlock; -import org.apache.hadoop.yarn.webapp.view.HtmlPage.Page; -import org.apache.hadoop.yarn.webapp.view.HtmlPage._; import com.google.inject.Inject; import com.google.inject.servlet.RequestScoped; @@ -50,16 +50,15 @@ public class FairSchedulerPage extends RmView { @RequestScoped static class FSQInfo { - FairSchedulerInfo fsinfo; FairSchedulerQueueInfo qinfo; } - static class QueueInfoBlock extends HtmlBlock { - final FairSchedulerQueueInfo qinfo; + static class LeafQueueBlock extends HtmlBlock { + final FairSchedulerLeafQueueInfo qinfo; - @Inject QueueInfoBlock(ViewContext ctx, FSQInfo info) { + @Inject LeafQueueBlock(ViewContext ctx, FSQInfo info) { super(ctx); - qinfo = (FairSchedulerQueueInfo) info.qinfo; + qinfo = (FairSchedulerLeafQueueInfo)info.qinfo; } @Override @@ -83,6 +82,47 @@ protected void render(Block html) { } } + static class QueueBlock extends HtmlBlock { + final FSQInfo fsqinfo; + + @Inject QueueBlock(FSQInfo info) { + fsqinfo = info; + } + + @Override + public void render(Block html) { + Collection<FairSchedulerQueueInfo> subQueues = fsqinfo.qinfo.getChildQueues(); + UL<Hamlet> ul = html.ul("#pq"); + for (FairSchedulerQueueInfo info : subQueues) { + float capacity = info.getMaxResourcesFraction(); + float fairShare = info.getFairShareFraction(); + float used = info.getUsedFraction(); + LI<UL<Hamlet>> li = ul. + li(). + a(_Q).$style(width(capacity * Q_MAX_WIDTH)). + $title(join("Fair Share:", percent(fairShare))). + span().$style(join(Q_GIVEN, ";font-size:1px;", width(fairShare/capacity))). + _('.')._(). + span().$style(join(width(used/capacity), + ";font-size:1px;left:0%;", used > fairShare ? Q_OVER : Q_UNDER)). + _('.')._(). + span(".q", info.getQueueName())._(). + span().$class("qstats").$style(left(Q_STATS_POS)). + _(join(percent(used), " used"))._(); + + fsqinfo.qinfo = info; + if (info instanceof FairSchedulerLeafQueueInfo) { + li.ul("#lq").li()._(LeafQueueBlock.class)._()._(); + } else { + li._(QueueBlock.class); + } + li._(); + } + + ul._(); + } + } + static class QueuesBlock extends HtmlBlock { final FairScheduler fs; final FSQInfo fsqinfo; @@ -91,8 +131,9 @@ static class QueuesBlock extends HtmlBlock { fs = (FairScheduler)rm.getResourceScheduler(); fsqinfo = info; } - - @Override public void render(Block html) { + + @Override + public void render(Block html) { html._(MetricsOverviewTable.class); UL<DIV<DIV<Hamlet>>> ul = html. div("#cs-wrapper.ui-widget"). @@ -108,8 +149,8 @@ static class QueuesBlock extends HtmlBlock { span(".q", "default")._()._(); } else { FairSchedulerInfo sinfo = new FairSchedulerInfo(fs); - fsqinfo.fsinfo = sinfo; - fsqinfo.qinfo = null; + fsqinfo.qinfo = sinfo.getRootQueueInfo(); + float used = fsqinfo.qinfo.getUsedFraction(); ul. li().$style("margin-bottom: 1em"). @@ -122,29 +163,15 @@ static class QueuesBlock extends HtmlBlock { _("Used (over fair share)")._(). span().$class("qlegend ui-corner-all ui-state-default"). _("Max Capacity")._(). - _(); - - List<FairSchedulerQueueInfo> subQueues = fsqinfo.fsinfo.getQueueInfos(); - for (FairSchedulerQueueInfo info : subQueues) { - fsqinfo.qinfo = info; - float capacity = info.getMaxResourcesFraction(); - float fairShare = info.getFairShareFraction(); - float used = info.getUsedFraction(); - ul. - li(). - a(_Q).$style(width(capacity * Q_MAX_WIDTH)). - $title(join("Fair Share:", percent(fairShare))). - span().$style(join(Q_GIVEN, ";font-size:1px;", width(fairShare/capacity))). - _('.')._(). - span().$style(join(width(used/capacity), - ";font-size:1px;left:0%;", used > fairShare ? Q_OVER : Q_UNDER)). - _('.')._(). - span(".q", info.getQueueName())._(). - span().$class("qstats").$style(left(Q_STATS_POS)). - _(join(percent(used), " used"))._(). - ul("#lq").li()._(QueueInfoBlock.class)._()._(). - _(); - } + _(). + li(). + a(_Q).$style(width(Q_MAX_WIDTH)). + span().$style(join(width(used), ";left:0%;", + used > 1 ? Q_OVER : Q_UNDER))._(".")._(). + span(".q", "root")._(). + span().$class("qstats").$style(left(Q_STATS_POS)). + _(join(percent(used), " used"))._(). + _(QueueBlock.class)._(); } ul._()._(). script().$type("text/javascript"). diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerInfo.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerInfo.java index 4fe19ca13d1b5..e1fac4a2cf4da 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerInfo.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerInfo.java @@ -18,33 +18,23 @@ package org.apache.hadoop.yarn.server.resourcemanager.webapp.dao; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; -import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSLeafQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; public class FairSchedulerInfo { - private List<FairSchedulerQueueInfo> queueInfos; private FairScheduler scheduler; public FairSchedulerInfo(FairScheduler fs) { scheduler = fs; - Collection<FSLeafQueue> queues = fs.getQueueManager().getLeafQueues(); - queueInfos = new ArrayList<FairSchedulerQueueInfo>(); - for (FSLeafQueue queue : queues) { - queueInfos.add(new FairSchedulerQueueInfo(queue, fs)); - } - } - - public List<FairSchedulerQueueInfo> getQueueInfos() { - return queueInfos; } public int getAppFairShare(ApplicationAttemptId appAttemptId) { return scheduler.getSchedulerApp(appAttemptId). getAppSchedulable().getFairShare().getMemory(); } + + public FairSchedulerQueueInfo getRootQueueInfo() { + return new FairSchedulerQueueInfo(scheduler.getQueueManager(). + getRootQueue(), scheduler); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerLeafQueueInfo.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerLeafQueueInfo.java new file mode 100644 index 0000000000000..bee1cfd9866fc --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerLeafQueueInfo.java @@ -0,0 +1,32 @@ +package org.apache.hadoop.yarn.server.resourcemanager.webapp.dao; + +import java.util.Collection; + +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.AppSchedulable; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSLeafQueue; + +public class FairSchedulerLeafQueueInfo extends FairSchedulerQueueInfo { + private int numPendingApps; + private int numActiveApps; + + public FairSchedulerLeafQueueInfo(FSLeafQueue queue, FairScheduler scheduler) { + super(queue, scheduler); + Collection<AppSchedulable> apps = queue.getAppSchedulables(); + for (AppSchedulable app : apps) { + if (app.getApp().isPending()) { + numPendingApps++; + } else { + numActiveApps++; + } + } + } + + public int getNumActiveApplications() { + return numPendingApps; + } + + public int getNumPendingApplications() { + return numActiveApps; + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerQueueInfo.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerQueueInfo.java index 35749427d007a..3cab1da33c0ad 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerQueueInfo.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/FairSchedulerQueueInfo.java @@ -18,19 +18,18 @@ package org.apache.hadoop.yarn.server.resourcemanager.webapp.dao; + +import java.util.ArrayList; import java.util.Collection; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.resource.Resources; -import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.AppSchedulable; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSLeafQueue; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.QueueManager; -public class FairSchedulerQueueInfo { - private int numPendingApps; - private int numActiveApps; - +public class FairSchedulerQueueInfo { private int fairShare; private int minShare; private int maxShare; @@ -48,16 +47,9 @@ public class FairSchedulerQueueInfo { private String queueName; - public FairSchedulerQueueInfo(FSLeafQueue queue, FairScheduler scheduler) { - Collection<AppSchedulable> apps = queue.getAppSchedulables(); - for (AppSchedulable app : apps) { - if (app.getApp().isPending()) { - numPendingApps++; - } else { - numActiveApps++; - } - } - + private Collection<FairSchedulerQueueInfo> childInfos; + + public FairSchedulerQueueInfo(FSQueue queue, FairScheduler scheduler) { QueueManager manager = scheduler.getQueueManager(); queueName = queue.getName(); @@ -81,6 +73,16 @@ public FairSchedulerQueueInfo(FSLeafQueue queue, FairScheduler scheduler) { fractionMinShare = (float)minShare / clusterMaxMem; maxApps = manager.getQueueMaxApps(queueName); + + Collection<FSQueue> childQueues = queue.getChildQueues(); + childInfos = new ArrayList<FairSchedulerQueueInfo>(); + for (FSQueue child : childQueues) { + if (child instanceof FSLeafQueue) { + childInfos.add(new FairSchedulerLeafQueueInfo((FSLeafQueue)child, scheduler)); + } else { + childInfos.add(new FairSchedulerQueueInfo(child, scheduler)); + } + } } /** @@ -96,15 +98,7 @@ public float getFairShareFraction() { public int getFairShare() { return fairShare; } - - public int getNumActiveApplications() { - return numPendingApps; - } - - public int getNumPendingApplications() { - return numActiveApps; - } - + public Resource getMinResources() { return minResources; } @@ -148,4 +142,8 @@ public float getUsedFraction() { public float getMaxResourcesFraction() { return (float)maxShare / clusterMaxMem; } + + public Collection<FairSchedulerQueueInfo> getChildQueues() { + return childInfos; + } }
4da9b2cc9c18a5b8680550e3bdbe2c405abb5d81
elasticsearch
Catch AmazonClientExceptions to prevent- connection loss If the AWS client throws an exception (e.g: because of a DNS- failure) it will end up killing the rejoin thread and stop retrying which can- lead to a node getting stuck unable to rejoin the cluster.--Closes -30.-
c
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2UnicastHostsProvider.java b/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2UnicastHostsProvider.java index abca15afd8e3a..a8f99462b9442 100644 --- a/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2UnicastHostsProvider.java +++ b/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2UnicastHostsProvider.java @@ -19,6 +19,7 @@ package org.elasticsearch.discovery.ec2; +import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.*; import org.elasticsearch.Version; @@ -96,7 +97,14 @@ public AwsEc2UnicastHostsProvider(Settings settings, TransportService transportS public List<DiscoveryNode> buildDynamicNodes() { List<DiscoveryNode> discoNodes = Lists.newArrayList(); - DescribeInstancesResult descInstances = client.describeInstances(new DescribeInstancesRequest()); + DescribeInstancesResult descInstances; + try { + descInstances = client.describeInstances(new DescribeInstancesRequest()); + } catch (AmazonClientException e) { + logger.info("Exception while retrieving instance list from AWS API: {}", e.getMessage()); + logger.debug("Full exception:", e); + return discoNodes; + } logger.trace("building dynamic unicast discovery nodes..."); for (Reservation reservation : descInstances.getReservations()) {
ebb08cddcf8511e6a62ffbf0fff675e9627cd376
hbase
HBASE-1866 Scan(Scan) copy constructor does not- copy value of cacheBlocks--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@818656 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index 3df60cc6deb9..c08e89a1bfb4 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -45,6 +45,8 @@ Release 0.21.0 - Unreleased HBASE-1809 NPE thrown in BoundedRangeFileInputStream HBASE-1859 Misc shell fixes patch (Kyle Oba via Stack) HBASE-1865 0.20.0 TableInputFormatBase NPE + HBASE-1866 Scan(Scan) copy constructor does not copy value of + cacheBlocks IMPROVEMENTS HBASE-1760 Cleanup TODOs in HTable diff --git a/src/java/org/apache/hadoop/hbase/client/Scan.java b/src/java/org/apache/hadoop/hbase/client/Scan.java index ab2a36452a8f..7aef19ade474 100644 --- a/src/java/org/apache/hadoop/hbase/client/Scan.java +++ b/src/java/org/apache/hadoop/hbase/client/Scan.java @@ -124,6 +124,7 @@ public Scan(Scan scan) throws IOException { stopRow = scan.getStopRow(); maxVersions = scan.getMaxVersions(); caching = scan.getCaching(); + cacheBlocks = scan.getCacheBlocks(); filter = scan.getFilter(); // clone? TimeRange ctr = scan.getTimeRange(); tr = new TimeRange(ctr.getMin(), ctr.getMax()); @@ -380,6 +381,8 @@ public String toString() { sb.append("" + this.maxVersions); sb.append(", caching="); sb.append("" + this.caching); + sb.append(", cacheBlocks="); + sb.append("" + this.cacheBlocks); sb.append(", timeRange="); sb.append("[" + this.tr.getMin() + "," + this.tr.getMax() + ")"); sb.append(", families=");
26d26d605e9887885afe78d943fbf152d965e44a
intellij-community
PY-1635 Extract Method in middle of expression- generates broken code--
c
https://github.com/JetBrains/intellij-community
diff --git a/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java b/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java index c4e5eb036be11..04daea9e6c155 100644 --- a/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java +++ b/python/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java @@ -198,15 +198,15 @@ public void run() { // Generating call element final StringBuilder builder = new StringBuilder(); - if (fragment.isReturnInstructionInside()) { - builder.append("return "); - } + builder.append("return "); if (isMethod){ appendSelf(expression, builder); } builder.append(methodName); builder.append("(").append(createCallArgsString(variableData)).append(")"); - PsiElement callElement = PyElementGenerator.getInstance(project).createFromText(LanguageLevel.getDefault(), PyElement.class, builder.toString()); + final PyReturnStatement returnStatement = + (PyReturnStatement) PyElementGenerator.getInstance(project).createFromText(LanguageLevel.getDefault(), PyElement.class, builder.toString()); + PsiElement callElement = fragment.isReturnInstructionInside() ? returnStatement : returnStatement.getExpression(); // replace statements with call callElement = PyPsiUtils.replaceExpression(project, expression, callElement); diff --git a/python/testData/refactoring/extractmethod/return_tuple.after.py b/python/testData/refactoring/extractmethod/return_tuple.after.py new file mode 100644 index 0000000000000..dc924a7a7074b --- /dev/null +++ b/python/testData/refactoring/extractmethod/return_tuple.after.py @@ -0,0 +1,5 @@ +def bar(p_name_new, params_new): + return p_name_new + '(' + ', '.join(params_new) + ')' + +def x(p_name, params): + return bar(p_name, params), None \ No newline at end of file diff --git a/python/testData/refactoring/extractmethod/return_tuple.before.py b/python/testData/refactoring/extractmethod/return_tuple.before.py new file mode 100644 index 0000000000000..3e30779879366 --- /dev/null +++ b/python/testData/refactoring/extractmethod/return_tuple.before.py @@ -0,0 +1,2 @@ +def x(p_name, params): + return <selection>p_name + '(' + ', '.join(params) + ')'</selection>, None \ No newline at end of file diff --git a/python/testSrc/com/jetbrains/python/refactoring/PyExtractMethodTest.java b/python/testSrc/com/jetbrains/python/refactoring/PyExtractMethodTest.java index 0d00716b87a4c..0f55625d895a9 100644 --- a/python/testSrc/com/jetbrains/python/refactoring/PyExtractMethodTest.java +++ b/python/testSrc/com/jetbrains/python/refactoring/PyExtractMethodTest.java @@ -133,4 +133,8 @@ public void testConditionalReturn() throws Throwable { doTest("conditionalreturn.before.py", "bar", "Cannot perform refactoring when execution flow is interrupted"); } + public void testReturnTuple() throws Throwable { + doTest("return_tuple.before.py", "bar", "return_tuple.after.py"); + } + }
e517f55833c7ec02676bd850e9cd8f302a8a713f
ReactiveX-RxJava
Add finally0 to Observable.java .--
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java index 5d11c7b9ed..72c400dbf7 100644 --- a/rxjava-core/src/main/java/rx/Observable.java +++ b/rxjava-core/src/main/java/rx/Observable.java @@ -1182,6 +1182,18 @@ public static <T> Observable<T> concat(Observable<T>... source) { return _create(OperationConcat.concat(source)); } + /** + * Emits the same objects as the given Observable, calling the given action + * when it calls <code>onComplete</code> or <code>onError</code>. + * @param source an observable + * @param action an action to be called when the source completes or errors. + * @return an Observable that emits the same objects, then calls the action. + * @see <a href="http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx">MSDN: Observable.Finally Method</a> + */ + public static <T> Observable<T> finally0(Observable source, Action0 action) { + return _create(OperationFinally.finally0(source, action)); + } + /** * Groups the elements of an observable and selects the resulting elements by using a specified function. * diff --git a/rxjava-core/src/main/java/rx/operators/OperationFinally.java b/rxjava-core/src/main/java/rx/operators/OperationFinally.java index 0eddc57d2f..4474e11936 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationFinally.java +++ b/rxjava-core/src/main/java/rx/operators/OperationFinally.java @@ -1,12 +1,12 @@ /** * Copyright 2013 Netflix, Inc. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,15 +23,12 @@ import java.util.List; import java.util.concurrent.CountDownLatch; -import org.junit.Assert; -import org.junit.Before; import org.junit.Test; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.util.AtomicObservableSubscription; -import rx.util.AtomicObserver; import rx.util.functions.Action0; import rx.util.functions.Func1; @@ -42,16 +39,16 @@ public final class OperationFinally { * exception). The returned observable is exactly as threadsafe as the * source observable; in particular, any situation allowing the source to * call onComplete or onError multiple times allows the returned observable - * to call the action multiple times. + * to call the final action multiple times. * <p/> * Note that "finally" is a Java reserved word and cannot be an identifier, * so we use "finally0". - * + * * @param sequence An observable sequence of elements * @param action An action to be taken when the sequence is complete or throws an exception * @return An observable sequence with the same elements as the input. * After the last element is consumed (just before {@link Observer#onComplete} is called), - * or when an exception is thrown (just before {@link Observer#onError}), the action will be taken. + * or when an exception is thrown (just before {@link Observer#onError}), the action will be called. * @see http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx */ public static <T> Func1<Observer<T>, Subscription> finally0(final Observable<T> sequence, final Action0 action) { @@ -121,25 +118,24 @@ private static class TestAction implements Action0 { called++; } } - + @Test public void testFinally() { final String[] n = {"1", "2", "3"}; final Observable<String> nums = Observable.toObservable(n); TestAction action = new TestAction(); action.called = 0; - @SuppressWarnings("unchecked") Observable<String> fin = Observable.create(finally0(nums, action)); @SuppressWarnings("unchecked") Observer<String> aObserver = mock(Observer.class); fin.subscribe(aObserver); - Assert.assertEquals(1, action.called); + assertEquals(1, action.called); action.called = 0; Observable<String> error = Observable.<String>error(new RuntimeException("expected")); fin = Observable.create(finally0(error, action)); fin.subscribe(aObserver); - Assert.assertEquals(1, action.called); + assertEquals(1, action.called); } } -} \ No newline at end of file +}
a47d981c6e88178558d3b07fa53c903654a0e321
hadoop
YARN-975. Added a file-system implementation for- HistoryStorage. Contributed by Zhijie Shen. svn merge --ignore-ancestry -c- 1556727 ../YARN-321--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1562184 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 7ab49ac347199..48c97fc26d9b0 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -477,6 +477,9 @@ Branch YARN-321: Generic ApplicationHistoryService YARN-1007. Enhance History Reader interface for Containers. (Mayank Bansal via devaraj) + YARN-975. Added a file-system implementation for HistoryStorage. (Zhijie Shen + via vinodkv) + Release 2.2.0 - 2013-10-13 INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java index dc195858cb827..009dda3c16062 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java @@ -931,6 +931,19 @@ public class YarnConfiguration extends Configuration { public static final String YARN_APP_CONTAINER_LOG_BACKUPS = YARN_PREFIX + "app.container.log.backups"; + //////////////////////////////// + // AHS Configs + //////////////////////////////// + + public static final String AHS_PREFIX = YARN_PREFIX + "ahs."; + + /** URI for FileSystemApplicationHistoryStore */ + public static final String FS_HISTORY_STORE_URI = AHS_PREFIX + "fs-history-store.uri"; + + /** T-file compression types used to compress history data.*/ + public static final String FS_HISTORY_STORE_COMPRESSION_TYPE = AHS_PREFIX + "fs-history-store.compression-type"; + public static final String DEFAULT_FS_HISTORY_STORE_COMPRESSION_TYPE = "none"; + //////////////////////////////// // Other Configs //////////////////////////////// diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/resources/yarn-default.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/resources/yarn-default.xml index ba6264e0ae31f..b831158460fa4 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/resources/yarn-default.xml +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/resources/yarn-default.xml @@ -1041,6 +1041,23 @@ <value></value> </property> + <!-- Application History Service's Configuration--> + + <property> + <description>URI pointing to the location of the FileSystem path where + the history will be persisted. This must be supplied when using + org.apache.hadoop.yarn.server.applicationhistoryservice.FileSystemApplicationHistoryStore + as the value for yarn.resourcemanager.ahs.writer.class</description> + <name>yarn.ahs.fs-history-store.uri</name> + <value>${hadoop.log.dir}/yarn/system/ahstore</value> + </property> + + <property> + <description>T-file compression types used to compress history data.</description> + <name>yarn.ahs.fs-history-store.compression-type</name> + <value>none</value> + </property> + <!-- Other configuration --> <property> <description>The interval that the yarn client library uses to poll the diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java new file mode 100644 index 0000000000000..b4d97f314db59 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java @@ -0,0 +1,860 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.applicationhistoryservice; + +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.classification.InterfaceAudience.Public; +import org.apache.hadoop.classification.InterfaceStability.Unstable; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FSDataInputStream; +import org.apache.hadoop.fs.FSDataOutputStream; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.permission.FsPermission; +import org.apache.hadoop.io.IOUtils; +import org.apache.hadoop.io.Writable; +import org.apache.hadoop.io.file.tfile.TFile; +import org.apache.hadoop.service.AbstractService; +import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; +import org.apache.hadoop.yarn.api.records.ApplicationId; +import org.apache.hadoop.yarn.api.records.ContainerId; +import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.proto.ApplicationHistoryServerProtos.ApplicationAttemptFinishDataProto; +import org.apache.hadoop.yarn.proto.ApplicationHistoryServerProtos.ApplicationAttemptStartDataProto; +import org.apache.hadoop.yarn.proto.ApplicationHistoryServerProtos.ApplicationFinishDataProto; +import org.apache.hadoop.yarn.proto.ApplicationHistoryServerProtos.ApplicationStartDataProto; +import org.apache.hadoop.yarn.proto.ApplicationHistoryServerProtos.ContainerFinishDataProto; +import org.apache.hadoop.yarn.proto.ApplicationHistoryServerProtos.ContainerStartDataProto; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ApplicationAttemptFinishData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ApplicationAttemptHistoryData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ApplicationAttemptStartData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ApplicationFinishData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ApplicationHistoryData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ApplicationStartData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ContainerFinishData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ContainerHistoryData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ContainerStartData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.impl.pb.ApplicationAttemptFinishDataPBImpl; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.impl.pb.ApplicationAttemptStartDataPBImpl; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.impl.pb.ApplicationFinishDataPBImpl; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.impl.pb.ApplicationStartDataPBImpl; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.impl.pb.ContainerFinishDataPBImpl; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.impl.pb.ContainerStartDataPBImpl; +import org.apache.hadoop.yarn.util.ConverterUtils; + +import com.google.protobuf.InvalidProtocolBufferException; + +/** + * File system implementation of {@link ApplicationHistoryStore}. In this + * implementation, one application will have just one file in the file system, + * which contains all the history data of one application, and its attempts and + * containers. {@link #applicationStarted(ApplicationStartData)} is supposed to + * be invoked first when writing any history data of one application and it will + * open a file, while {@link #applicationFinished(ApplicationFinishData)} is + * supposed to be last writing operation and will close the file. + */ +@Public +@Unstable +public class FileSystemApplicationHistoryStore extends AbstractService + implements ApplicationHistoryStore { + + private static final Log LOG = LogFactory + .getLog(FileSystemApplicationHistoryStore.class); + + private static final String ROOT_DIR_NAME = "ApplicationHistoryDataRoot"; + private static final int MIN_BLOCK_SIZE = 256 * 1024; + private static final String START_DATA_SUFFIX = "_start"; + private static final String FINISH_DATA_SUFFIX = "_finish"; + private static final FsPermission ROOT_DIR_UMASK = + FsPermission.createImmutable((short) 0740); + private static final FsPermission HISTORY_FILE_UMASK = + FsPermission.createImmutable((short) 0640); + + private FileSystem fs; + private Path rootDirPath; + + private ConcurrentMap<ApplicationId, HistoryFileWriter> outstandingWriters = + new ConcurrentHashMap<ApplicationId, HistoryFileWriter>(); + + public FileSystemApplicationHistoryStore() { + super(FileSystemApplicationHistoryStore.class.getName()); + } + + @Override + public void serviceInit(Configuration conf) throws Exception { + Path fsWorkingPath = new Path( + conf.get(YarnConfiguration.FS_HISTORY_STORE_URI)); + rootDirPath = new Path(fsWorkingPath, ROOT_DIR_NAME); + try { + fs = fsWorkingPath.getFileSystem(conf); + fs.mkdirs(rootDirPath); + fs.setPermission(rootDirPath, ROOT_DIR_UMASK); + } catch (IOException e) { + LOG.error("Error when initializing FileSystemHistoryStorage", e); + throw e; + } + super.serviceInit(conf); + } + + @Override + public void serviceStop() throws Exception { + try { + for (Entry<ApplicationId, HistoryFileWriter> entry : outstandingWriters + .entrySet()) { + entry.getValue().close(); + } + outstandingWriters.clear(); + } finally { + IOUtils.cleanup(LOG, fs); + } + super.serviceStop(); + } + + @Override + public ApplicationHistoryData getApplication(ApplicationId appId) + throws IOException { + HistoryFileReader hfReader = getHistoryFileReader(appId); + try { + boolean readStartData = false; + boolean readFinishData = false; + ApplicationHistoryData historyData = + ApplicationHistoryData.newInstance( + appId, null, null, null, null, Long.MIN_VALUE, Long.MIN_VALUE, + Long.MAX_VALUE, null, FinalApplicationStatus.UNDEFINED, null); + while ((!readStartData || !readFinishData) && hfReader.hasNext()) { + HistoryFileReader.Entry entry = hfReader.next(); + if (entry.key.id.equals(appId.toString())) { + if (entry.key.suffix.equals(START_DATA_SUFFIX)) { + ApplicationStartData startData = + parseApplicationStartData(entry.value); + mergeApplicationHistoryData(historyData, startData); + readStartData = true; + } else if (entry.key.suffix.equals(FINISH_DATA_SUFFIX)) { + ApplicationFinishData finishData = + parseApplicationFinishData(entry.value); + mergeApplicationHistoryData(historyData, finishData); + readFinishData = true; + } + } + } + if (!readStartData && !readFinishData) { + return null; + } + if (!readStartData) { + LOG.warn("Start information is missing for application " + appId); + } + if (!readFinishData) { + LOG.warn("Finish information is missing for application " + appId); + } + LOG.info("Completed reading history information of application " + appId); + return historyData; + } catch (IOException e) { + LOG.error("Error when reading history file of application " + appId); + throw e; + } finally { + hfReader.close(); + } + } + + @Override + public Map<ApplicationId, ApplicationHistoryData> getAllApplications() + throws IOException { + Map<ApplicationId, ApplicationHistoryData> historyDataMap = + new HashMap<ApplicationId, ApplicationHistoryData>(); + FileStatus[] files = fs.listStatus(rootDirPath); + for (FileStatus file : files) { + ApplicationId appId = + ConverterUtils.toApplicationId(file.getPath().getName()); + try { + ApplicationHistoryData historyData = getApplication(appId); + if (historyData != null) { + historyDataMap.put(appId, historyData); + } + } catch (IOException e) { + // Eat the exception not to disturb the getting the next + // ApplicationHistoryData + LOG.error("History information of application " + appId + + " is not included into the result due to the exception", e); + } + } + return historyDataMap; + } + + @Override + public Map<ApplicationAttemptId, ApplicationAttemptHistoryData> + getApplicationAttempts(ApplicationId appId) throws IOException { + Map<ApplicationAttemptId, ApplicationAttemptHistoryData> historyDataMap = + new HashMap<ApplicationAttemptId, ApplicationAttemptHistoryData>(); + Map<ApplicationAttemptId, StartFinishDataPair<ApplicationAttemptStartData, ApplicationAttemptFinishData>> startFinshDataMap = + new HashMap<ApplicationAttemptId, StartFinishDataPair<ApplicationAttemptStartData, ApplicationAttemptFinishData>>(); + HistoryFileReader hfReader = getHistoryFileReader(appId); + try { + while (hfReader.hasNext()) { + HistoryFileReader.Entry entry = hfReader.next(); + if (entry.key.id.startsWith(ConverterUtils.APPLICATION_ATTEMPT_PREFIX)) { + if (entry.key.suffix.equals(START_DATA_SUFFIX)) { + retrieveStartFinishData(appId, entry, startFinshDataMap, true); + } else if (entry.key.suffix.equals(FINISH_DATA_SUFFIX)) { + retrieveStartFinishData(appId, entry, startFinshDataMap, false); + } + } + } + LOG.info("Completed reading history information of all application" + + " attempts of application " + appId); + } catch (IOException e) { + LOG.info("Error when reading history information of some application" + + " attempts of application " + appId); + } finally { + hfReader.close(); + } + for (Map.Entry<ApplicationAttemptId, StartFinishDataPair<ApplicationAttemptStartData, ApplicationAttemptFinishData>> entry : startFinshDataMap + .entrySet()) { + ApplicationAttemptHistoryData historyData = + ApplicationAttemptHistoryData.newInstance( + entry.getKey(), null, -1, null, null, null, + FinalApplicationStatus.UNDEFINED, null); + mergeApplicationAttemptHistoryData(historyData, + entry.getValue().startData); + mergeApplicationAttemptHistoryData(historyData, + entry.getValue().finishData); + historyDataMap.put(entry.getKey(), historyData); + } + return historyDataMap; + } + + private + void + retrieveStartFinishData( + ApplicationId appId, + HistoryFileReader.Entry entry, + Map<ApplicationAttemptId, StartFinishDataPair<ApplicationAttemptStartData, ApplicationAttemptFinishData>> startFinshDataMap, + boolean start) throws IOException { + ApplicationAttemptId appAttemptId = + ConverterUtils.toApplicationAttemptId(entry.key.id); + if (appAttemptId.getApplicationId().equals(appId)) { + StartFinishDataPair<ApplicationAttemptStartData, ApplicationAttemptFinishData> pair = + startFinshDataMap.get(appAttemptId); + if (pair == null) { + pair = + new StartFinishDataPair<ApplicationAttemptStartData, ApplicationAttemptFinishData>(); + startFinshDataMap.put(appAttemptId, pair); + } + if (start) { + pair.startData = parseApplicationAttemptStartData(entry.value); + } else { + pair.finishData = parseApplicationAttemptFinishData(entry.value); + } + } + } + + @Override + public ApplicationAttemptHistoryData getApplicationAttempt( + ApplicationAttemptId appAttemptId) throws IOException { + HistoryFileReader hfReader = + getHistoryFileReader(appAttemptId.getApplicationId()); + try { + boolean readStartData = false; + boolean readFinishData = false; + ApplicationAttemptHistoryData historyData = + ApplicationAttemptHistoryData.newInstance( + appAttemptId, null, -1, null, null, null, + FinalApplicationStatus.UNDEFINED, null); + while ((!readStartData || !readFinishData) && hfReader.hasNext()) { + HistoryFileReader.Entry entry = hfReader.next(); + if (entry.key.id.equals(appAttemptId.toString())) { + if (entry.key.suffix.equals(START_DATA_SUFFIX)) { + ApplicationAttemptStartData startData = + parseApplicationAttemptStartData(entry.value); + mergeApplicationAttemptHistoryData(historyData, startData); + readStartData = true; + } else if (entry.key.suffix.equals(FINISH_DATA_SUFFIX)) { + ApplicationAttemptFinishData finishData = + parseApplicationAttemptFinishData(entry.value); + mergeApplicationAttemptHistoryData(historyData, finishData); + readFinishData = true; + } + } + } + if (!readStartData && !readFinishData) { + return null; + } + if (!readStartData) { + LOG.warn("Start information is missing for application attempt " + + appAttemptId); + } + if (!readFinishData) { + LOG.warn("Finish information is missing for application attempt " + + appAttemptId); + } + LOG.info("Completed reading history information of application attempt " + + appAttemptId); + return historyData; + } catch (IOException e) { + LOG.error("Error when reading history file of application attempt" + + appAttemptId); + throw e; + } finally { + hfReader.close(); + } + } + + @Override + public ContainerHistoryData getContainer(ContainerId containerId) + throws IOException { + HistoryFileReader hfReader = + getHistoryFileReader(containerId.getApplicationAttemptId() + .getApplicationId()); + try { + boolean readStartData = false; + boolean readFinishData = false; + ContainerHistoryData historyData = + ContainerHistoryData.newInstance(containerId, null, null, null, + Long.MIN_VALUE, Long.MAX_VALUE, null, null, Integer.MAX_VALUE, + null); + while ((!readStartData || !readFinishData) && hfReader.hasNext()) { + HistoryFileReader.Entry entry = hfReader.next(); + if (entry.key.id.equals(containerId.toString())) { + if (entry.key.suffix.equals(START_DATA_SUFFIX)) { + ContainerStartData startData = + parseContainerStartData(entry.value); + mergeContainerHistoryData(historyData, startData); + readStartData = true; + } else if (entry.key.suffix.equals(FINISH_DATA_SUFFIX)) { + ContainerFinishData finishData = + parseContainerFinishData(entry.value); + mergeContainerHistoryData(historyData, finishData); + readFinishData = true; + } + } + } + if (!readStartData && !readFinishData) { + return null; + } + if (!readStartData) { + LOG.warn("Start information is missing for container " + containerId); + } + if (!readFinishData) { + LOG.warn("Finish information is missing for container " + containerId); + } + LOG.info("Completed reading history information of container " + + containerId); + return historyData; + } catch (IOException e) { + LOG.error("Error when reading history file of container " + containerId); + throw e; + } finally { + hfReader.close(); + } + } + + @Override + public ContainerHistoryData getAMContainer(ApplicationAttemptId appAttemptId) + throws IOException { + ApplicationAttemptHistoryData attemptHistoryData = + getApplicationAttempt(appAttemptId); + if (attemptHistoryData == null + || attemptHistoryData.getMasterContainerId() == null) { + return null; + } + return getContainer(attemptHistoryData.getMasterContainerId()); + } + + @Override + public Map<ContainerId, ContainerHistoryData> getContainers( + ApplicationAttemptId appAttemptId) throws IOException { + Map<ContainerId, ContainerHistoryData> historyDataMap = + new HashMap<ContainerId, ContainerHistoryData>(); + Map<ContainerId, StartFinishDataPair<ContainerStartData, ContainerFinishData>> startFinshDataMap = + new HashMap<ContainerId, StartFinishDataPair<ContainerStartData, ContainerFinishData>>(); + HistoryFileReader hfReader = + getHistoryFileReader(appAttemptId.getApplicationId()); + try { + while (hfReader.hasNext()) { + HistoryFileReader.Entry entry = hfReader.next(); + if (entry.key.id.startsWith(ConverterUtils.CONTAINER_PREFIX)) { + if (entry.key.suffix.equals(START_DATA_SUFFIX)) { + retrieveStartFinishData(appAttemptId, entry, startFinshDataMap, + true); + } else if (entry.key.suffix.equals(FINISH_DATA_SUFFIX)) { + retrieveStartFinishData(appAttemptId, entry, startFinshDataMap, + false); + } + } + } + LOG.info("Completed reading history information of all conatiners" + + " of application attempt " + appAttemptId); + } catch (IOException e) { + LOG.info("Error when reading history information of some containers" + + " of application attempt " + appAttemptId); + } finally { + hfReader.close(); + } + for (Map.Entry<ContainerId, StartFinishDataPair<ContainerStartData, ContainerFinishData>> entry : startFinshDataMap + .entrySet()) { + ContainerHistoryData historyData = + ContainerHistoryData.newInstance(entry.getKey(), null, null, null, + Long.MIN_VALUE, Long.MAX_VALUE, null, null, Integer.MAX_VALUE, + null); + mergeContainerHistoryData(historyData, entry.getValue().startData); + mergeContainerHistoryData(historyData, entry.getValue().finishData); + historyDataMap.put(entry.getKey(), historyData); + } + return historyDataMap; + } + + private + void + retrieveStartFinishData( + ApplicationAttemptId appAttemptId, + HistoryFileReader.Entry entry, + Map<ContainerId, StartFinishDataPair<ContainerStartData, ContainerFinishData>> startFinshDataMap, + boolean start) throws IOException { + ContainerId containerId = + ConverterUtils.toContainerId(entry.key.id); + if (containerId.getApplicationAttemptId().equals(appAttemptId)) { + StartFinishDataPair<ContainerStartData, ContainerFinishData> pair = + startFinshDataMap.get(containerId); + if (pair == null) { + pair = + new StartFinishDataPair<ContainerStartData, ContainerFinishData>(); + startFinshDataMap.put(containerId, pair); + } + if (start) { + pair.startData = parseContainerStartData(entry.value); + } else { + pair.finishData = parseContainerFinishData(entry.value); + } + } + } + + @Override + public void applicationStarted(ApplicationStartData appStart) + throws IOException { + HistoryFileWriter hfWriter = + outstandingWriters.get(appStart.getApplicationId()); + if (hfWriter == null) { + Path applicationHistoryFile = + new Path(rootDirPath, appStart.getApplicationId().toString()); + try { + hfWriter = new HistoryFileWriter(applicationHistoryFile); + LOG.info("Opened history file of application " + + appStart.getApplicationId()); + } catch (IOException e) { + LOG.error("Error when openning history file of application " + + appStart.getApplicationId()); + throw e; + } + outstandingWriters.put(appStart.getApplicationId(), hfWriter); + } else { + throw new IOException("History file of application " + + appStart.getApplicationId() + " is already opened"); + } + assert appStart instanceof ApplicationStartDataPBImpl; + try { + hfWriter.writeHistoryData(new HistoryDataKey(appStart.getApplicationId() + .toString(), START_DATA_SUFFIX), + ((ApplicationStartDataPBImpl) appStart) + .getProto().toByteArray()); + LOG.info("Start information of application " + + appStart.getApplicationId() + " is written"); + } catch (IOException e) { + LOG.error("Error when writing start information of application " + + appStart.getApplicationId()); + throw e; + } + } + + @Override + public void applicationFinished(ApplicationFinishData appFinish) + throws IOException { + HistoryFileWriter hfWriter = + getHistoryFileWriter(appFinish.getApplicationId()); + assert appFinish instanceof ApplicationFinishDataPBImpl; + try { + hfWriter.writeHistoryData( + new HistoryDataKey(appFinish.getApplicationId().toString(), + FINISH_DATA_SUFFIX), + ((ApplicationFinishDataPBImpl) appFinish).getProto().toByteArray()); + LOG.info("Finish information of application " + + appFinish.getApplicationId() + " is written"); + } catch (IOException e) { + LOG.error("Error when writing finish information of application " + + appFinish.getApplicationId()); + throw e; + } finally { + hfWriter.close(); + outstandingWriters.remove(appFinish.getApplicationId()); + } + } + + @Override + public void applicationAttemptStarted( + ApplicationAttemptStartData appAttemptStart) throws IOException { + HistoryFileWriter hfWriter = + getHistoryFileWriter(appAttemptStart.getApplicationAttemptId() + .getApplicationId()); + assert appAttemptStart instanceof ApplicationAttemptStartDataPBImpl; + try { + hfWriter.writeHistoryData( + new HistoryDataKey(appAttemptStart.getApplicationAttemptId() + .toString(), + START_DATA_SUFFIX), + ((ApplicationAttemptStartDataPBImpl) appAttemptStart).getProto() + .toByteArray()); + LOG.info("Start information of application attempt " + + appAttemptStart.getApplicationAttemptId() + " is written"); + } catch (IOException e) { + LOG.error("Error when writing start information of application attempt " + + appAttemptStart.getApplicationAttemptId()); + throw e; + } + } + + @Override + public void applicationAttemptFinished( + ApplicationAttemptFinishData appAttemptFinish) throws IOException { + HistoryFileWriter hfWriter = + getHistoryFileWriter(appAttemptFinish.getApplicationAttemptId() + .getApplicationId()); + assert appAttemptFinish instanceof ApplicationAttemptFinishDataPBImpl; + try { + hfWriter.writeHistoryData( + new HistoryDataKey(appAttemptFinish.getApplicationAttemptId() + .toString(), + FINISH_DATA_SUFFIX), + ((ApplicationAttemptFinishDataPBImpl) appAttemptFinish).getProto() + .toByteArray()); + LOG.info("Finish information of application attempt " + + appAttemptFinish.getApplicationAttemptId() + " is written"); + } catch (IOException e) { + LOG.error("Error when writing finish information of application attempt " + + appAttemptFinish.getApplicationAttemptId()); + throw e; + } + } + + @Override + public void containerStarted(ContainerStartData containerStart) + throws IOException { + HistoryFileWriter hfWriter = + getHistoryFileWriter(containerStart.getContainerId() + .getApplicationAttemptId() + .getApplicationId()); + assert containerStart instanceof ContainerStartDataPBImpl; + try { + hfWriter.writeHistoryData( + new HistoryDataKey(containerStart.getContainerId().toString(), + START_DATA_SUFFIX), + ((ContainerStartDataPBImpl) containerStart).getProto().toByteArray()); + LOG.info("Start information of container " + + containerStart.getContainerId() + " is written"); + } catch (IOException e) { + LOG.error("Error when writing start information of container " + + containerStart.getContainerId()); + throw e; + } + } + + @Override + public void containerFinished(ContainerFinishData containerFinish) + throws IOException { + HistoryFileWriter hfWriter = + getHistoryFileWriter(containerFinish.getContainerId() + .getApplicationAttemptId().getApplicationId()); + assert containerFinish instanceof ContainerFinishDataPBImpl; + try { + hfWriter.writeHistoryData( + new HistoryDataKey(containerFinish.getContainerId().toString(), + FINISH_DATA_SUFFIX), + ((ContainerFinishDataPBImpl) containerFinish).getProto() + .toByteArray()); + LOG.info("Finish information of container " + + containerFinish.getContainerId() + " is written"); + } catch (IOException e) { + LOG.error("Error when writing finish information of container " + + containerFinish.getContainerId()); + } + } + + private static ApplicationStartData parseApplicationStartData(byte[] value) + throws InvalidProtocolBufferException { + return new ApplicationStartDataPBImpl( + ApplicationStartDataProto.parseFrom(value)); + } + + private static ApplicationFinishData parseApplicationFinishData(byte[] value) + throws InvalidProtocolBufferException { + return new ApplicationFinishDataPBImpl( + ApplicationFinishDataProto.parseFrom(value)); + } + + private static ApplicationAttemptStartData parseApplicationAttemptStartData( + byte[] value) throws InvalidProtocolBufferException { + return new ApplicationAttemptStartDataPBImpl( + ApplicationAttemptStartDataProto.parseFrom(value)); + } + + private static ApplicationAttemptFinishData + parseApplicationAttemptFinishData( + byte[] value) throws InvalidProtocolBufferException { + return new ApplicationAttemptFinishDataPBImpl( + ApplicationAttemptFinishDataProto.parseFrom(value)); + } + + private static ContainerStartData parseContainerStartData(byte[] value) + throws InvalidProtocolBufferException { + return new ContainerStartDataPBImpl( + ContainerStartDataProto.parseFrom(value)); + } + + private static ContainerFinishData parseContainerFinishData(byte[] value) + throws InvalidProtocolBufferException { + return new ContainerFinishDataPBImpl( + ContainerFinishDataProto.parseFrom(value)); + } + + private static void mergeApplicationHistoryData( + ApplicationHistoryData historyData, + ApplicationStartData startData) { + historyData.setApplicationName(startData.getApplicationName()); + historyData.setApplicationType(startData.getApplicationType()); + historyData.setQueue(startData.getQueue()); + historyData.setUser(startData.getUser()); + historyData.setSubmitTime(startData.getSubmitTime()); + historyData.setStartTime(startData.getStartTime()); + } + + private static void mergeApplicationHistoryData( + ApplicationHistoryData historyData, + ApplicationFinishData finishData) { + historyData.setFinishTime(finishData.getFinishTime()); + historyData.setDiagnosticsInfo(finishData.getDiagnosticsInfo()); + historyData.setFinalApplicationStatus(finishData + .getFinalApplicationStatus()); + historyData.setYarnApplicationState(finishData.getYarnApplicationState()); + } + + private static void mergeApplicationAttemptHistoryData( + ApplicationAttemptHistoryData historyData, + ApplicationAttemptStartData startData) { + historyData.setHost(startData.getHost()); + historyData.setRPCPort(startData.getRPCPort()); + historyData.setMasterContainerId(startData.getMasterContainerId()); + } + + private static void mergeApplicationAttemptHistoryData( + ApplicationAttemptHistoryData historyData, + ApplicationAttemptFinishData finishData) { + historyData.setDiagnosticsInfo(finishData.getDiagnosticsInfo()); + historyData.setTrackingURL(finishData.getTrackingURL()); + historyData.setFinalApplicationStatus(finishData + .getFinalApplicationStatus()); + historyData.setYarnApplicationAttemptState(finishData + .getYarnApplicationAttemptState()); + } + + private static void mergeContainerHistoryData( + ContainerHistoryData historyData, ContainerStartData startData) { + historyData.setAllocatedResource(startData.getAllocatedResource()); + historyData.setAssignedNode(startData.getAssignedNode()); + historyData.setPriority(startData.getPriority()); + historyData.setStartTime(startData.getStartTime()); + } + + private static void mergeContainerHistoryData( + ContainerHistoryData historyData, ContainerFinishData finishData) { + historyData.setFinishTime(finishData.getFinishTime()); + historyData.setDiagnosticsInfo(finishData.getDiagnosticsInfo()); + historyData.setLogURL(finishData.getLogURL()); + historyData.setContainerExitStatus(finishData + .getContainerExitStatus()); + historyData.setContainerState(finishData.getContainerState()); + } + + private HistoryFileWriter getHistoryFileWriter(ApplicationId appId) + throws IOException { + HistoryFileWriter hfWriter = outstandingWriters.get(appId); + if (hfWriter == null) { + throw new IOException("History file of application " + appId + + " is not opened"); + } + return hfWriter; + } + + private HistoryFileReader getHistoryFileReader(ApplicationId appId) + throws IOException { + Path applicationHistoryFile = new Path(rootDirPath, appId.toString()); + if (!fs.exists(applicationHistoryFile)) { + throw new IOException("History file for application " + appId + + " is not found"); + } + // The history file is still under writing + if (outstandingWriters.containsKey(appId)) { + throw new IOException("History file for application " + appId + + " is under writing"); + } + return new HistoryFileReader(applicationHistoryFile); + } + + private class HistoryFileReader { + + private class Entry { + + private HistoryDataKey key; + private byte[] value; + + public Entry(HistoryDataKey key, byte[] value) { + this.key = key; + this.value = value; + } + } + + private FSDataInputStream fsdis; + private TFile.Reader reader; + private TFile.Reader.Scanner scanner; + + public HistoryFileReader(Path historyFile) throws IOException { + FSDataInputStream fsdis = fs.open(historyFile); + reader = + new TFile.Reader(fsdis, fs.getFileStatus(historyFile).getLen(), + getConfig()); + reset(); + } + + public boolean hasNext() { + return !scanner.atEnd(); + } + + public Entry next() throws IOException { + TFile.Reader.Scanner.Entry entry = scanner.entry(); + DataInputStream dis = entry.getKeyStream(); + HistoryDataKey key = new HistoryDataKey(); + key.readFields(dis); + dis = entry.getValueStream(); + byte[] value = new byte[entry.getValueLength()]; + dis.read(value); + scanner.advance(); + return new Entry(key, value); + } + + public void reset() throws IOException { + IOUtils.cleanup(LOG, scanner); + scanner = reader.createScanner(); + } + + public void close() { + IOUtils.cleanup(LOG, scanner, reader, fsdis); + } + + } + + private class HistoryFileWriter { + + private FSDataOutputStream fsdos; + private TFile.Writer writer; + + public HistoryFileWriter(Path historyFile) + throws IOException { + if (fs.exists(historyFile)) { + fsdos = fs.append(historyFile); + } else { + fsdos = fs.create(historyFile); + } + fs.setPermission(historyFile, HISTORY_FILE_UMASK); + writer = + new TFile.Writer(fsdos, MIN_BLOCK_SIZE, getConfig().get( + YarnConfiguration.FS_HISTORY_STORE_COMPRESSION_TYPE, + YarnConfiguration.DEFAULT_FS_HISTORY_STORE_COMPRESSION_TYPE), + null, getConfig()); + } + + public synchronized void close() { + IOUtils.cleanup(LOG, writer, fsdos); + } + + public synchronized void writeHistoryData(HistoryDataKey key, byte[] value) + throws IOException { + DataOutputStream dos = null; + try { + dos = writer.prepareAppendKey(-1); + key.write(dos); + } finally { + IOUtils.cleanup(LOG, dos); + } + try { + dos = writer.prepareAppendValue(value.length); + dos.write(value); + } finally { + IOUtils.cleanup(LOG, dos); + } + } + + } + + private static class HistoryDataKey implements Writable { + + private String id; + + private String suffix; + + public HistoryDataKey() { + this(null, null); + } + + public HistoryDataKey(String id, String suffix) { + this.id = id; + this.suffix = suffix; + } + + @Override + public void write(DataOutput out) throws IOException { + out.writeUTF(id); + out.writeUTF(suffix); + } + + @Override + public void readFields(DataInput in) throws IOException { + id = in.readUTF(); + suffix = in.readUTF(); + } + + } + + private static class StartFinishDataPair<S, F> { + + private S startData; + private F finishData; + + } + +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java new file mode 100644 index 0000000000000..d4a431f4ecb7f --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java @@ -0,0 +1,198 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.applicationhistoryservice; + +import java.io.IOException; +import java.net.URI; + +import junit.framework.Assert; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.RawLocalFileSystem; +import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; +import org.apache.hadoop.yarn.api.records.ApplicationId; +import org.apache.hadoop.yarn.api.records.ContainerId; +import org.apache.hadoop.yarn.api.records.Priority; +import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ApplicationAttemptHistoryData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ApplicationHistoryData; +import org.apache.hadoop.yarn.server.applicationhistoryservice.records.ContainerHistoryData; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class TestFileSystemApplicationHistoryStore extends + ApplicationHistoryStoreTestUtils { + + private FileSystem fs; + private Path fsWorkingPath; + + @Before + public void setup() throws Exception { + fs = new RawLocalFileSystem(); + Configuration conf = new Configuration(); + fs.initialize(new URI("/"), conf); + fsWorkingPath = new Path("Test"); + fs.delete(fsWorkingPath, true); + conf.set(YarnConfiguration.FS_HISTORY_STORE_URI, fsWorkingPath.toString()); + store = new FileSystemApplicationHistoryStore(); + store.init(conf); + store.start(); + } + + @After + public void tearDown() throws Exception { + store.stop(); + fs.delete(fsWorkingPath, true); + fs.close(); + } + + @Test + public void testReadWriteHistoryData() throws IOException { + testWriteHistoryData(5); + testReadHistoryData(5); + } + + private void testWriteHistoryData(int num) throws IOException { + // write application history data + for (int i = 1; i <= num; ++i) { + ApplicationId appId = ApplicationId.newInstance(0, i); + writeApplicationStartData(appId); + + // write application attempt history data + for (int j = 1; j <= num; ++j) { + ApplicationAttemptId appAttemptId = + ApplicationAttemptId.newInstance(appId, j); + writeApplicationAttemptStartData(appAttemptId); + + // write container history data + for (int k = 1; k <= num; ++k) { + ContainerId containerId = ContainerId.newInstance(appAttemptId, k); + writeContainerStartData(containerId); + writeContainerFinishData(containerId); + + writeApplicationAttemptFinishData(appAttemptId); + } + } + + writeApplicationFinishData(appId); + } + } + + private void testReadHistoryData(int num) throws IOException { + // read application history data + Assert.assertEquals(num, store.getAllApplications().size()); + for (int i = 1; i <= num; ++i) { + ApplicationId appId = ApplicationId.newInstance(0, i); + ApplicationHistoryData appData = store.getApplication(appId); + Assert.assertNotNull(appData); + Assert.assertEquals(appId.toString(), appData.getApplicationName()); + Assert.assertEquals(appId.toString(), appData.getDiagnosticsInfo()); + + // read application attempt history data + Assert.assertEquals( + num, store.getApplicationAttempts(appId).size()); + for (int j = 1; j <= num; ++j) { + ApplicationAttemptId appAttemptId = + ApplicationAttemptId.newInstance(appId, j); + ApplicationAttemptHistoryData attemptData = + store.getApplicationAttempt(appAttemptId); + Assert.assertNotNull(attemptData); + Assert.assertEquals(appAttemptId.toString(), attemptData.getHost()); + Assert.assertEquals(appAttemptId.toString(), + attemptData.getDiagnosticsInfo()); + + // read container history data + Assert.assertEquals( + num, store.getContainers(appAttemptId).size()); + for (int k = 1; k <= num; ++k) { + ContainerId containerId = ContainerId.newInstance(appAttemptId, k); + ContainerHistoryData containerData = store.getContainer(containerId); + Assert.assertNotNull(containerData); + Assert.assertEquals(Priority.newInstance(containerId.getId()), + containerData.getPriority()); + Assert.assertEquals(containerId.toString(), + containerData.getDiagnosticsInfo()); + } + ContainerHistoryData masterContainer = + store.getAMContainer(appAttemptId); + Assert.assertNotNull(masterContainer); + Assert.assertEquals(ContainerId.newInstance(appAttemptId, 1), + masterContainer.getContainerId()); + } + } + } + + @Test + public void testWriteAfterApplicationFinish() throws IOException { + ApplicationId appId = ApplicationId.newInstance(0, 1); + writeApplicationStartData(appId); + writeApplicationFinishData(appId); + // write application attempt history data + ApplicationAttemptId appAttemptId = + ApplicationAttemptId.newInstance(appId, 1); + try { + writeApplicationAttemptStartData(appAttemptId); + Assert.fail(); + } catch (IOException e) { + Assert.assertTrue(e.getMessage().contains("is not opened")); + } + try { + writeApplicationAttemptFinishData(appAttemptId); + Assert.fail(); + } catch (IOException e) { + Assert.assertTrue(e.getMessage().contains("is not opened")); + } + // write container history data + ContainerId containerId = ContainerId.newInstance(appAttemptId, 1); + try { + writeContainerStartData(containerId); + Assert.fail(); + } catch (IOException e) { + Assert.assertTrue(e.getMessage().contains("is not opened")); + } + try { + writeContainerFinishData(containerId); + Assert.fail(); + } catch (IOException e) { + Assert.assertTrue(e.getMessage().contains("is not opened")); + } + } + + @Test + public void testMassiveWriteContainerHistoryData() throws IOException { + long mb = 1024 * 1024; + long usedDiskBefore = fs.getContentSummary(fsWorkingPath).getLength() / mb; + ApplicationId appId = ApplicationId.newInstance(0, 1); + writeApplicationStartData(appId); + ApplicationAttemptId appAttemptId = + ApplicationAttemptId.newInstance(appId, 1); + for (int i = 1; i <= 100000; ++i) { + ContainerId containerId = ContainerId.newInstance(appAttemptId, i); + writeContainerStartData(containerId); + writeContainerFinishData(containerId); + } + writeApplicationFinishData(appId); + long usedDiskAfter = fs.getContentSummary(fsWorkingPath).getLength() / mb; + Assert.assertTrue((usedDiskAfter - usedDiskBefore) < 20); + } + +}
a6cbe8419351fcd8d26f1660dd4b112a7cd64e0b
camel
removed the generics from the Process interface- so that it must take an Exchange parameter to avoid ClassCastException when- sending any old Exchange into an Endpoint<FooExchange>--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@534145 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/CamelClient.java b/camel-core/src/main/java/org/apache/camel/CamelClient.java index 7a31a33ec893c..95e67ce1011a3 100644 --- a/camel-core/src/main/java/org/apache/camel/CamelClient.java +++ b/camel-core/src/main/java/org/apache/camel/CamelClient.java @@ -58,7 +58,7 @@ public E send(String endpointUri, E exchange) { * @param endpointUri the endpoint URI to send the exchange to * @param processor the transformer used to populate the new exchange */ - public E send(String endpointUri, Processor<E> processor) { + public E send(String endpointUri, Processor processor) { Endpoint endpoint = resolveMandatoryEndpoint(endpointUri); return send(endpoint, processor); } @@ -70,7 +70,8 @@ public E send(String endpointUri, Processor<E> processor) { * @param exchange the exchange to send */ public E send(Endpoint<E> endpoint, E exchange) { - producerCache.send(endpoint, exchange); + E convertedExchange = endpoint.toExchangeType(exchange); + producerCache.send(endpoint, convertedExchange); return exchange; } @@ -80,7 +81,7 @@ public E send(Endpoint<E> endpoint, E exchange) { * @param endpoint the endpoint to send the exchange to * @param processor the transformer used to populate the new exchange */ - public E send(Endpoint<E> endpoint, Processor<E> processor) { + public E send(Endpoint<E> endpoint, Processor processor) { return producerCache.send(endpoint, processor); } diff --git a/camel-core/src/main/java/org/apache/camel/Endpoint.java b/camel-core/src/main/java/org/apache/camel/Endpoint.java index d70cc7bba86e1..39de94562359c 100644 --- a/camel-core/src/main/java/org/apache/camel/Endpoint.java +++ b/camel-core/src/main/java/org/apache/camel/Endpoint.java @@ -48,7 +48,12 @@ public interface Endpoint<E extends Exchange> { * Creates a new exchange for communicating with this exchange using the given exchange to pre-populate the values * of the headers and messages */ - E createExchange(E exchange); + E createExchange(Exchange exchange); + + /** + * Converts the given exchange to this endpoints required type + */ + E toExchangeType(Exchange exchange); /** * Returns the context which created the endpoint @@ -69,6 +74,5 @@ public interface Endpoint<E extends Exchange> { * * @return a newly created consumer */ - Consumer<E> createConsumer(Processor<E> processor) throws Exception; - + Consumer<E> createConsumer(Processor processor) throws Exception; } diff --git a/camel-core/src/main/java/org/apache/camel/Processor.java b/camel-core/src/main/java/org/apache/camel/Processor.java index 86a00a255cf8b..6ac8080758236 100644 --- a/camel-core/src/main/java/org/apache/camel/Processor.java +++ b/camel-core/src/main/java/org/apache/camel/Processor.java @@ -25,12 +25,12 @@ * * @version $Revision$ */ -public interface Processor<E> { +public interface Processor { /** * Processes the message exchange * * @throws Exception if an internal processing error has occurred. */ - void process(E exchange) throws Exception; + void process(Exchange exchange) throws Exception; } diff --git a/camel-core/src/main/java/org/apache/camel/Producer.java b/camel-core/src/main/java/org/apache/camel/Producer.java index 9f679156dc5ba..2aad603173d58 100644 --- a/camel-core/src/main/java/org/apache/camel/Producer.java +++ b/camel-core/src/main/java/org/apache/camel/Producer.java @@ -22,7 +22,8 @@ * * @version $Revision$ */ -public interface Producer<E extends Exchange> extends Processor<E>, Service { +public interface Producer<E extends Exchange> extends Processor, Service { + Endpoint<E> getEndpoint(); /** diff --git a/camel-core/src/main/java/org/apache/camel/Route.java b/camel-core/src/main/java/org/apache/camel/Route.java index 2c30f968dcaca..6745d2102b92b 100644 --- a/camel-core/src/main/java/org/apache/camel/Route.java +++ b/camel-core/src/main/java/org/apache/camel/Route.java @@ -31,9 +31,9 @@ public class Route<E extends Exchange> { private final Map<String, Object> properties = new HashMap<String, Object>(16); private Endpoint<E> endpoint; - private Processor<E> processor; + private Processor processor; - public Route(Endpoint<E> endpoint, Processor<E> processor) { + public Route(Endpoint<E> endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } @@ -51,11 +51,11 @@ public void setEndpoint(Endpoint<E> endpoint) { this.endpoint = endpoint; } - public Processor<E> getProcessor() { + public Processor getProcessor() { return processor; } - public void setProcessor(Processor<E> processor) { + public void setProcessor(Processor processor) { this.processor = processor; } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ConstantProcessorBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ConstantProcessorBuilder.java index 8626c07cd7be1..fb93f87c8d797 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ConstantProcessorBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ConstantProcessorBuilder.java @@ -23,14 +23,14 @@ /** * @version $Revision$ */ -public class ConstantProcessorBuilder<E extends Exchange> implements ProcessorFactory<E> { - private Processor<E> processor; +public class ConstantProcessorBuilder implements ProcessorFactory { + private Processor processor; - public ConstantProcessorBuilder(Processor<E> processor) { + public ConstantProcessorBuilder(Processor processor) { this.processor = processor; } - public Processor<E> createProcessor() { + public Processor createProcessor() { return processor; } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/DeadLetterChannelBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/DeadLetterChannelBuilder.java index b2ae7f9657563..1bd98add66662 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/DeadLetterChannelBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/DeadLetterChannelBuilder.java @@ -33,64 +33,64 @@ * * @version $Revision$ */ -public class DeadLetterChannelBuilder<E extends Exchange> implements ErrorHandlerBuilder<E> { +public class DeadLetterChannelBuilder implements ErrorHandlerBuilder { private RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); - private ProcessorFactory<E> deadLetterFactory; - private Processor<E> defaultDeadLetterEndpoint; - private Expression<E> defaultDeadLetterEndpointExpression; + private ProcessorFactory deadLetterFactory; + private Processor defaultDeadLetterEndpoint; + private Expression defaultDeadLetterEndpointExpression; private String defaultDeadLetterEndpointUri = "log:org.apache.camel.DeadLetterChannel:error"; - private Logger<E> logger = DeadLetterChannel.createDefaultLogger(); + private Logger logger = DeadLetterChannel.createDefaultLogger(); public DeadLetterChannelBuilder() { } - public DeadLetterChannelBuilder(Processor<E> processor) { - this(new ConstantProcessorBuilder<E>(processor)); + public DeadLetterChannelBuilder(Processor processor) { + this(new ConstantProcessorBuilder(processor)); } - public DeadLetterChannelBuilder(ProcessorFactory<E> deadLetterFactory) { + public DeadLetterChannelBuilder(ProcessorFactory deadLetterFactory) { this.deadLetterFactory = deadLetterFactory; } - public ErrorHandlerBuilder<E> copy() { - DeadLetterChannelBuilder<E> answer = new DeadLetterChannelBuilder<E>(deadLetterFactory); + public ErrorHandlerBuilder copy() { + DeadLetterChannelBuilder answer = new DeadLetterChannelBuilder(deadLetterFactory); answer.setRedeliveryPolicy(getRedeliveryPolicy().copy()); return answer; } - public Processor<E> createErrorHandler(Processor<E> processor) throws Exception { - Processor<E> deadLetter = getDeadLetterFactory().createProcessor(); - return new DeadLetterChannel<E>(processor, deadLetter, getRedeliveryPolicy(), getLogger()); + public Processor createErrorHandler(Processor processor) throws Exception { + Processor deadLetter = getDeadLetterFactory().createProcessor(); + return new DeadLetterChannel(processor, deadLetter, getRedeliveryPolicy(), getLogger()); } // Builder methods //------------------------------------------------------------------------- - public DeadLetterChannelBuilder<E> backOffMultiplier(double backOffMultiplier) { + public DeadLetterChannelBuilder backOffMultiplier(double backOffMultiplier) { getRedeliveryPolicy().backOffMultiplier(backOffMultiplier); return this; } - public DeadLetterChannelBuilder<E> collisionAvoidancePercent(short collisionAvoidancePercent) { + public DeadLetterChannelBuilder collisionAvoidancePercent(short collisionAvoidancePercent) { getRedeliveryPolicy().collisionAvoidancePercent(collisionAvoidancePercent); return this; } - public DeadLetterChannelBuilder<E> initialRedeliveryDelay(long initialRedeliveryDelay) { + public DeadLetterChannelBuilder initialRedeliveryDelay(long initialRedeliveryDelay) { getRedeliveryPolicy().initialRedeliveryDelay(initialRedeliveryDelay); return this; } - public DeadLetterChannelBuilder<E> maximumRedeliveries(int maximumRedeliveries) { + public DeadLetterChannelBuilder maximumRedeliveries(int maximumRedeliveries) { getRedeliveryPolicy().maximumRedeliveries(maximumRedeliveries); return this; } - public DeadLetterChannelBuilder<E> useCollisionAvoidance() { + public DeadLetterChannelBuilder useCollisionAvoidance() { getRedeliveryPolicy().useCollisionAvoidance(); return this; } - public DeadLetterChannelBuilder<E> useExponentialBackOff() { + public DeadLetterChannelBuilder useExponentialBackOff() { getRedeliveryPolicy().useExponentialBackOff(); return this; } @@ -98,7 +98,7 @@ public DeadLetterChannelBuilder<E> useExponentialBackOff() { /** * Sets the logger used for caught exceptions */ - public DeadLetterChannelBuilder<E> logger(Logger<E> logger) { + public DeadLetterChannelBuilder logger(Logger logger) { setLogger(logger); return this; } @@ -106,7 +106,7 @@ public DeadLetterChannelBuilder<E> logger(Logger<E> logger) { /** * Sets the logging level of exceptions caught */ - public DeadLetterChannelBuilder<E> loggingLevel(LoggingLevel level) { + public DeadLetterChannelBuilder loggingLevel(LoggingLevel level) { getLogger().setLevel(level); return this; } @@ -114,7 +114,7 @@ public DeadLetterChannelBuilder<E> loggingLevel(LoggingLevel level) { /** * Sets the log used for caught exceptions */ - public DeadLetterChannelBuilder<E> log(Log log) { + public DeadLetterChannelBuilder log(Log log) { getLogger().setLog(log); return this; } @@ -122,14 +122,14 @@ public DeadLetterChannelBuilder<E> log(Log log) { /** * Sets the log used for caught exceptions */ - public DeadLetterChannelBuilder<E> log(String log) { + public DeadLetterChannelBuilder log(String log) { return log(LogFactory.getLog(log)); } /** * Sets the log used for caught exceptions */ - public DeadLetterChannelBuilder<E> log(Class log) { + public DeadLetterChannelBuilder log(Class log) { return log(LogFactory.getLog(log)); } @@ -146,10 +146,10 @@ public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) { this.redeliveryPolicy = redeliveryPolicy; } - public ProcessorFactory<E> getDeadLetterFactory() { + public ProcessorFactory getDeadLetterFactory() { if (deadLetterFactory == null) { - deadLetterFactory = new ProcessorFactory<E>() { - public Processor<E> createProcessor() { + deadLetterFactory = new ProcessorFactory() { + public Processor createProcessor() { return getDefaultDeadLetterEndpoint(); } }; @@ -160,13 +160,13 @@ public Processor<E> createProcessor() { /** * Sets the default dead letter queue factory */ - public void setDeadLetterFactory(ProcessorFactory<E> deadLetterFactory) { + public void setDeadLetterFactory(ProcessorFactory deadLetterFactory) { this.deadLetterFactory = deadLetterFactory; } - public Processor<E> getDefaultDeadLetterEndpoint() { + public Processor getDefaultDeadLetterEndpoint() { if (defaultDeadLetterEndpoint == null) { - defaultDeadLetterEndpoint = new RecipientList<E>(getDefaultDeadLetterEndpointExpression()); + defaultDeadLetterEndpoint = new RecipientList(getDefaultDeadLetterEndpointExpression()); } return defaultDeadLetterEndpoint; } @@ -174,11 +174,11 @@ public Processor<E> getDefaultDeadLetterEndpoint() { /** * Sets the default dead letter endpoint used */ - public void setDefaultDeadLetterEndpoint(Processor<E> defaultDeadLetterEndpoint) { + public void setDefaultDeadLetterEndpoint(Processor defaultDeadLetterEndpoint) { this.defaultDeadLetterEndpoint = defaultDeadLetterEndpoint; } - public Expression<E> getDefaultDeadLetterEndpointExpression() { + public Expression getDefaultDeadLetterEndpointExpression() { if (defaultDeadLetterEndpointExpression == null) { defaultDeadLetterEndpointExpression = ExpressionBuilder.constantExpression(getDefaultDeadLetterEndpointUri()); } @@ -189,7 +189,7 @@ public Expression<E> getDefaultDeadLetterEndpointExpression() { * Sets the expression used to decide the dead letter channel endpoint for an exchange * if no factory is provided via {@link #setDeadLetterFactory(ProcessorFactory)} */ - public void setDefaultDeadLetterEndpointExpression(Expression<E> defaultDeadLetterEndpointExpression) { + public void setDefaultDeadLetterEndpointExpression(Expression defaultDeadLetterEndpointExpression) { this.defaultDeadLetterEndpointExpression = defaultDeadLetterEndpointExpression; } @@ -207,11 +207,11 @@ public void setDefaultDeadLetterEndpointUri(String defaultDeadLetterEndpointUri) this.defaultDeadLetterEndpointUri = defaultDeadLetterEndpointUri; } - public Logger<E> getLogger() { + public Logger getLogger() { return logger; } - public void setLogger(Logger<E> logger) { + public void setLogger(Logger logger) { this.logger = logger; } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java index 3d9432e7ec5a1..ffbe3ea244e3c 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java @@ -32,5 +32,5 @@ public interface ErrorHandlerBuilder<E extends Exchange> { /** * Creates the error handler interceptor */ - Processor<E> createErrorHandler(Processor<E> processor) throws Exception; + Processor createErrorHandler(Processor processor) throws Exception; } diff --git a/camel-core/src/main/java/org/apache/camel/builder/FilterBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/FilterBuilder.java index 814a567583941..9578afce5c95f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/FilterBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/FilterBuilder.java @@ -24,10 +24,10 @@ /** * @version $Revision$ */ -public class FilterBuilder<E extends Exchange> extends FromBuilder<E> { - private Predicate<E> predicate; +public class FilterBuilder extends FromBuilder { + private Predicate predicate; - public FilterBuilder(FromBuilder<E> builder, Predicate<E> predicate) { + public FilterBuilder(FromBuilder builder, Predicate predicate) { super(builder); this.predicate = predicate; } @@ -35,7 +35,7 @@ public FilterBuilder(FromBuilder<E> builder, Predicate<E> predicate) { /** * Adds another predicate using a logical AND */ - public FilterBuilder<E> and(Predicate<E> predicate) { + public FilterBuilder and(Predicate predicate) { this.predicate = PredicateBuilder.and(this.predicate, predicate); return this; } @@ -43,19 +43,19 @@ public FilterBuilder<E> and(Predicate<E> predicate) { /** * Adds another predicate using a logical OR */ - public FilterBuilder<E> or(Predicate<E> predicate) { + public FilterBuilder or(Predicate predicate) { this.predicate = PredicateBuilder.or(this.predicate, predicate); return this; } - public Predicate<E> getPredicate() { + public Predicate getPredicate() { return predicate; } - public FilterProcessor<E> createProcessor() throws Exception { + public FilterProcessor createProcessor() throws Exception { // lets create a single processor for all child predicates - Processor<E> childProcessor = super.createProcessor(); - return new FilterProcessor<E>(predicate, childProcessor); + Processor childProcessor = super.createProcessor(); + return new FilterProcessor(predicate, childProcessor); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/FromBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/FromBuilder.java index 9965827b6c0eb..98cc2de5e995f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/FromBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/FromBuilder.java @@ -39,7 +39,7 @@ /** * @version $Revision$ */ -public class FromBuilder<E extends Exchange> extends BuilderSupport implements ProcessorFactory<E> { +public class FromBuilder extends BuilderSupport implements ProcessorFactory { public static final String DEFAULT_TRACE_CATEGORY = "org.apache.camel.TRACE"; @@ -264,7 +264,7 @@ public FromBuilder trace() { @Fluent public FromBuilder trace(@FluentArg("category")String category) { final Log log = LogFactory.getLog(category); - return intercept(new DelegateProcessor<Exchange>(){ + return intercept(new DelegateProcessor(){ @Override public void process(Exchange exchange) throws Exception { log.trace(exchange); diff --git a/camel-core/src/main/java/org/apache/camel/builder/IdempotentConsumerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/IdempotentConsumerBuilder.java index 3a24e0b0b16e8..c70b13d3c5738 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/IdempotentConsumerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/IdempotentConsumerBuilder.java @@ -28,8 +28,8 @@ * * @version $Revision: 1.1 $ */ -public class IdempotentConsumerBuilder<E extends Exchange> extends FromBuilder<E> implements ProcessorFactory<E> { - private final Expression<E> messageIdExpression; +public class IdempotentConsumerBuilder extends FromBuilder implements ProcessorFactory { + private final Expression messageIdExpression; private final MessageIdRepository messageIdRegistry; public IdempotentConsumerBuilder(FromBuilder fromBuilder, Expression messageIdExpression, MessageIdRepository messageIdRegistry) { diff --git a/camel-core/src/main/java/org/apache/camel/builder/InterceptorBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/InterceptorBuilder.java index b21b9f9fc52f0..f081eb924b85e 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/InterceptorBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/InterceptorBuilder.java @@ -28,37 +28,37 @@ /** * @version $Revision: 519943 $ */ -public class InterceptorBuilder<E extends Exchange> implements ProcessorFactory<E> { - private final List<DelegateProcessor<E>> intercepts = new ArrayList<DelegateProcessor<E>>(); - private final FromBuilder<E> parent; - private FromBuilder<E> target; +public class InterceptorBuilder implements ProcessorFactory { + private final List<DelegateProcessor> intercepts = new ArrayList<DelegateProcessor>(); + private final FromBuilder parent; + private FromBuilder target; - public InterceptorBuilder(FromBuilder<E> parent) { + public InterceptorBuilder(FromBuilder parent) { this.parent = parent; } @Fluent("interceptor") - public InterceptorBuilder<E> add(@FluentArg("ref") DelegateProcessor<E> interceptor) { + public InterceptorBuilder add(@FluentArg("ref") DelegateProcessor interceptor) { intercepts.add(interceptor); return this; } @Fluent(callOnElementEnd=true) - public FromBuilder<E> target() { - this.target = new FromBuilder<E>(parent); + public FromBuilder target() { + this.target = new FromBuilder(parent); return target; } - public Processor<E> createProcessor() throws Exception { + public Processor createProcessor() throws Exception { // The target is required. if( target == null ) throw new RuntimeCamelException("target provided."); // Interceptors are optional - DelegateProcessor<E> first=null; - DelegateProcessor<E> last=null; - for (DelegateProcessor<E> p : intercepts) { + DelegateProcessor first=null; + DelegateProcessor last=null; + for (DelegateProcessor p : intercepts) { if( first == null ) { first = p; } @@ -68,7 +68,7 @@ public Processor<E> createProcessor() throws Exception { last = p; } - Processor<E> p = target.createProcessor(); + Processor p = target.createProcessor(); if( last != null ) { last.setNext(p); } diff --git a/camel-core/src/main/java/org/apache/camel/builder/LoggingErrorHandlerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/LoggingErrorHandlerBuilder.java index 06fbfa3fcd4cf..a5c36579bab42 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/LoggingErrorHandlerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/LoggingErrorHandlerBuilder.java @@ -30,7 +30,7 @@ * * @version $Revision$ */ -public class LoggingErrorHandlerBuilder<E extends Exchange> implements ErrorHandlerBuilder<E> { +public class LoggingErrorHandlerBuilder implements ErrorHandlerBuilder { private Log log = LogFactory.getLog(Logger.class); private LoggingLevel level = LoggingLevel.INFO; @@ -46,15 +46,15 @@ public LoggingErrorHandlerBuilder(Log log, LoggingLevel level) { this.level = level; } - public ErrorHandlerBuilder<E> copy() { - LoggingErrorHandlerBuilder<E> answer = new LoggingErrorHandlerBuilder<E>(); + public ErrorHandlerBuilder copy() { + LoggingErrorHandlerBuilder answer = new LoggingErrorHandlerBuilder(); answer.setLog(getLog()); answer.setLevel(getLevel()); return answer; } - public Processor<E> createErrorHandler(Processor<E> processor) { - return new LoggingErrorHandler<E>(processor, log, level); + public Processor createErrorHandler(Processor processor) { + return new LoggingErrorHandler(processor, log, level); } public LoggingLevel getLevel() { diff --git a/camel-core/src/main/java/org/apache/camel/builder/MulticastBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/MulticastBuilder.java index f8c749be8a946..5cc77be8ee8d1 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/MulticastBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/MulticastBuilder.java @@ -29,16 +29,16 @@ * * @version $Revision$ */ -public class MulticastBuilder<E extends Exchange> extends FromBuilder<E> { - private final Collection<Endpoint<E>> endpoints; +public class MulticastBuilder extends FromBuilder { + private final Collection<Endpoint> endpoints; - public MulticastBuilder(FromBuilder<E> parent, Collection<Endpoint<E>> endpoints) { + public MulticastBuilder(FromBuilder parent, Collection<Endpoint> endpoints) { super(parent); this.endpoints = endpoints; } @Override - public Processor<E> createProcessor() throws Exception { - return new MulticastProcessor<E>(endpoints); + public Processor createProcessor() throws Exception { + return new MulticastProcessor(endpoints); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/NoErrorHandlerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/NoErrorHandlerBuilder.java index c99692ae081ba..f602231720c1f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/NoErrorHandlerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/NoErrorHandlerBuilder.java @@ -34,7 +34,7 @@ public ErrorHandlerBuilder<E> copy() { return this; } - public Processor<E> createErrorHandler(Processor<E> processor) { + public Processor createErrorHandler(Processor processor) { return processor; } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/PipelineBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/PipelineBuilder.java index 6737f9bd112bd..355d4d6a74577 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/PipelineBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/PipelineBuilder.java @@ -29,16 +29,16 @@ * * @version $Revision$ */ -public class PipelineBuilder<E extends Exchange> extends FromBuilder<E> { - private final Collection<Endpoint<E>> endpoints; +public class PipelineBuilder extends FromBuilder { + private final Collection<Endpoint> endpoints; - public PipelineBuilder(FromBuilder<E> parent, Collection<Endpoint<E>> endpoints) { + public PipelineBuilder(FromBuilder parent, Collection<Endpoint> endpoints) { super(parent); this.endpoints = endpoints; } @Override - public Processor<E> createProcessor() throws Exception { - return new Pipeline<E>(endpoints); + public Processor createProcessor() throws Exception { + return new Pipeline(endpoints); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/PolicyBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/PolicyBuilder.java index c309f6b599b9f..cd7772cf617b2 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/PolicyBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/PolicyBuilder.java @@ -28,36 +28,36 @@ /** * @version $Revision: 519943 $ */ -public class PolicyBuilder<E extends Exchange> implements ProcessorFactory<E> { - private final ArrayList<Policy<E>> policies = new ArrayList<Policy<E>>(); - private final FromBuilder<E> parent; - private FromBuilder<E> target; +public class PolicyBuilder implements ProcessorFactory { + private final ArrayList<Policy> policies = new ArrayList<Policy>(); + private final FromBuilder parent; + private FromBuilder target; - public PolicyBuilder(FromBuilder<E> parent) { + public PolicyBuilder(FromBuilder parent) { this.parent = parent; } @Fluent("policy") - public PolicyBuilder<E> add(@FluentArg("ref") Policy<E> interceptor) { + public PolicyBuilder add(@FluentArg("ref") Policy interceptor) { policies.add(interceptor); return this; } @Fluent(callOnElementEnd=true) - public FromBuilder<E> target() { - this.target = new FromBuilder<E>(parent); + public FromBuilder target() { + this.target = new FromBuilder(parent); return target; } - public Processor<E> createProcessor() throws Exception { + public Processor createProcessor() throws Exception { // The target is required. if( target == null ) throw new RuntimeCamelException("target not provided."); - Processor<E> last = target.createProcessor(); + Processor last = target.createProcessor(); Collections.reverse(policies); - for (Policy<E> p : policies) { + for (Policy p : policies) { last = p.wrap(last); } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ProcessorBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ProcessorBuilder.java index 3b210e02e3801..828dba56a36aa 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ProcessorBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ProcessorBuilder.java @@ -31,9 +31,9 @@ public class ProcessorBuilder { /** * Creates a processor which sets the body of the IN message to the value of the expression */ - public static <E extends Exchange> Processor<E> setBody(final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setBody(final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object newBody = expression.evaluate(exchange); exchange.getIn().setBody(newBody); } @@ -48,9 +48,9 @@ public String toString() { /** * Creates a processor which sets the body of the IN message to the value of the expression */ - public static <E extends Exchange> Processor<E> setOutBody(final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setOutBody(final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object newBody = expression.evaluate(exchange); exchange.getOut().setBody(newBody); } @@ -65,9 +65,9 @@ public String toString() { /** * Sets the header on the IN message */ - public static <E extends Exchange> Processor<E> setHeader(final String name, final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setHeader(final String name, final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object value = expression.evaluate(exchange); exchange.getIn().setHeader(name, value); } @@ -82,9 +82,9 @@ public String toString() { /** * Sets the header on the OUT message */ - public static <E extends Exchange> Processor<E> setOutHeader(final String name, final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setOutHeader(final String name, final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object value = expression.evaluate(exchange); exchange.getOut().setHeader(name, value); } @@ -99,9 +99,9 @@ public String toString() { /** * Sets the property on the exchange */ - public static <E extends Exchange> Processor<E> setProperty(final String name, final Expression<E> expression) { - return new Processor<E>() { - public void process(E exchange) { + public static Processor setProperty(final String name, final Expression expression) { + return new Processor() { + public void process(Exchange exchange) { Object value = expression.evaluate(exchange); exchange.setProperty(name, value); } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ProcessorFactory.java b/camel-core/src/main/java/org/apache/camel/builder/ProcessorFactory.java index 7d56582e85cc6..2cd2fb8decd9f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ProcessorFactory.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ProcessorFactory.java @@ -24,8 +24,8 @@ * * @version $Revision$ */ -public interface ProcessorFactory<E extends Exchange> { +public interface ProcessorFactory { - public Processor<E> createProcessor() throws Exception; + public Processor createProcessor() throws Exception; } diff --git a/camel-core/src/main/java/org/apache/camel/builder/SplitterBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/SplitterBuilder.java index e4c220f5afe72..21ea333391e13 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/SplitterBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/SplitterBuilder.java @@ -28,17 +28,17 @@ * @version $Revision$ */ -public class SplitterBuilder<E extends Exchange> extends FromBuilder<E> { - private final Expression<E> expression; +public class SplitterBuilder extends FromBuilder { + private final Expression expression; - public SplitterBuilder(FromBuilder<E> parent, Expression<E> expression) { + public SplitterBuilder(FromBuilder parent, Expression expression) { super(parent); this.expression = expression; } - public Processor<E> createProcessor() throws Exception { + public Processor createProcessor() throws Exception { // lets create a single processor for all child predicates - Processor<E> destination = super.createProcessor(); - return new Splitter<E>(destination, expression); + Processor destination = super.createProcessor(); + return new Splitter(destination, expression); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ToBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ToBuilder.java index d2a35e8b10be0..ad7ab46fce754 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ToBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ToBuilder.java @@ -25,16 +25,16 @@ /** * @version $Revision$ */ -public class ToBuilder<E extends Exchange> extends FromBuilder<E> { - private Endpoint<E> destination; +public class ToBuilder<E extends Exchange> extends FromBuilder { + private Endpoint destination; - public ToBuilder(FromBuilder<E> parent, Endpoint<E> endpoint) { + public ToBuilder(FromBuilder parent, Endpoint endpoint) { super(parent); this.destination = endpoint; } @Override - public Processor<E> createProcessor() { - return new SendProcessor<E>(destination); + public Processor createProcessor() { + return new SendProcessor(destination); } } diff --git a/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java index 555243c7c9e21..79b181baf2b4a 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java @@ -45,7 +45,7 @@ * * @version $Revision: 531854 $ */ -public class XsltBuilder<E extends Exchange> implements Processor<E> { +public class XsltBuilder implements Processor { private Map<String, Object> parameters = new HashMap<String, Object>(); private XmlConverter converter = new XmlConverter(); private Transformer transformer; @@ -64,7 +64,7 @@ public String toString() { return "XSLT[" + transformer + "]"; } - public synchronized void process(E exchange) throws Exception { + public synchronized void process(Exchange exchange) throws Exception { Transformer transformer = getTransformer(); if (transformer == null) { throw new IllegalArgumentException("No transformer configured!"); @@ -82,16 +82,16 @@ public synchronized void process(E exchange) throws Exception { /** * Creates an XSLT processor using the given transformer instance */ - public static <E extends Exchange> XsltBuilder<E> xslt(Transformer transformer) { - return new XsltBuilder<E>(transformer); + public static XsltBuilder xslt(Transformer transformer) { + return new XsltBuilder(transformer); } /** * Creates an XSLT processor using the given XSLT source */ - public static <E extends Exchange> XsltBuilder<E> xslt(Source xslt) throws TransformerConfigurationException { + public static XsltBuilder xslt(Source xslt) throws TransformerConfigurationException { notNull(xslt, "xslt"); - XsltBuilder<E> answer = new XsltBuilder<E>(); + XsltBuilder answer = new XsltBuilder(); answer.setTransformerSource(xslt); return answer; } @@ -99,7 +99,7 @@ public static <E extends Exchange> XsltBuilder<E> xslt(Source xslt) throws Trans /** * Creates an XSLT processor using the given XSLT source */ - public static <E extends Exchange> XsltBuilder<E> xslt(File xslt) throws TransformerConfigurationException { + public static XsltBuilder xslt(File xslt) throws TransformerConfigurationException { notNull(xslt, "xslt"); return xslt(new StreamSource(xslt)); } @@ -107,7 +107,7 @@ public static <E extends Exchange> XsltBuilder<E> xslt(File xslt) throws Transfo /** * Creates an XSLT processor using the given XSLT source */ - public static <E extends Exchange> XsltBuilder<E> xslt(URL xslt) throws TransformerConfigurationException, IOException { + public static XsltBuilder xslt(URL xslt) throws TransformerConfigurationException, IOException { notNull(xslt, "xslt"); return xslt(xslt.openStream()); } @@ -115,7 +115,7 @@ public static <E extends Exchange> XsltBuilder<E> xslt(URL xslt) throws Transfor /** * Creates an XSLT processor using the given XSLT source */ - public static <E extends Exchange> XsltBuilder<E> xslt(InputStream xslt) throws TransformerConfigurationException, IOException { + public static XsltBuilder xslt(InputStream xslt) throws TransformerConfigurationException, IOException { notNull(xslt, "xslt"); return xslt(new StreamSource(xslt)); } @@ -123,7 +123,7 @@ public static <E extends Exchange> XsltBuilder<E> xslt(InputStream xslt) throws /** * Sets the output as being a byte[] */ - public XsltBuilder<E> outputBytes() { + public XsltBuilder outputBytes() { setResultHandler(new StreamResultHandler()); return this; } @@ -131,7 +131,7 @@ public XsltBuilder<E> outputBytes() { /** * Sets the output as being a String */ - public XsltBuilder<E> outputString() { + public XsltBuilder outputString() { setResultHandler(new StringResultHandler()); return this; } @@ -139,12 +139,12 @@ public XsltBuilder<E> outputString() { /** * Sets the output as being a DOM */ - public XsltBuilder<E> outputDOM() { + public XsltBuilder outputDOM() { setResultHandler(new DomResultHandler()); return this; } - public XsltBuilder<E> parameter(String name, Object value) { + public XsltBuilder parameter(String name, Object value) { parameters.put(name, value); return this; } @@ -194,7 +194,7 @@ public void setTransformerSource(Source source) throws TransformerConfigurationE /** * Converts the inbound body to a {@link Source} */ - protected Source getSource(E exchange) { + protected Source getSource(Exchange exchange) { Message in = exchange.getIn(); Source source = in.getBody(Source.class); if (source == null) { diff --git a/camel-core/src/main/java/org/apache/camel/component/direct/DirectEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/direct/DirectEndpoint.java index 29f0a43da4be2..2bca9272c7980 100644 --- a/camel-core/src/main/java/org/apache/camel/component/direct/DirectEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/direct/DirectEndpoint.java @@ -44,21 +44,21 @@ public DirectEndpoint(String uri, DirectComponent<E> component) { super(uri, component); } - public Producer<E> createProducer() throws Exception { - return startService(new DefaultProducer<E>(this) { - public void process(E exchange) throws Exception { + public Producer createProducer() throws Exception { + return startService(new DefaultProducer(this) { + public void process(Exchange exchange) throws Exception { DirectEndpoint.this.process(exchange); } }); } - protected void process(E exchange) throws Exception { + protected void process(Exchange exchange) throws Exception { for (DefaultConsumer<E> consumer : consumers) { consumer.getProcessor().process(exchange); } } - public Consumer<E> createConsumer(Processor<E> processor) throws Exception { + public Consumer<E> createConsumer(Processor processor) throws Exception { DefaultConsumer<E> consumer = new DefaultConsumer<E>(this, processor) { @Override public void start() throws Exception { diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java b/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java index 60dc89d0bef7b..ff3ad28b0e875 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java @@ -38,7 +38,7 @@ public class FileConsumer extends PollingConsumer<FileExchange> { private String regexPattern = ""; private long lastPollTime = 0l; - public FileConsumer(final FileEndpoint endpoint, Processor<FileExchange> processor) { + public FileConsumer(final FileEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java index ffba01b66e55e..3a965508e1148 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java @@ -53,7 +53,7 @@ public Producer<FileExchange> createProducer() throws Exception { * @throws Exception * @see org.apache.camel.Endpoint#createConsumer(org.apache.camel.Processor) */ - public Consumer<FileExchange> createConsumer(Processor<FileExchange> file) throws Exception { + public Consumer<FileExchange> createConsumer(Processor file) throws Exception { Consumer<FileExchange> result = new FileConsumer(this, file); configureConsumer(result); return startService(result); diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileProducer.java b/camel-core/src/main/java/org/apache/camel/component/file/FileProducer.java index 5e4e6a556477c..8738ea465abb9 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileProducer.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileProducer.java @@ -1,63 +1,70 @@ /** - * + * * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ - package org.apache.camel.component.file; -import java.io.File; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; +import org.apache.camel.Exchange; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultProducer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import java.io.File; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; + /** * A {@link Producer} implementation for File - * + * * @version $Revision: 523016 $ */ -public class FileProducer extends DefaultProducer<FileExchange>{ - - private static final transient Log log=LogFactory.getLog(FileProducer.class); +public class FileProducer extends DefaultProducer { + private static final transient Log log = LogFactory.getLog(FileProducer.class); private final FileEndpoint endpoint; - public FileProducer(FileEndpoint endpoint){ + public FileProducer(FileEndpoint endpoint) { super(endpoint); - this.endpoint=endpoint; + this.endpoint = endpoint; } /** * @param exchange - * @see org.apache.camel.Processor#process(java.lang.Object) + * @see org.apache.camel.Processor#process(Exchange) */ - public void process(FileExchange exchange){ - ByteBuffer payload=exchange.getIn().getBody(ByteBuffer.class); + public void process(Exchange exchange) { + process(endpoint.toExchangeType(exchange)); + } + + public void process(FileExchange exchange) { + ByteBuffer payload = exchange.getIn().getBody(ByteBuffer.class); payload.flip(); - File file=null; - if(endpoint.getFile()!=null&&endpoint.getFile().isDirectory()){ - file=new File(endpoint.getFile(),exchange.getFile().getName()); - }else{ - file=exchange.getFile(); + File file = null; + + if (endpoint.getFile() != null && endpoint.getFile().isDirectory()) { + file = new File(endpoint.getFile(), exchange.getFile().getName()); } - try{ - FileChannel fc=new RandomAccessFile(file,"rw").getChannel(); + else { + file = exchange.getFile(); + } + try { + FileChannel fc = new RandomAccessFile(file, "rw").getChannel(); fc.position(fc.size()); fc.write(payload); fc.close(); - }catch(Throwable e){ - log.error("Failed to write to File: "+file,e); + } + catch (Throwable e) { + log.error("Failed to write to File: " + file, e); } } } diff --git a/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java index 4409b331aaabf..cbacca7086007 100644 --- a/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/mock/MockEndpoint.java @@ -45,7 +45,7 @@ public class MockEndpoint extends DefaultEndpoint<Exchange> { private static final transient Log log = LogFactory.getLog(MockEndpoint.class); private int expectedCount = -1; - private Map<Integer, Processor<Exchange>> processors = new HashMap<Integer, Processor<Exchange>>(); + private Map<Integer, Processor> processors = new HashMap<Integer, Processor>(); private List<Exchange> receivedExchanges = new ArrayList<Exchange>(); private List<Throwable> failures = new ArrayList<Throwable>(); private List<Runnable> tests = new ArrayList<Runnable>(); @@ -93,7 +93,7 @@ public Exchange createExchange() { return new DefaultExchange(getContext()); } - public Consumer<Exchange> createConsumer(Processor<Exchange> processor) throws Exception { + public Consumer<Exchange> createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("You cannot consume from this endpoint"); } @@ -309,7 +309,7 @@ protected synchronized void onExchange(Exchange exchange) { receivedExchanges.add(exchange); - Processor<Exchange> processor = processors.get(getReceivedCounter()); + Processor processor = processors.get(getReceivedCounter()); if (processor != null) { processor.process(exchange); } diff --git a/camel-core/src/main/java/org/apache/camel/component/pojo/PojoEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/pojo/PojoEndpoint.java index 8c11efbdc0c6a..2ea513607165c 100644 --- a/camel-core/src/main/java/org/apache/camel/component/pojo/PojoEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/pojo/PojoEndpoint.java @@ -22,6 +22,7 @@ import org.apache.camel.NoSuchEndpointException; import org.apache.camel.Processor; import org.apache.camel.Producer; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.impl.DefaultProducer; @@ -46,14 +47,14 @@ public Producer<PojoExchange> createProducer() throws Exception { if( pojo == null ) throw new NoSuchEndpointException(getEndpointUri()); - return startService(new DefaultProducer<PojoExchange>(this) { - public void process(PojoExchange exchange) { - invoke(pojo, exchange); + return startService(new DefaultProducer(this) { + public void process(Exchange exchange) { + invoke(pojo, toExchangeType(exchange)); } }); } - public Consumer<PojoExchange> createConsumer(Processor<PojoExchange> processor) throws Exception { + public Consumer<PojoExchange> createConsumer(Processor processor) throws Exception { throw new Exception("You cannot consume from pojo endpoints."); } diff --git a/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerConsumer.java b/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerConsumer.java index 471fde08eb702..285a09b635b07 100644 --- a/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerConsumer.java @@ -38,7 +38,7 @@ public class TimerConsumer extends DefaultConsumer<PojoExchange> implements Invo private Timer timer; - public TimerConsumer(TimerEndpoint endpoint, Processor<PojoExchange> processor) { + public TimerConsumer(TimerEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } diff --git a/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerEndpoint.java index 63a5f1c5e624e..886ab2c41b9e5 100644 --- a/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/pojo/timer/TimerEndpoint.java @@ -62,7 +62,7 @@ public Producer<PojoExchange> createProducer() throws Exception { throw new RuntimeCamelException("Cannot produce to a TimerEndpoint: "+getEndpointUri()); } - public Consumer<PojoExchange> createConsumer(Processor<PojoExchange> processor) throws Exception { + public Consumer<PojoExchange> createConsumer(Processor processor) throws Exception { TimerConsumer consumer = new TimerConsumer(this, processor); return startService(consumer); } diff --git a/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpoint.java index c1c974b834136..9de17bfc7d01a 100644 --- a/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpoint.java @@ -34,10 +34,10 @@ * @version $Revision: 1.1 $ */ public class ProcessorEndpoint extends DefaultEndpoint<Exchange> { - private final Processor<Exchange> processor; - private final LoadBalancer<Exchange> loadBalancer; + private final Processor processor; + private final LoadBalancer loadBalancer; - protected ProcessorEndpoint(String endpointUri, Component component, Processor<Exchange> processor, LoadBalancer<Exchange> loadBalancer) { + protected ProcessorEndpoint(String endpointUri, Component component, Processor processor, LoadBalancer loadBalancer) { super(endpointUri, component); this.processor = processor; this.loadBalancer = loadBalancer; @@ -55,15 +55,15 @@ public void process(Exchange exchange) throws Exception { }); } - public Consumer<Exchange> createConsumer(Processor<Exchange> processor) throws Exception { + public Consumer<Exchange> createConsumer(Processor processor) throws Exception { return startService(new ProcessorEndpointConsumer(this, processor)); } - public Processor<Exchange> getProcessor() { + public Processor getProcessor() { return processor; } - public LoadBalancer<Exchange> getLoadBalancer() { + public LoadBalancer getLoadBalancer() { return loadBalancer; } diff --git a/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpointConsumer.java b/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpointConsumer.java index 71b68839741e9..3f7116f3c540f 100644 --- a/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpointConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/processor/ProcessorEndpointConsumer.java @@ -27,7 +27,7 @@ public class ProcessorEndpointConsumer extends DefaultConsumer<Exchange> { private final ProcessorEndpoint endpoint; - public ProcessorEndpointConsumer(ProcessorEndpoint endpoint, Processor<Exchange> processor) { + public ProcessorEndpointConsumer(ProcessorEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } diff --git a/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpoint.java index a4ada27cd7308..0f881ae7b5f12 100644 --- a/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpoint.java @@ -42,14 +42,14 @@ public QueueEndpoint(String uri, QueueComponent<E> component) { } public Producer<E> createProducer() throws Exception { - return startService(new DefaultProducer<E>(this) { - public void process(E exchange) { - queue.add(exchange); + return startService(new DefaultProducer(this) { + public void process(Exchange exchange) { + queue.add(toExchangeType(exchange)); } }); } - public Consumer<E> createConsumer(Processor<E> processor) throws Exception { + public Consumer<E> createConsumer(Processor processor) throws Exception { return startService(new QueueEndpointConsumer<E>(this, processor)); } diff --git a/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpointConsumer.java b/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpointConsumer.java index a19779a7c3ed0..122a7c6cbf2db 100644 --- a/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpointConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/queue/QueueEndpointConsumer.java @@ -29,10 +29,10 @@ */ public class QueueEndpointConsumer<E extends Exchange> extends ServiceSupport implements Consumer<E>, Runnable { private QueueEndpoint<E> endpoint; - private Processor<E> processor; + private Processor processor; private Thread thread; - public QueueEndpointConsumer(QueueEndpoint<E> endpoint, Processor<E> processor) { + public QueueEndpointConsumer(QueueEndpoint<E> endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index 9605ab1ee2042..471ab0119f323 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -295,7 +295,7 @@ protected void doStart() throws Exception { if (routes != null) { for (Route<Exchange> route : routes) { - Processor<Exchange> processor = route.getProcessor(); + Processor processor = route.getProcessor(); Consumer<Exchange> consumer = route.getEndpoint().createConsumer(processor); if (consumer != null) { consumer.start(); diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java index bdbabce80ec32..0680a143c72e4 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultConsumer.java @@ -29,10 +29,10 @@ */ public class DefaultConsumer<E extends Exchange> extends ServiceSupport implements Consumer<E> { private Endpoint<E> endpoint; - private Processor<E> processor; + private Processor processor; private ExceptionHandler exceptionHandler; - public DefaultConsumer(Endpoint<E> endpoint, Processor<E> processor) { + public DefaultConsumer(Endpoint<E> endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } @@ -41,7 +41,7 @@ public Endpoint<E> getEndpoint() { return endpoint; } - public Processor<E> getProcessor() { + public Processor getProcessor() { return processor; } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java index 08e89218ae912..477404960b728 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultEndpoint.java @@ -109,12 +109,17 @@ public E convertTo(Class<E> type, Exchange exchange) { return getContext().getExchangeConverter().convertTo(type, exchange); } - public E createExchange(E exchange) { + public E createExchange(Exchange exchange) { E answer = createExchange(); answer.copyFrom(exchange); return answer; } + public E toExchangeType(Exchange exchange) { + // TODO avoid cloning exchanges if E == Exchange! + return createExchange(exchange); + } + /** * A helper method to reduce the clutter of implementors of {@link #createProducer()} and {@link #createConsumer(Processor)} */ diff --git a/camel-core/src/main/java/org/apache/camel/impl/NoPolicy.java b/camel-core/src/main/java/org/apache/camel/impl/NoPolicy.java index d631d3ffdaffa..0740573bbb8cb 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/NoPolicy.java +++ b/camel-core/src/main/java/org/apache/camel/impl/NoPolicy.java @@ -27,7 +27,7 @@ */ public class NoPolicy<E> implements Policy<E> { - public Processor<E> wrap(Processor<E> processor) { + public Processor wrap(Processor processor) { return processor; } } diff --git a/camel-core/src/main/java/org/apache/camel/impl/PollingConsumer.java b/camel-core/src/main/java/org/apache/camel/impl/PollingConsumer.java index 12aa5ae3db8c8..8992027281164 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/PollingConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/impl/PollingConsumer.java @@ -42,11 +42,11 @@ public abstract class PollingConsumer<E extends Exchange> extends DefaultConsume private boolean useFixedDelay; private ScheduledFuture<?> future; - public PollingConsumer(DefaultEndpoint<E> endpoint, Processor<E> processor) { + public PollingConsumer(DefaultEndpoint<E> endpoint, Processor processor) { this(endpoint, processor, endpoint.getExecutorService()); } - public PollingConsumer(Endpoint<E> endpoint, Processor<E> processor, ScheduledExecutorService executor) { + public PollingConsumer(Endpoint<E> endpoint, Processor processor, ScheduledExecutorService executor) { super(endpoint, processor); this.executor = executor; if (executor == null) { diff --git a/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java index 4fa1d4f3d11c3..d46adf107ffd4 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java @@ -19,6 +19,7 @@ import org.apache.camel.Predicate; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.util.ServiceHelper; import org.apache.camel.impl.ServiceSupport; @@ -31,18 +32,18 @@ * * @version $Revision$ */ -public class ChoiceProcessor<E> extends ServiceSupport implements Processor<E> { - private List<FilterProcessor<E>> filters = new ArrayList<FilterProcessor<E>>(); - private Processor<E> otherwise; +public class ChoiceProcessor extends ServiceSupport implements Processor { + private List<FilterProcessor> filters = new ArrayList<FilterProcessor>(); + private Processor otherwise; - public ChoiceProcessor(List<FilterProcessor<E>> filters, Processor<E> otherwise) { + public ChoiceProcessor(List<FilterProcessor> filters, Processor otherwise) { this.filters = filters; this.otherwise = otherwise; } - public void process(E exchange) throws Exception { - for (FilterProcessor<E> filterProcessor : filters) { - Predicate<E> predicate = filterProcessor.getPredicate(); + public void process(Exchange exchange) throws Exception { + for (FilterProcessor filterProcessor : filters) { + Predicate<Exchange> predicate = filterProcessor.getPredicate(); if (predicate != null && predicate.matches(exchange)) { filterProcessor.getProcessor().process(exchange); return; @@ -57,7 +58,7 @@ public void process(E exchange) throws Exception { public String toString() { StringBuilder builder = new StringBuilder("choice{"); boolean first = true; - for (FilterProcessor<E> processor : filters) { + for (FilterProcessor processor : filters) { if (first) { first = false; } @@ -77,11 +78,11 @@ public String toString() { return builder.toString(); } - public List<FilterProcessor<E>> getFilters() { + public List<FilterProcessor> getFilters() { return filters; } - public Processor<E> getOtherwise() { + public Processor getOtherwise() { return otherwise; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/CompositeProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/CompositeProcessor.java index 685c4f8c86f2f..862ac703cc487 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/CompositeProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/CompositeProcessor.java @@ -18,6 +18,7 @@ package org.apache.camel.processor; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.util.ServiceHelper; @@ -28,15 +29,15 @@ * * @version $Revision$ */ -public class CompositeProcessor<E> extends ServiceSupport implements Processor<E> { - private final Collection<Processor<E>> processors; +public class CompositeProcessor extends ServiceSupport implements Processor { + private final Collection<Processor> processors; - public CompositeProcessor(Collection<Processor<E>> processors) { + public CompositeProcessor(Collection<Processor> processors) { this.processors = processors; } - public void process(E exchange) throws Exception { - for (Processor<E> processor : processors) { + public void process(Exchange exchange) throws Exception { + for (Processor processor : processors) { processor.process(exchange); } } @@ -45,7 +46,7 @@ public void process(E exchange) throws Exception { public String toString() { StringBuilder builder = new StringBuilder("[ "); boolean first = true; - for (Processor<E> processor : processors) { + for (Processor processor : processors) { if (first) { first = false; } @@ -58,7 +59,7 @@ public String toString() { return builder.toString(); } - public Collection<Processor<E>> getProcessors() { + public Collection<Processor> getProcessors() { return processors; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/DeadLetterChannel.java b/camel-core/src/main/java/org/apache/camel/processor/DeadLetterChannel.java index a80cebb3f72fc..f9768e6d215df 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/DeadLetterChannel.java +++ b/camel-core/src/main/java/org/apache/camel/processor/DeadLetterChannel.java @@ -32,25 +32,25 @@ * * @version $Revision$ */ -public class DeadLetterChannel<E extends Exchange> extends ServiceSupport implements ErrorHandler<E> { +public class DeadLetterChannel extends ServiceSupport implements ErrorHandler { public static final String REDELIVERY_COUNTER = "org.apache.camel.RedeliveryCounter"; public static final String REDELIVERED = "org.apache.camel.Redelivered"; private static final transient Log log = LogFactory.getLog(DeadLetterChannel.class); - private Processor<E> output; - private Processor<E> deadLetter; + private Processor output; + private Processor deadLetter; private RedeliveryPolicy redeliveryPolicy; - private Logger<E> logger; + private Logger logger; - public static <E extends Exchange> Logger<E> createDefaultLogger() { - return new Logger<E>(log, LoggingLevel.ERROR); + public static <E extends Exchange> Logger createDefaultLogger() { + return new Logger(log, LoggingLevel.ERROR); } - public DeadLetterChannel(Processor<E> output, Processor<E> deadLetter) { - this(output, deadLetter, new RedeliveryPolicy(), DeadLetterChannel.<E>createDefaultLogger()); + public DeadLetterChannel(Processor output, Processor deadLetter) { + this(output, deadLetter, new RedeliveryPolicy(), DeadLetterChannel.createDefaultLogger()); } - public DeadLetterChannel(Processor<E> output, Processor<E> deadLetter, RedeliveryPolicy redeliveryPolicy, Logger<E> logger) { + public DeadLetterChannel(Processor output, Processor deadLetter, RedeliveryPolicy redeliveryPolicy, Logger logger) { this.deadLetter = deadLetter; this.output = output; this.redeliveryPolicy = redeliveryPolicy; @@ -62,7 +62,7 @@ public String toString() { return "DeadLetterChannel[" + output + ", " + deadLetter + ", " + redeliveryPolicy + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { int redeliveryCounter = 0; long redeliveryDelay = 0; @@ -94,14 +94,14 @@ public void process(E exchange) throws Exception { /** * Returns the output processor */ - public Processor<E> getOutput() { + public Processor getOutput() { return output; } /** * Returns the dead letter that message exchanges will be sent to if the redelivery attempts fail */ - public Processor<E> getDeadLetter() { + public Processor getDeadLetter() { return deadLetter; } @@ -116,14 +116,14 @@ public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) { this.redeliveryPolicy = redeliveryPolicy; } - public Logger<E> getLogger() { + public Logger getLogger() { return logger; } /** * Sets the logger strategy; which {@link Log} to use and which {@link LoggingLevel} to use */ - public void setLogger(Logger<E> logger) { + public void setLogger(Logger logger) { this.logger = logger; } @@ -133,7 +133,7 @@ public void setLogger(Logger<E> logger) { /** * Increments the redelivery counter and adds the redelivered flag if the message has been redelivered */ - protected int incrementRedeliveryCounter(E exchange) { + protected int incrementRedeliveryCounter(Exchange exchange) { Message in = exchange.getIn(); Integer counter = in.getHeader(REDELIVERY_COUNTER, Integer.class); int next = 1; diff --git a/camel-core/src/main/java/org/apache/camel/processor/DelegateProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/DelegateProcessor.java index 3289e5ad7f9c4..fc764ff2b1937 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/DelegateProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/DelegateProcessor.java @@ -18,6 +18,7 @@ package org.apache.camel.processor; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.spi.Policy; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.util.ServiceHelper; @@ -28,21 +29,21 @@ * * @version $Revision: 519941 $ */ -public class DelegateProcessor<E> extends ServiceSupport implements Processor<E> { - protected Processor<E> next; +public class DelegateProcessor extends ServiceSupport implements Processor { + protected Processor next; public DelegateProcessor() { } - public DelegateProcessor(Processor<E> next) { + public DelegateProcessor(Processor next) { this.next = next; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { processNext(exchange); } - protected void processNext(E exchange) throws Exception { + protected void processNext(Exchange exchange) throws Exception { if (next != null) { next.process(exchange); } @@ -53,11 +54,11 @@ public String toString() { return "delegate(" + next + ")"; } - public Processor<E> getNext() { + public Processor getNext() { return next; } - public void setNext(Processor<E> next) { + public void setNext(Processor next) { this.next = next; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/ErrorHandler.java b/camel-core/src/main/java/org/apache/camel/processor/ErrorHandler.java index c00b0e211e788..d9e568b634039 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/ErrorHandler.java +++ b/camel-core/src/main/java/org/apache/camel/processor/ErrorHandler.java @@ -25,5 +25,5 @@ * * @version $Revision$ */ -public interface ErrorHandler<E extends Exchange> extends Processor<E> { +public interface ErrorHandler extends Processor { } diff --git a/camel-core/src/main/java/org/apache/camel/processor/FilterProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/FilterProcessor.java index 10aa29b85eda2..7d13e0d9bb3a3 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/FilterProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/FilterProcessor.java @@ -19,22 +19,23 @@ import org.apache.camel.Predicate; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.impl.ServiceSupport; import org.apache.camel.util.ServiceHelper; /** * @version $Revision$ */ -public class FilterProcessor<E> extends ServiceSupport implements Processor<E> { - private Predicate<E> predicate; - private Processor<E> processor; +public class FilterProcessor extends ServiceSupport implements Processor { + private Predicate<Exchange> predicate; + private Processor processor; - public FilterProcessor(Predicate<E> predicate, Processor<E> processor) { + public FilterProcessor(Predicate<Exchange> predicate, Processor processor) { this.predicate = predicate; this.processor = processor; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { if (predicate.matches(exchange)) { processor.process(exchange); } @@ -45,11 +46,11 @@ public String toString() { return "if (" + predicate + ") " + processor; } - public Predicate<E> getPredicate() { + public Predicate<Exchange> getPredicate() { return predicate; } - public Processor<E> getProcessor() { + public Processor getProcessor() { return processor; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/Logger.java b/camel-core/src/main/java/org/apache/camel/processor/Logger.java index 16826954161e5..57a961b3e9ef7 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Logger.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Logger.java @@ -28,7 +28,7 @@ * * @version $Revision$ */ -public class Logger<E extends Exchange> implements Processor<E> { +public class Logger implements Processor { private Log log; private LoggingLevel level; @@ -50,7 +50,7 @@ public String toString() { return "Logger[" + log + "]"; } - public void process(E exchange) { + public void process(Exchange exchange) { switch (level) { case DEBUG: if (log.isDebugEnabled()) { @@ -161,7 +161,7 @@ public void log(String message, Throwable exception) { } } - protected Object logMessage(E exchange) { + protected Object logMessage(Exchange exchange) { return exchange; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/LoggingErrorHandler.java b/camel-core/src/main/java/org/apache/camel/processor/LoggingErrorHandler.java index 20af96816165b..80c1d223bc9b4 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/LoggingErrorHandler.java +++ b/camel-core/src/main/java/org/apache/camel/processor/LoggingErrorHandler.java @@ -29,16 +29,16 @@ * * @version $Revision$ */ -public class LoggingErrorHandler<E extends Exchange> extends ServiceSupport implements ErrorHandler<E> { - private Processor<E> output; +public class LoggingErrorHandler extends ServiceSupport implements ErrorHandler { + private Processor output; private Log log; private LoggingLevel level; - public LoggingErrorHandler(Processor<E> output) { + public LoggingErrorHandler(Processor output) { this(output, LogFactory.getLog(LoggingErrorHandler.class), LoggingLevel.INFO); } - public LoggingErrorHandler(Processor<E> output, Log log, LoggingLevel level) { + public LoggingErrorHandler(Processor output, Log log, LoggingLevel level) { this.output = output; this.log = log; this.level = level; @@ -49,7 +49,7 @@ public String toString() { return "LoggingErrorHandler[" + output + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { try { output.process(exchange); } @@ -64,7 +64,7 @@ public void process(E exchange) throws Exception { /** * Returns the output processor */ - public Processor<E> getOutput() { + public Processor getOutput() { return output; } @@ -86,7 +86,7 @@ public void setLog(Log log) { // Implementation methods //------------------------------------------------------------------------- - protected void logError(E exchange, RuntimeException e) { + protected void logError(Exchange exchange, RuntimeException e) { switch (level) { case DEBUG: if (log.isDebugEnabled()) { @@ -123,7 +123,7 @@ protected void logError(E exchange, RuntimeException e) { } } - protected Object logMessage(E exchange, RuntimeException e) { + protected Object logMessage(Exchange exchange, RuntimeException e) { return e + " while processing exchange: " + exchange; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index 7c4940321dc85..cb5f09c6ef98b 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -32,21 +32,21 @@ * * @version $Revision$ */ -public class MulticastProcessor<E extends Exchange> extends ServiceSupport implements Processor<E> { - private Collection<Producer<E>> producers; +public class MulticastProcessor extends ServiceSupport implements Processor { + private Collection<Producer> producers; /** * A helper method to convert a list of endpoints into a list of processors */ - public static <E extends Exchange> Collection<Producer<E>> toProducers(Collection<Endpoint<E>> endpoints) throws Exception { - Collection<Producer<E>> answer = new ArrayList<Producer<E>>(); - for (Endpoint<E> endpoint : endpoints) { + public static <E extends Exchange> Collection<Producer> toProducers(Collection<Endpoint> endpoints) throws Exception { + Collection<Producer> answer = new ArrayList<Producer>(); + for (Endpoint endpoint : endpoints) { answer.add(endpoint.createProducer()); } return answer; } - public MulticastProcessor(Collection<Endpoint<E>> endpoints) throws Exception { + public MulticastProcessor(Collection<Endpoint> endpoints) throws Exception { this.producers = toProducers(endpoints); } @@ -55,21 +55,21 @@ public String toString() { return "Multicast" + getEndpoints(); } - public void process(E exchange) throws Exception { - for (Producer<E> producer : producers) { - E copy = copyExchangeStrategy(producer, exchange); + public void process(Exchange exchange) throws Exception { + for (Producer producer : producers) { + Exchange copy = copyExchangeStrategy(producer, exchange); producer.process(copy); } } protected void doStop() throws Exception { - for (Producer<E> producer : producers) { + for (Producer producer : producers) { producer.stop(); } } protected void doStart() throws Exception { - for (Producer<E> producer : producers) { + for (Producer producer : producers) { producer.start(); } } @@ -77,16 +77,16 @@ protected void doStart() throws Exception { /** * Returns the producers to multicast to */ - public Collection<Producer<E>> getProducers() { + public Collection<Producer> getProducers() { return producers; } /** * Returns the list of endpoints */ - public Collection<Endpoint<E>> getEndpoints() { - Collection<Endpoint<E>> answer = new ArrayList<Endpoint<E>>(); - for (Producer<E> producer : producers) { + public Collection<Endpoint> getEndpoints() { + Collection<Endpoint> answer = new ArrayList<Endpoint>(); + for (Producer producer : producers) { answer.add(producer.getEndpoint()); } return answer; @@ -99,7 +99,7 @@ public Collection<Endpoint<E>> getEndpoints() { * @param producer the producer that will send the exchange * @param exchange @return the current exchange if no copying is required such as for a pipeline otherwise a new copy of the exchange is returned. */ - protected E copyExchangeStrategy(Producer<E> producer, E exchange) { + protected Exchange copyExchangeStrategy(Producer producer, Exchange exchange) { return producer.createExchange(exchange); } } diff --git a/camel-core/src/main/java/org/apache/camel/processor/Pipeline.java b/camel-core/src/main/java/org/apache/camel/processor/Pipeline.java index 5505504bf42be..9aed0cc93fe16 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Pipeline.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Pipeline.java @@ -30,15 +30,15 @@ * * @version $Revision$ */ -public class Pipeline<E extends Exchange> extends MulticastProcessor<E> implements Processor<E> { - public Pipeline(Collection<Endpoint<E>> endpoints) throws Exception { +public class Pipeline extends MulticastProcessor implements Processor { + public Pipeline(Collection<Endpoint> endpoints) throws Exception { super(endpoints); } - public void process(E exchange) throws Exception { - E nextExchange = exchange; + public void process(Exchange exchange) throws Exception { + Exchange nextExchange = exchange; boolean first = true; - for (Producer<E> producer : getProducers()) { + for (Producer producer : getProducers()) { if (first) { first = false; } @@ -56,8 +56,8 @@ public void process(E exchange) throws Exception { * @param previousExchange the previous exchange * @return a new exchange */ - protected E createNextExchange(Producer<E> producer, E previousExchange) { - E answer = producer.createExchange(previousExchange); + protected Exchange createNextExchange(Producer producer, Exchange previousExchange) { + Exchange answer = producer.createExchange(previousExchange); // now lets set the input of the next exchange to the output of the previous message if it is not null Object output = previousExchange.getOut().getBody(); @@ -74,8 +74,8 @@ protected E createNextExchange(Producer<E> producer, E previousExchange) { * @param exchange * @return the current exchange if no copying is required such as for a pipeline otherwise a new copy of the exchange is returned. */ - protected E copyExchangeStrategy(E exchange) { - return (E) exchange.copy(); + protected Exchange copyExchangeStrategy(Exchange exchange) { + return exchange.copy(); } @Override diff --git a/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java b/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java index 34cb10bdf2cbd..c3d609014bd5b 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java @@ -35,11 +35,11 @@ * * @version $Revision$ */ -public class RecipientList<E extends Exchange> extends ServiceSupport implements Processor<E> { - private final Expression<E> expression; - private ProducerCache<E> producerCache = new ProducerCache<E>(); +public class RecipientList extends ServiceSupport implements Processor { + private final Expression<Exchange> expression; + private ProducerCache<Exchange> producerCache = new ProducerCache<Exchange>(); - public RecipientList(Expression<E> expression) { + public RecipientList(Expression<Exchange> expression) { notNull(expression, "expression"); this.expression = expression; } @@ -49,17 +49,17 @@ public String toString() { return "RecipientList[" + expression + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { Object receipientList = expression.evaluate(exchange); Iterator iter = ObjectConverter.iterator(receipientList); while (iter.hasNext()) { Object recipient = iter.next(); - Endpoint<E> endpoint = resolveEndpoint(exchange, recipient); + Endpoint<Exchange> endpoint = resolveEndpoint(exchange, recipient); producerCache.getProducer(endpoint).process(exchange); } } - protected Endpoint<E> resolveEndpoint(E exchange, Object recipient) { + protected Endpoint<Exchange> resolveEndpoint(Exchange exchange, Object recipient) { return ExchangeHelper.resolveEndpoint(exchange, recipient); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java index 6ec3d4556ea9a..1cb1ca0dc628e 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java @@ -27,11 +27,11 @@ /** * @version $Revision$ */ -public class SendProcessor<E extends Exchange> extends ServiceSupport implements Processor<E>, Service { - private Endpoint<E> destination; - private Producer<E> producer; +public class SendProcessor extends ServiceSupport implements Processor, Service { + private Endpoint destination; + private Producer producer; - public SendProcessor(Endpoint<E> destination) { + public SendProcessor(Endpoint destination) { this.destination = destination; } @@ -50,14 +50,14 @@ protected void doStart() throws Exception { this.producer = destination.createProducer(); } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { if (producer == null) { throw new IllegalStateException("No producer, this processor has not been started!"); } producer.process(exchange); } - public Endpoint<E> getDestination() { + public Endpoint getDestination() { return destination; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java index a0e54632c50c4..4d33dc2125836 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java @@ -33,11 +33,11 @@ * * @version $Revision$ */ -public class Splitter<E extends Exchange> extends ServiceSupport implements Processor<E> { - private final Processor<E> processor; - private final Expression<E> expression; +public class Splitter extends ServiceSupport implements Processor { + private final Processor processor; + private final Expression expression; - public Splitter(Processor<E> destination, Expression<E> expression) { + public Splitter(Processor destination, Expression expression) { this.processor = destination; this.expression = expression; notNull(destination, "destination"); @@ -49,12 +49,12 @@ public String toString() { return "Splitter[on: " + expression + " to: " + processor + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { Object value = expression.evaluate(exchange); Iterator iter = ObjectConverter.iterator(value); while (iter.hasNext()) { Object part = iter.next(); - E newExchange = (E) exchange.copy(); + Exchange newExchange = exchange.copy(); newExchange.getIn().setBody(part); processor.process(newExchange); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java b/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java index 9188c05d74934..2ae777915cee2 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java @@ -32,13 +32,13 @@ * * @version $Revision: 1.1 $ */ -public class IdempotentConsumer<E extends Exchange> extends ServiceSupport implements Processor<E> { +public class IdempotentConsumer extends ServiceSupport implements Processor { private static final transient Log log = LogFactory.getLog(IdempotentConsumer.class); - private Expression<E> messageIdExpression; - private Processor<E> nextProcessor; + private Expression<Exchange> messageIdExpression; + private Processor nextProcessor; private MessageIdRepository messageIdRepository; - public IdempotentConsumer(Expression<E> messageIdExpression, MessageIdRepository messageIdRepository, Processor<E> nextProcessor) { + public IdempotentConsumer(Expression<Exchange> messageIdExpression, MessageIdRepository messageIdRepository, Processor nextProcessor) { this.messageIdExpression = messageIdExpression; this.messageIdRepository = messageIdRepository; this.nextProcessor = nextProcessor; @@ -49,7 +49,7 @@ public String toString() { return "IdempotentConsumer[expression=" + messageIdExpression + ", repository=" + messageIdRepository + ", processor=" + nextProcessor + "]"; } - public void process(E exchange) throws Exception { + public void process(Exchange exchange) throws Exception { String messageId = ExpressionHelper.evaluateAsString(messageIdExpression, exchange); if (messageId == null) { throw new NoMessageIdException(exchange, messageIdExpression); @@ -64,7 +64,7 @@ public void process(E exchange) throws Exception { // Properties //------------------------------------------------------------------------- - public Expression<E> getMessageIdExpression() { + public Expression<Exchange> getMessageIdExpression() { return messageIdExpression; } @@ -72,7 +72,7 @@ public MessageIdRepository getMessageIdRepository() { return messageIdRepository; } - public Processor<E> getNextProcessor() { + public Processor getNextProcessor() { return nextProcessor; } @@ -94,7 +94,7 @@ protected void doStop() throws Exception { * @param exchange the exchange * @param messageId the message ID of this exchange */ - protected void onDuplicateMessage(E exchange, String messageId) { + protected void onDuplicateMessage(Exchange exchange, String messageId) { if (log.isDebugEnabled()) { log.debug("Ignoring duplicate message with id: " + messageId + " for exchange: " + exchange); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancer.java index 3592ec41df417..4bd4d3f748393 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancer.java @@ -26,18 +26,18 @@ * * @version $Revision: 1.1 $ */ -public interface LoadBalancer<E extends Exchange> extends Processor<E> { +public interface LoadBalancer extends Processor { /** * Adds a new processor to the load balancer * * @param processor the processor to be added to the load balancer */ - void addProcessor(Processor<E> processor); + void addProcessor(Processor processor); /** * Removes the given processor from the load balancer * * @param processor the processor to be removed from the load balancer */ - void removeProcessor(Processor<E> processor); + void removeProcessor(Processor processor); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java index 2facdc99a82a3..525e60c00adf0 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java @@ -28,14 +28,14 @@ * * @version $Revision: 1.1 $ */ -public abstract class LoadBalancerSupport<E extends Exchange> implements LoadBalancer<E> { - private List<Processor<E>> processors = new CopyOnWriteArrayList<Processor<E>>(); +public abstract class LoadBalancerSupport implements LoadBalancer { + private List<Processor> processors = new CopyOnWriteArrayList<Processor>(); - public void addProcessor(Processor<E> processor) { + public void addProcessor(Processor processor) { processors.add(processor); } - public void removeProcessor(Processor<E> processor) { + public void removeProcessor(Processor processor) { processors.remove(processor); } @@ -44,7 +44,7 @@ public void removeProcessor(Processor<E> processor) { * * @return the processors available */ - public List<Processor<E>> getProcessors() { + public List<Processor> getProcessors() { return processors; } } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java index f6f81001ee3e9..4bef53263e700 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/QueueLoadBalancer.java @@ -28,14 +28,14 @@ * * @version $Revision: 1.1 $ */ -public abstract class QueueLoadBalancer<E extends Exchange> extends LoadBalancerSupport<E> { +public abstract class QueueLoadBalancer extends LoadBalancerSupport { - public void process(E exchange) throws Exception { - List<Processor<E>> list = getProcessors(); + public void process(Exchange exchange) throws Exception { + List<Processor> list = getProcessors(); if (list.isEmpty()) { throw new IllegalStateException("No processors available to process " + exchange); } - Processor<E> processor = chooseProcessor(list, exchange); + Processor processor = chooseProcessor(list, exchange); if (processor == null) { throw new IllegalStateException("No processors could be chosen to process " + exchange); } @@ -44,5 +44,5 @@ public void process(E exchange) throws Exception { } } - protected abstract Processor<E> chooseProcessor(List<Processor<E>> processors, E exchange); + protected abstract Processor chooseProcessor(List<Processor> processors, Exchange exchange); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RandomLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RandomLoadBalancer.java index 5e29cb1766e65..b79f23cd169f6 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RandomLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RandomLoadBalancer.java @@ -27,9 +27,9 @@ * * @version $Revision: 1.1 $ */ -public class RandomLoadBalancer<E extends Exchange> extends QueueLoadBalancer<E> { +public class RandomLoadBalancer extends QueueLoadBalancer { - protected synchronized Processor<E> chooseProcessor(List<Processor<E>> processors, E exchange) { + protected synchronized Processor chooseProcessor(List<Processor> processors, Exchange exchange) { int size = processors.size(); while (true) { int index = (int) Math.round(Math.random() * size); diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RoundRobinLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RoundRobinLoadBalancer.java index 3f5d0cc1d577f..edb6c85dce7f7 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RoundRobinLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/RoundRobinLoadBalancer.java @@ -27,10 +27,10 @@ * * @version $Revision: 1.1 $ */ -public class RoundRobinLoadBalancer<E extends Exchange> extends QueueLoadBalancer<E> { +public class RoundRobinLoadBalancer extends QueueLoadBalancer { private int counter = -1; - protected synchronized Processor<E> chooseProcessor(List<Processor<E>> processors, E exchange) { + protected synchronized Processor chooseProcessor(List<Processor> processors, Exchange exchange) { int size = processors.size(); if (++counter >= size) { counter = 0; diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/StickyLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/StickyLoadBalancer.java index 4861581b9d5d6..fe9b07f8f5f2b 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/StickyLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/StickyLoadBalancer.java @@ -34,26 +34,26 @@ * * @version $Revision: 1.1 $ */ -public class StickyLoadBalancer<E extends Exchange> extends QueueLoadBalancer<E> { - private Expression<E> correlationExpression; +public class StickyLoadBalancer extends QueueLoadBalancer { + private Expression<Exchange> correlationExpression; private QueueLoadBalancer loadBalancer; private int numberOfHashGroups = 64 * 1024; - private Map<Object, Processor<E>> stickyMap = new HashMap<Object, Processor<E>>(); + private Map<Object, Processor> stickyMap = new HashMap<Object, Processor>(); - public StickyLoadBalancer(Expression<E> correlationExpression) { + public StickyLoadBalancer(Expression<Exchange> correlationExpression) { this(correlationExpression, new RoundRobinLoadBalancer()); } - public StickyLoadBalancer(Expression<E> correlationExpression, QueueLoadBalancer loadBalancer) { + public StickyLoadBalancer(Expression<Exchange> correlationExpression, QueueLoadBalancer loadBalancer) { this.correlationExpression = correlationExpression; this.loadBalancer = loadBalancer; } - protected synchronized Processor<E> chooseProcessor(List<Processor<E>> processors, E exchange) { + protected synchronized Processor chooseProcessor(List<Processor> processors, Exchange exchange) { Object value = correlationExpression.evaluate(exchange); Object key = getStickyKey(value); - Processor<E> processor; + Processor processor; synchronized (stickyMap) { processor = stickyMap.get(key); if (processor == null) { @@ -65,11 +65,11 @@ protected synchronized Processor<E> chooseProcessor(List<Processor<E>> processor } @Override - public void removeProcessor(Processor<E> processor) { + public void removeProcessor(Processor processor) { synchronized (stickyMap) { - Iterator<Map.Entry<Object,Processor<E>>> iter = stickyMap.entrySet().iterator(); + Iterator<Map.Entry<Object,Processor>> iter = stickyMap.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry<Object, Processor<E>> entry = iter.next(); + Map.Entry<Object, Processor> entry = iter.next(); if (processor.equals(entry.getValue())) { iter.remove(); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/TopicLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/TopicLoadBalancer.java index c7243871044b7..af544b6fe33e1 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/TopicLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/TopicLoadBalancer.java @@ -28,11 +28,11 @@ * * @version $Revision: 1.1 $ */ -public class TopicLoadBalancer<E extends Exchange> extends LoadBalancerSupport<E> { - public void process(E exchange) throws Exception { - List<Processor<E>> list = getProcessors(); - for (Processor<E> processor : list) { - E copy = copyExchangeStrategy(processor, exchange); +public class TopicLoadBalancer extends LoadBalancerSupport { + public void process(Exchange exchange) throws Exception { + List<Processor> list = getProcessors(); + for (Processor processor : list) { + Exchange copy = copyExchangeStrategy(processor, exchange); processor.process(copy); } } @@ -44,7 +44,7 @@ public void process(E exchange) throws Exception { * @param processor the processor that will send the exchange * @param exchange @return the current exchange if no copying is required such as for a pipeline otherwise a new copy of the exchange is returned. */ - protected E copyExchangeStrategy(Processor<E> processor, E exchange) { - return (E) exchange.copy(); + protected Exchange copyExchangeStrategy(Processor processor, Exchange exchange) { + return exchange.copy(); } } diff --git a/camel-core/src/main/java/org/apache/camel/spi/Policy.java b/camel-core/src/main/java/org/apache/camel/spi/Policy.java index f9187da22b217..c240bece2fbf0 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/Policy.java +++ b/camel-core/src/main/java/org/apache/camel/spi/Policy.java @@ -33,5 +33,5 @@ public interface Policy<E> { * @param processor the processor to be intercepted * @return either the original processor or a processor wrapped in one or more interceptors */ - Processor<E> wrap(Processor<E> processor); + Processor wrap(Processor processor); } diff --git a/camel-core/src/main/java/org/apache/camel/util/ProducerCache.java b/camel-core/src/main/java/org/apache/camel/util/ProducerCache.java index 5df403ae2847c..eb6bcfbfebf51 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ProducerCache.java +++ b/camel-core/src/main/java/org/apache/camel/util/ProducerCache.java @@ -72,7 +72,7 @@ public void send(Endpoint<E> endpoint, E exchange) { * @param endpoint the endpoint to send the exchange to * @param processor the transformer used to populate the new exchange */ - public E send(Endpoint<E> endpoint, Processor<E> processor) { + public E send(Endpoint<E> endpoint, Processor processor) { try { Producer<E> producer = getProducer(endpoint); E exchange = producer.createExchange(); diff --git a/camel-core/src/test/java/org/apache/camel/ContextTestSupport.java b/camel-core/src/test/java/org/apache/camel/ContextTestSupport.java index 540d9dfa65336..5746cb8ecb753 100644 --- a/camel-core/src/test/java/org/apache/camel/ContextTestSupport.java +++ b/camel-core/src/test/java/org/apache/camel/ContextTestSupport.java @@ -70,7 +70,7 @@ protected Endpoint resolveMandatoryEndpoint(String uri) { * @param body the body for the message */ protected void send(String endpointUri, final Object body) { - client.send(endpointUri, new Processor<Exchange>() { + client.send(endpointUri, new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody(body); diff --git a/camel-core/src/test/java/org/apache/camel/builder/ErrorHandlerTest.java b/camel-core/src/test/java/org/apache/camel/builder/ErrorHandlerTest.java index 76fb3848cd6bd..0bcb3844d3a7e 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/ErrorHandlerTest.java +++ b/camel-core/src/test/java/org/apache/camel/builder/ErrorHandlerTest.java @@ -45,10 +45,10 @@ public void configure() { }; // END SNIPPET: e1 - Map<Endpoint<Exchange>, Processor<Exchange>> routeMap = builder.getRouteMap(); - Set<Map.Entry<Endpoint<Exchange>, Processor<Exchange>>> routes = routeMap.entrySet(); + Map<Endpoint<Exchange>, Processor> routeMap = builder.getRouteMap(); + Set<Map.Entry<Endpoint<Exchange>, Processor>> routes = routeMap.entrySet(); assertEquals("Number routes created", 1, routes.size()); - for (Map.Entry<Endpoint<Exchange>, Processor<Exchange>> route : routes) { + for (Map.Entry<Endpoint<Exchange>, Processor> route : routes) { Endpoint<Exchange> key = route.getKey(); assertEquals("From endpoint", "queue:a", key.getEndpointUri()); Processor processor = route.getValue(); @@ -70,12 +70,12 @@ public void configure() { }; // END SNIPPET: e2 - Map<Endpoint<Exchange>, Processor<Exchange>> routeMap = builder.getRouteMap(); + Map<Endpoint<Exchange>, Processor> routeMap = builder.getRouteMap(); log.info(routeMap); - Set<Map.Entry<Endpoint<Exchange>, Processor<Exchange>>> routes = routeMap.entrySet(); + Set<Map.Entry<Endpoint<Exchange>, Processor>> routes = routeMap.entrySet(); assertEquals("Number routes created", 2, routes.size()); - for (Map.Entry<Endpoint<Exchange>, Processor<Exchange>> route : routes) { + for (Map.Entry<Endpoint<Exchange>, Processor> route : routes) { Endpoint<Exchange> key = route.getKey(); String endpointUri = key.getEndpointUri(); Processor processor = route.getValue(); @@ -108,10 +108,10 @@ public void configure() { }; // END SNIPPET: e3 - Map<Endpoint<Exchange>, Processor<Exchange>> routeMap = builder.getRouteMap(); - Set<Map.Entry<Endpoint<Exchange>, Processor<Exchange>>> routes = routeMap.entrySet(); + Map<Endpoint<Exchange>, Processor> routeMap = builder.getRouteMap(); + Set<Map.Entry<Endpoint<Exchange>, Processor>> routes = routeMap.entrySet(); assertEquals("Number routes created", 1, routes.size()); - for (Map.Entry<Endpoint<Exchange>, Processor<Exchange>> route : routes) { + for (Map.Entry<Endpoint<Exchange>, Processor> route : routes) { Endpoint<Exchange> key = route.getKey(); assertEquals("From endpoint", "queue:a", key.getEndpointUri()); Processor processor = route.getValue(); @@ -134,10 +134,10 @@ public void configure() { }; // END SNIPPET: e4 - Map<Endpoint<Exchange>, Processor<Exchange>> routeMap = builder.getRouteMap(); - Set<Map.Entry<Endpoint<Exchange>, Processor<Exchange>>> routes = routeMap.entrySet(); + Map<Endpoint<Exchange>, Processor> routeMap = builder.getRouteMap(); + Set<Map.Entry<Endpoint<Exchange>, Processor>> routes = routeMap.entrySet(); assertEquals("Number routes created", 1, routes.size()); - for (Map.Entry<Endpoint<Exchange>, Processor<Exchange>> route : routes) { + for (Map.Entry<Endpoint<Exchange>, Processor> route : routes) { Endpoint<Exchange> key = route.getKey(); assertEquals("From endpoint", "queue:a", key.getEndpointUri()); Processor processor = route.getValue(); diff --git a/camel-core/src/test/java/org/apache/camel/builder/InterceptorBuilderTest.java b/camel-core/src/test/java/org/apache/camel/builder/InterceptorBuilderTest.java index ab2e9e23281d2..a04bb23e47792 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/InterceptorBuilderTest.java +++ b/camel-core/src/test/java/org/apache/camel/builder/InterceptorBuilderTest.java @@ -41,7 +41,7 @@ public void testRouteWithInterceptor() throws Exception { CamelContext container = new DefaultCamelContext(); final ArrayList<String> order = new ArrayList<String>(); - final DelegateProcessor<Exchange> interceptor1 = new DelegateProcessor<Exchange>() { + final DelegateProcessor interceptor1 = new DelegateProcessor() { @Override public void process(Exchange exchange) throws Exception { order.add("START:1"); @@ -49,7 +49,7 @@ public void process(Exchange exchange) throws Exception { order.add("END:1"); } }; - final DelegateProcessor<Exchange> interceptor2 = new DelegateProcessor<Exchange>() { + final DelegateProcessor interceptor2 = new DelegateProcessor() { @Override public void process(Exchange exchange) throws Exception { order.add("START:2"); diff --git a/camel-core/src/test/java/org/apache/camel/builder/MyInterceptorProcessor.java b/camel-core/src/test/java/org/apache/camel/builder/MyInterceptorProcessor.java index 549bcfb6ac530..59b28da1e9594 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/MyInterceptorProcessor.java +++ b/camel-core/src/test/java/org/apache/camel/builder/MyInterceptorProcessor.java @@ -6,7 +6,7 @@ import org.apache.camel.Exchange; import org.apache.camel.processor.DelegateProcessor; -public class MyInterceptorProcessor extends DelegateProcessor<Exchange> { +public class MyInterceptorProcessor extends DelegateProcessor { public void process(Exchange exchange) throws Exception { System.out.println("START of onExchange: "+exchange); next.process(exchange); diff --git a/camel-core/src/test/java/org/apache/camel/builder/MyProcessor.java b/camel-core/src/test/java/org/apache/camel/builder/MyProcessor.java index d2c74b5931c09..c74a1fd7e59ec 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/MyProcessor.java +++ b/camel-core/src/test/java/org/apache/camel/builder/MyProcessor.java @@ -19,7 +19,7 @@ import org.apache.camel.Exchange; import org.apache.camel.Processor; -public class MyProcessor implements Processor<Exchange> { +public class MyProcessor implements Processor { public void process(Exchange exchange) { System.out.println("Called with exchange: " + exchange); } diff --git a/camel-core/src/test/java/org/apache/camel/builder/RouteBuilderTest.java b/camel-core/src/test/java/org/apache/camel/builder/RouteBuilderTest.java index cdbd9771776ff..3a2880025cf4f 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/RouteBuilderTest.java +++ b/camel-core/src/test/java/org/apache/camel/builder/RouteBuilderTest.java @@ -41,9 +41,9 @@ * @version $Revision$ */ public class RouteBuilderTest extends TestSupport { - protected Processor<Exchange> myProcessor = new MyProcessor(); - protected DelegateProcessor<Exchange> interceptor1; - protected DelegateProcessor<Exchange> interceptor2; + protected Processor myProcessor = new MyProcessor(); + protected DelegateProcessor interceptor1; + protected DelegateProcessor interceptor2; protected RouteBuilder buildSimpleRoute() { // START SNIPPET: e1 @@ -142,7 +142,7 @@ public void testSimpleRouteWithChoice() throws Exception { protected RouteBuilder buildCustomProcessor() { // START SNIPPET: e4 - myProcessor = new Processor<Exchange>() { + myProcessor = new Processor() { public void process(Exchange exchange) { System.out.println("Called with exchange: " + exchange); } diff --git a/camel-core/src/test/java/org/apache/camel/component/direct/DirectRouteTest.java b/camel-core/src/test/java/org/apache/camel/component/direct/DirectRouteTest.java index fb6db3f71d052..34cbc7fa91665 100644 --- a/camel-core/src/test/java/org/apache/camel/component/direct/DirectRouteTest.java +++ b/camel-core/src/test/java/org/apache/camel/component/direct/DirectRouteTest.java @@ -44,7 +44,7 @@ public void testSedaQueue() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from("direct:test.a").to("direct:test.b"); - from("direct:test.b").process(new Processor<Exchange>() { + from("direct:test.b").process(new Processor() { public void process(Exchange e) { invoked.set(true); } diff --git a/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java b/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java index fdb5124bd0b9d..7346cf11000c6 100644 --- a/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java +++ b/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java @@ -25,6 +25,7 @@ import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Producer; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; import org.apache.commons.logging.Log; @@ -37,7 +38,7 @@ public class FileRouteTest extends TestCase { private static final transient Log log = LogFactory.getLog(FileRouteTest.class); protected CamelContext container = new DefaultCamelContext(); protected CountDownLatch latch = new CountDownLatch(1); - protected FileExchange receivedExchange; + protected Exchange receivedExchange; protected String uri = "file://foo.txt"; protected Producer<FileExchange> producer; @@ -77,8 +78,8 @@ protected void tearDown() throws Exception { protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { - from(uri).process(new Processor<FileExchange>() { - public void process(FileExchange e) { + from(uri).process(new Processor() { + public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); receivedExchange = e; latch.countDown(); diff --git a/camel-core/src/test/java/org/apache/camel/component/queue/QueueRouteTest.java b/camel-core/src/test/java/org/apache/camel/component/queue/QueueRouteTest.java index 7968fc69ef12c..1b1724ebdfdd0 100644 --- a/camel-core/src/test/java/org/apache/camel/component/queue/QueueRouteTest.java +++ b/camel-core/src/test/java/org/apache/camel/component/queue/QueueRouteTest.java @@ -45,7 +45,7 @@ public void testSedaQueue() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from("queue:test.a").to("queue:test.b"); - from("queue:test.b").process(new Processor<Exchange>() { + from("queue:test.b").process(new Processor() { public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); latch.countDown(); @@ -82,7 +82,7 @@ public void xtestThatShowsEndpointResolutionIsNotConsistent() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from("queue:test.a").to("queue:test.b"); - from("queue:test.b").process(new Processor<Exchange>() { + from("queue:test.b").process(new Processor() { public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); latch.countDown(); diff --git a/camel-core/src/test/java/org/apache/camel/impl/MyExchange.java b/camel-core/src/test/java/org/apache/camel/impl/MyExchange.java new file mode 100644 index 0000000000000..ac63167a0f8f4 --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/impl/MyExchange.java @@ -0,0 +1,30 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.impl; + +import org.apache.camel.CamelContext; + +/** + * @version $Revision: 1.1 $ + */ +public class MyExchange extends DefaultExchange { + + public MyExchange(CamelContext context) { + super(context); + } +} diff --git a/camel-core/src/test/java/org/apache/camel/impl/ProducerTest.java b/camel-core/src/test/java/org/apache/camel/impl/ProducerTest.java new file mode 100644 index 0000000000000..f3a985b198e7b --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/impl/ProducerTest.java @@ -0,0 +1,64 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.impl; + +import junit.framework.TestCase; +import org.apache.camel.TestSupport; +import org.apache.camel.Endpoint; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.Exchange; +import org.apache.camel.CamelContext; + +/** + * @version $Revision: 1.1 $ + */ +public class ProducerTest extends TestSupport { + private CamelContext context = new DefaultCamelContext(); + + public void testUsingADerivedExchange() throws Exception { + Endpoint<MyExchange> endpoint = new DefaultEndpoint<MyExchange>("foo", new DefaultComponent()) { + public Consumer<MyExchange> createConsumer(Processor processor) throws Exception { + return null; + } + + public MyExchange createExchange() { + return new MyExchange(getContext()); + } + + public Producer<MyExchange> createProducer() throws Exception { + return null; + } + + public boolean isSingleton() { + return false; + } + }; + + DefaultProducer producer = new DefaultProducer(endpoint) { + public void process(Exchange exchange) throws Exception { + log.info("Received: " + exchange); + } + }; + + // now lets try send in a normal exchange + Exchange exchange = new DefaultExchange(context); + producer.process(exchange); + } +} diff --git a/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java b/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java index 0c968bc6565a6..2fcdbed134c1c 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/ChoiceTest.java @@ -62,7 +62,7 @@ public void testSendToOtherwiseClause() throws Exception { } protected void sendMessage(final Object headerValue, final Object body) throws Exception { - client.send(startEndpoint, new Processor<Exchange>() { + client.send(startEndpoint, new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelTest.java b/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelTest.java index 9d99075e845fd..a7b22da775856 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelTest.java @@ -70,7 +70,7 @@ protected void setUp() throws Exception { } protected RouteBuilder createRouteBuilder() { - final Processor<Exchange> processor = new Processor<Exchange>() { + final Processor processor = new Processor() { public void process(Exchange exchange) { Integer counter = exchange.getIn().getHeader(DeadLetterChannel.REDELIVERY_COUNTER, Integer.class); int attempt = (counter == null) ? 1 : counter + 1; diff --git a/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java b/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java index e985b7986f5fb..94d8b480f8547 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/FilterTest.java @@ -65,7 +65,7 @@ public void configure() { } protected void sendMessage(final Object headerValue, final Object body) throws Exception { - client.send(startEndpoint, new Processor<Exchange>() { + client.send(startEndpoint, new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerTest.java b/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerTest.java index 3bdc047264b94..bef4b88aa1340 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerTest.java @@ -48,7 +48,7 @@ public void testDuplicateMessagesAreFilteredOut() throws Exception { } protected void sendMessage(final Object messageId, final Object body) { - client.send(startEndpoint, new Processor<Exchange>() { + client.send(startEndpoint, new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/JoinRoutesTest.java b/camel-core/src/test/java/org/apache/camel/processor/JoinRoutesTest.java index 3136c11396d2f..063a3975ace83 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/JoinRoutesTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/JoinRoutesTest.java @@ -42,7 +42,7 @@ public void testMessagesThroughDifferentRoutes() throws Exception { } protected void sendMessage(final Object headerValue, final Object body) throws Exception { - client.send(startEndpoint, new Processor<Exchange>() { + client.send(startEndpoint, new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/MulticastTest.java b/camel-core/src/test/java/org/apache/camel/processor/MulticastTest.java index 6d3eb941781ee..52867cfdfd1a2 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/MulticastTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/MulticastTest.java @@ -38,7 +38,7 @@ public void testSendingAMessageUsingMulticastReceivesItsOwnExchange() throws Exc y.expectedBodiesReceived("input+output"); z.expectedBodiesReceived("input+output"); - client.send("direct:a", new Processor<Exchange>() { + client.send("direct:a", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody("input"); @@ -59,7 +59,7 @@ protected void setUp() throws Exception { } protected RouteBuilder createRouteBuilder() { - final Processor<Exchange> processor = new Processor<Exchange>() { + final Processor processor = new Processor() { public void process(Exchange exchange) { // lets transform the IN message Message in = exchange.getIn(); diff --git a/camel-core/src/test/java/org/apache/camel/processor/PipelineTest.java b/camel-core/src/test/java/org/apache/camel/processor/PipelineTest.java index 21d78657f3a9d..81069f259d22c 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/PipelineTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/PipelineTest.java @@ -33,7 +33,7 @@ public class PipelineTest extends ContextTestSupport { public void testSendMessageThroughAPipeline() throws Exception { resultEndpoint.expectedBodiesReceived(4); - client.send("direct:a", new Processor<Exchange>() { + client.send("direct:a", new Processor() { public void process(Exchange exchange) { // now lets fire in a message Message in = exchange.getIn(); @@ -53,7 +53,7 @@ protected void setUp() throws Exception { } protected RouteBuilder createRouteBuilder() { - final Processor<Exchange> processor = new Processor<Exchange>() { + final Processor processor = new Processor() { public void process(Exchange exchange) { Integer number = exchange.getIn().getBody(Integer.class); if (number == null) { diff --git a/camel-core/src/test/java/org/apache/camel/processor/RecipientListTest.java b/camel-core/src/test/java/org/apache/camel/processor/RecipientListTest.java index 029cd72539f69..0f6d31744261f 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/RecipientListTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/RecipientListTest.java @@ -35,7 +35,7 @@ public void testSendingAMessageUsingMulticastReceivesItsOwnExchange() throws Exc y.expectedBodiesReceived("answer"); z.expectedBodiesReceived("answer"); - client.send("direct:a", new Processor<Exchange>() { + client.send("direct:a", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody("answer"); diff --git a/camel-core/src/test/java/org/apache/camel/processor/SplitterTest.java b/camel-core/src/test/java/org/apache/camel/processor/SplitterTest.java index 15c8668ec8246..5b4f45a821485 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/SplitterTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/SplitterTest.java @@ -35,7 +35,7 @@ public class SplitterTest extends ContextTestSupport { public void testSendingAMessageUsingMulticastReceivesItsOwnExchange() throws Exception { resultEndpoint.expectedBodiesReceived("James", "Guillaume", "Hiram", "Rob"); - client.send("direct:a", new Processor<Exchange>() { + client.send("direct:a", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody("James,Guillaume,Hiram,Rob"); diff --git a/camel-core/src/test/java/org/apache/camel/processor/TransformTest.java b/camel-core/src/test/java/org/apache/camel/processor/TransformTest.java index 7e9be48c859a0..1db0f4ce4cdf9 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/TransformTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/TransformTest.java @@ -49,7 +49,7 @@ protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: example - from("direct:start").process(new Processor<Exchange>() { + from("direct:start").process(new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody(in.getBody(String.class) + " World!"); diff --git a/camel-cxf/pom.xml b/camel-cxf/pom.xml index f5fabc11b366f..2deaa7d2f57ea 100644 --- a/camel-cxf/pom.xml +++ b/camel-cxf/pom.xml @@ -167,6 +167,7 @@ </includes> <excludes> <!-- TODO re-enable ASAP! --> + <exclude>**/CxfInvokeTest.*</exclude> <exclude>**/CxfTest.*</exclude> <exclude>**/transport/*Test.*</exclude> </excludes> diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfConsumer.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfConsumer.java index de882ddf06ce6..11e3640011009 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfConsumer.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfConsumer.java @@ -34,7 +34,7 @@ public class CxfConsumer extends DefaultConsumer<CxfExchange> { private final LocalTransportFactory transportFactory; private Destination destination; - public CxfConsumer(CxfEndpoint endpoint, Processor<CxfExchange> processor, LocalTransportFactory transportFactory) { + public CxfConsumer(CxfEndpoint endpoint, Processor processor, LocalTransportFactory transportFactory) { super(endpoint, processor); this.endpoint = endpoint; this.transportFactory = transportFactory; diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java index 533a4ee306196..663fc9e06583e 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java @@ -47,7 +47,7 @@ public Producer<CxfExchange> createProducer() throws Exception { return startService(new CxfProducer(this, getLocalTransportFactory())); } - public Consumer<CxfExchange> createConsumer(Processor<CxfExchange> processor) throws Exception { + public Consumer<CxfExchange> createConsumer(Processor processor) throws Exception { return startService(new CxfConsumer(this, processor, getLocalTransportFactory())); } diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeConsumer.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeConsumer.java index ffbd2609442e1..aeea514ca4049 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeConsumer.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeConsumer.java @@ -32,7 +32,7 @@ public class CxfInvokeConsumer extends DefaultConsumer<CxfExchange> { protected CxfInvokeEndpoint cxfEndpoint; private ServerImpl server; - public CxfInvokeConsumer(CxfInvokeEndpoint endpoint, Processor<CxfExchange> processor) { + public CxfInvokeConsumer(CxfInvokeEndpoint endpoint, Processor processor) { super(endpoint, processor); this.cxfEndpoint = endpoint; } diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeEndpoint.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeEndpoint.java index d06e91ff78af2..d767a05e78bd3 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeEndpoint.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeEndpoint.java @@ -47,7 +47,7 @@ public Producer<CxfExchange> createProducer() throws Exception { return startService(new CxfInvokeProducer(this)); } - public Consumer<CxfExchange> createConsumer(Processor<CxfExchange> processor) throws Exception { + public Consumer<CxfExchange> createConsumer(Processor processor) throws Exception { return startService(new CxfInvokeConsumer(this, processor)); } diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeProducer.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeProducer.java index cfd73dbcf038b..7dfb4e80aa1b8 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeProducer.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfInvokeProducer.java @@ -18,6 +18,7 @@ package org.apache.camel.component.cxf; import org.apache.camel.RuntimeCamelException; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultProducer; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientFactoryBean; @@ -29,26 +30,31 @@ * * @version $Revision$ */ -public class CxfInvokeProducer extends DefaultProducer<CxfExchange> { - private CxfInvokeEndpoint cxfEndpoint; +public class CxfInvokeProducer extends DefaultProducer { + private CxfInvokeEndpoint endpoint; private Client client; public CxfInvokeProducer(CxfInvokeEndpoint endpoint) { super(endpoint); - cxfEndpoint = endpoint; + this.endpoint = endpoint; + } + + public void process(Exchange exchange) { + CxfExchange cxfExchange = endpoint.toExchangeType(exchange); + process(cxfExchange); } public void process(CxfExchange exchange) { List params = exchange.getIn().getBody(List.class); Object[] response = null; try { - response = client.invoke(cxfEndpoint.getProperty(CxfConstants.METHOD), params.toArray()); + response = client.invoke(endpoint.getProperty(CxfConstants.METHOD), params.toArray()); } catch (Exception e) { throw new RuntimeCamelException(e); } - CxfBinding binding = cxfEndpoint.getBinding(); + CxfBinding binding = endpoint.getBinding(); binding.storeCxfResponse(exchange, response); } @@ -61,8 +67,8 @@ protected void doStart() throws Exception { if (client == null) { ClientFactoryBean cfBean = new ClientFactoryBean(); cfBean.setAddress(getEndpoint().getEndpointUri()); - cfBean.setBus(cxfEndpoint.getBus()); - cfBean.setServiceClass(Class.forName(cxfEndpoint.getProperty(CxfConstants.SEI))); + cfBean.setBus(endpoint.getBus()); + cfBean.setServiceClass(Class.forName(endpoint.getProperty(CxfConstants.SEI))); client = cfBean.create(); } } diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfProducer.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfProducer.java index 89a1378681e36..5dd4beb8edf26 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfProducer.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfProducer.java @@ -18,6 +18,7 @@ package org.apache.camel.component.cxf; import org.apache.camel.RuntimeCamelException; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultProducer; import org.apache.cxf.message.ExchangeImpl; import org.apache.cxf.message.Message; @@ -37,7 +38,7 @@ * * @version $Revision$ */ -public class CxfProducer extends DefaultProducer<CxfExchange> { +public class CxfProducer extends DefaultProducer { private CxfEndpoint endpoint; private final LocalTransportFactory transportFactory; private Destination destination; @@ -50,6 +51,11 @@ public CxfProducer(CxfEndpoint endpoint, LocalTransportFactory transportFactory) this.transportFactory = transportFactory; } + public void process(Exchange exchange) { + CxfExchange cxfExchange = endpoint.toExchangeType(exchange); + process(cxfExchange); + } + public void process(CxfExchange exchange) { try { CxfBinding binding = endpoint.getBinding(); diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java index c244716c30bed..03c3f677fd486 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java @@ -142,7 +142,7 @@ protected void onWrite() throws IOException { } private void commitOutputMessage() { - base.client.send(targetCamelEndpointUri, new Processor<org.apache.camel.Exchange>() { + base.client.send(targetCamelEndpointUri, new Processor() { public void process(org.apache.camel.Exchange reply) { Object request = null; diff --git a/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java b/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java index 90a9a7581dc32..ee6d3e4f60634 100644 --- a/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java +++ b/camel-cxf/src/main/java/org/apache/camel/component/cxf/transport/CamelDestination.java @@ -135,7 +135,7 @@ private void initConfig() { */ } - protected class ConsumerProcessor implements Processor<Exchange> { + protected class ConsumerProcessor implements Processor { public void process(Exchange exchange) { try { incoming(exchange); @@ -201,7 +201,7 @@ private void commitOutputMessage() throws IOException { //setup the reply message final String replyToUri = getReplyToDestination(inMessage); - base.client.send(replyToUri, new Processor<Exchange>() { + base.client.send(replyToUri, new Processor() { public void process(Exchange reply) { base.marshal(currentStream.toString(), replyToUri, reply); diff --git a/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfInvokeTest.java b/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfInvokeTest.java index 79b5536813cba..fc020c4a73f22 100644 --- a/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfInvokeTest.java +++ b/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfInvokeTest.java @@ -23,6 +23,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.Processor; import org.apache.camel.CamelClient; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultCamelContext; import org.apache.cxf.endpoint.ServerImpl; import org.apache.cxf.frontend.ServerFactoryBean; @@ -68,8 +69,8 @@ public void testInvokeOfServer() throws Exception { CxfExchange exchange = client.send(getUri(), - new Processor<CxfExchange>() { - public void process(final CxfExchange exchange) { + new Processor() { + public void process(final Exchange exchange) { final List<String> params = new ArrayList<String>(); params.add(testMessage); exchange.getIn().setBody(params); diff --git a/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTest.java b/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTest.java index f6516053d9e60..78f83c6d0190a 100644 --- a/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTest.java +++ b/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfTest.java @@ -85,8 +85,8 @@ public void testInvokeOfServer() throws Exception { CxfExchange exchange = (CxfExchange) client.send(getUri(), - new Processor<CxfExchange>() { - public void process(final CxfExchange exchange) { + new Processor() { + public void process(final Exchange exchange) { final List<String> params = new ArrayList<String>(); params.add(testMessage); exchange.getIn().setBody(params); diff --git a/camel-http/src/main/java/org/apache/camel/component/http/HttpEndpoint.java b/camel-http/src/main/java/org/apache/camel/component/http/HttpEndpoint.java index a2373e1309c87..da74634a71e33 100644 --- a/camel-http/src/main/java/org/apache/camel/component/http/HttpEndpoint.java +++ b/camel-http/src/main/java/org/apache/camel/component/http/HttpEndpoint.java @@ -23,6 +23,7 @@ import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.Consumer; +import org.apache.camel.Exchange; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -41,14 +42,14 @@ protected HttpEndpoint(String uri, HttpComponent component) { } public Producer<HttpExchange> createProducer() throws Exception { - return startService(new DefaultProducer<HttpExchange>(this) { - public void process(HttpExchange exchange) { + return startService(new DefaultProducer(this) { + public void process(Exchange exchange) { /** TODO */ } }); } - public Consumer<HttpExchange> createConsumer(Processor<HttpExchange> processor) throws Exception { + public Consumer<HttpExchange> createConsumer(Processor processor) throws Exception { // TODO return startService(new DefaultConsumer<HttpExchange>(this, processor) {}); } diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiComponent.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiComponent.java index 4234f6bcd0928..e341ad9ac0502 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiComponent.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiComponent.java @@ -101,7 +101,7 @@ public CamelJbiEndpoint createEndpoint(ServiceEndpoint ep) throws URISyntaxExcep Map map = URISupport.parseQuery(uri.getQuery()); String camelUri = uri.getSchemeSpecificPart(); Endpoint camelEndpoint = getCamelContext().getEndpoint(camelUri); - Processor<Exchange> processor = null; + Processor processor = null; try { processor = camelEndpoint.createProducer(); } @@ -147,7 +147,7 @@ public ScheduledExecutorService getExecutorService() { /** * Returns a JBI endpoint created for the given Camel endpoint */ - public CamelJbiEndpoint activateJbiEndpoint(JbiEndpoint camelEndpoint, Processor<Exchange> processor) throws Exception { + public CamelJbiEndpoint activateJbiEndpoint(JbiEndpoint camelEndpoint, Processor processor) throws Exception { CamelJbiEndpoint jbiEndpoint; String endpointUri = camelEndpoint.getEndpointUri(); if (endpointUri.startsWith("endpoint:")) { diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiEndpoint.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiEndpoint.java index e4db90b21710b..574da3c68f6f0 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiEndpoint.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/CamelJbiEndpoint.java @@ -34,16 +34,16 @@ public class CamelJbiEndpoint extends ProviderEndpoint { private static final QName SERVICE_NAME = new QName("http://camel.apache.org/service", "CamelEndpointComponent"); private Endpoint camelEndpoint; private JbiBinding binding; - private Processor<Exchange> processor; + private Processor processor; - public CamelJbiEndpoint(ServiceUnit serviceUnit, QName service, String endpoint, Endpoint camelEndpoint, JbiBinding binding, Processor<Exchange> processor) { + public CamelJbiEndpoint(ServiceUnit serviceUnit, QName service, String endpoint, Endpoint camelEndpoint, JbiBinding binding, Processor processor) { super(serviceUnit, service, endpoint); this.processor = processor; this.camelEndpoint = camelEndpoint; this.binding = binding; } - public CamelJbiEndpoint(ServiceUnit serviceUnit, Endpoint camelEndpoint, JbiBinding binding, Processor<Exchange> processor) { + public CamelJbiEndpoint(ServiceUnit serviceUnit, Endpoint camelEndpoint, JbiBinding binding, Processor processor) { this(serviceUnit, SERVICE_NAME, camelEndpoint.getEndpointUri(), camelEndpoint, binding, processor); } diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/FromJbiProcessor.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/FromJbiProcessor.java index de24d0c4b06b9..c28bd4bdb21b5 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/FromJbiProcessor.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/FromJbiProcessor.java @@ -30,9 +30,9 @@ public class FromJbiProcessor implements MessageExchangeListener { private CamelContext context; private JbiBinding binding; - private Processor<JbiExchange> processor; + private Processor processor; - public FromJbiProcessor(CamelContext context, JbiBinding binding, Processor<JbiExchange> processor) { + public FromJbiProcessor(CamelContext context, JbiBinding binding, Processor processor) { this.context = context; this.binding = binding; this.processor = processor; diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/JbiEndpoint.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/JbiEndpoint.java index c13d433874573..96ec222ad4130 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/JbiEndpoint.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/JbiEndpoint.java @@ -32,7 +32,7 @@ * @version $Revision$ */ public class JbiEndpoint extends DefaultEndpoint<Exchange> { - private Processor<Exchange> toJbiProcessor; + private Processor toJbiProcessor; private final CamelJbiComponent jbiComponent; public JbiEndpoint(CamelJbiComponent jbiComponent, String uri) { @@ -49,7 +49,7 @@ public void process(Exchange exchange) throws Exception { }); } - public Consumer<Exchange> createConsumer(final Processor<Exchange> processor) throws Exception { + public Consumer<Exchange> createConsumer(final Processor processor) throws Exception { return startService(new DefaultConsumer<Exchange>(this, processor) { CamelJbiEndpoint jbiEndpoint; diff --git a/camel-jbi/src/main/java/org/apache/camel/component/jbi/ToJbiProcessor.java b/camel-jbi/src/main/java/org/apache/camel/component/jbi/ToJbiProcessor.java index 753a2156275f5..d7ed9bf10b7a0 100644 --- a/camel-jbi/src/main/java/org/apache/camel/component/jbi/ToJbiProcessor.java +++ b/camel-jbi/src/main/java/org/apache/camel/component/jbi/ToJbiProcessor.java @@ -32,7 +32,7 @@ * * @version $Revision$ */ -public class ToJbiProcessor implements Processor<Exchange> { +public class ToJbiProcessor implements Processor { private JbiBinding binding; private ComponentContext componentContext; private String destinationUri; diff --git a/camel-jbi/src/test/java/org/apache/camel/component/jbi/JbiTestSupport.java b/camel-jbi/src/test/java/org/apache/camel/component/jbi/JbiTestSupport.java index f0cad00366a9d..3fe66d2e4e41a 100644 --- a/camel-jbi/src/test/java/org/apache/camel/component/jbi/JbiTestSupport.java +++ b/camel-jbi/src/test/java/org/apache/camel/component/jbi/JbiTestSupport.java @@ -51,7 +51,7 @@ public abstract class JbiTestSupport extends TestSupport { * Sends an exchange to the endpoint */ protected void sendExchange(final Object expectedBody) { - client.send(endpoint, new Processor<Exchange>() { + client.send(endpoint, new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody(expectedBody); diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java b/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java index 7aa16cd43d2f1..7a6c3b15d5518 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java @@ -35,10 +35,10 @@ public class EndpointMessageListener<E extends Exchange> implements MessageListener { private static final transient Log log = LogFactory.getLog(EndpointMessageListener.class); private Endpoint<E> endpoint; - private Processor<E> processor; + private Processor processor; private JmsBinding binding; - public EndpointMessageListener(Endpoint<E> endpoint, Processor<E> processor) { + public EndpointMessageListener(Endpoint<E> endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java index dc847ad6140ed..5fe6f2d8b09e9 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsBinding.java @@ -17,6 +17,8 @@ */ package org.apache.camel.component.jms; +import org.apache.camel.Exchange; + import javax.jms.BytesMessage; import javax.jms.JMSException; import javax.jms.MapMessage; @@ -77,33 +79,33 @@ else if (message instanceof BytesMessage || message instanceof StreamMessage) { * @return a newly created JMS Message instance containing the * @throws JMSException if the message could not be created */ - public Message makeJmsMessage(JmsMessage message, Session session) throws JMSException { - Message answer = createJmsMessage(message, session); - appendJmsProperties(answer, message, session); + public Message makeJmsMessage(Exchange exchange, Session session) throws JMSException { + Message answer = createJmsMessage(exchange.getIn().getBody(), session); + appendJmsProperties(answer, exchange, session); return answer; } /** * Appends the JMS headers from the Camel {@link JmsMessage} */ - protected void appendJmsProperties(Message jmsMessage, JmsMessage camelMessage, Session session) throws JMSException { - Set<Map.Entry<String, Object>> entries = camelMessage.getHeaders().entrySet(); + protected void appendJmsProperties(Message jmsMessage, Exchange exchange, Session session) throws JMSException { + org.apache.camel.Message in = exchange.getIn(); + Set<Map.Entry<String, Object>> entries = in.getHeaders().entrySet(); for (Map.Entry<String, Object> entry : entries) { String headerName = entry.getKey(); Object headerValue = entry.getValue(); - if (shouldOutputHeader(camelMessage, headerName, headerValue)) { + if (shouldOutputHeader(in, headerName, headerValue)) { jmsMessage.setObjectProperty(headerName, headerValue); } } } - protected Message createJmsMessage(JmsMessage message, Session session) throws JMSException { - Object value = message.getBody(); - if (value instanceof String) { - return session.createTextMessage((String) value); + protected Message createJmsMessage(Object body, Session session) throws JMSException { + if (body instanceof String) { + return session.createTextMessage((String) body); } - else if (value instanceof Serializable) { - return session.createObjectMessage((Serializable) value); + else if (body instanceof Serializable) { + return session.createObjectMessage((Serializable) body); } else { return session.createMessage(); @@ -127,7 +129,7 @@ public Map<String, Object> createMapFromMapMessage(MapMessage message) throws JM /** * Strategy to allow filtering of headers which are put on the JMS message */ - protected boolean shouldOutputHeader(JmsMessage camelMessage, String headerName, Object headerValue) { + protected boolean shouldOutputHeader(org.apache.camel.Message camelMessage, String headerName, Object headerValue) { return true; } } diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java index 4a3e9580496fd..340b3b6c34b2a 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java @@ -32,7 +32,7 @@ public class JmsConsumer extends DefaultConsumer<JmsExchange> { private final AbstractMessageListenerContainer listenerContainer; - public JmsConsumer(JmsEndpoint endpoint, Processor<JmsExchange> processor, AbstractMessageListenerContainer listenerContainer) { + public JmsConsumer(JmsEndpoint endpoint, Processor processor, AbstractMessageListenerContainer listenerContainer) { super(endpoint, processor); this.listenerContainer = listenerContainer; @@ -40,7 +40,7 @@ public JmsConsumer(JmsEndpoint endpoint, Processor<JmsExchange> processor, Abstr this.listenerContainer.setMessageListener(messageListener); } - protected MessageListener createMessageListener(JmsEndpoint endpoint, Processor<JmsExchange> processor) { + protected MessageListener createMessageListener(JmsEndpoint endpoint, Processor processor) { EndpointMessageListener<JmsExchange> messageListener = new EndpointMessageListener<JmsExchange>(endpoint, processor); messageListener.setBinding(endpoint.getBinding()); return messageListener; diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java index e76b0b638a744..ace0f81a619cc 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java @@ -60,7 +60,7 @@ public Producer<JmsExchange> createProducer(JmsOperations template) throws Excep return startService(new JmsProducer(this, template)); } - public Consumer<JmsExchange> createConsumer(Processor<JmsExchange> processor) throws Exception { + public Consumer<JmsExchange> createConsumer(Processor processor) throws Exception { AbstractMessageListenerContainer listenerContainer = configuration.createMessageListenerContainer(); return createConsumer(processor, listenerContainer); } @@ -73,7 +73,7 @@ public Consumer<JmsExchange> createConsumer(Processor<JmsExchange> processor) th * @return a newly created consumer * @throws Exception if the consumer cannot be created */ - public Consumer<JmsExchange> createConsumer(Processor<JmsExchange> processor, AbstractMessageListenerContainer listenerContainer) throws Exception { + public Consumer<JmsExchange> createConsumer(Processor processor, AbstractMessageListenerContainer listenerContainer) throws Exception { listenerContainer.setDestinationName(destination); listenerContainer.setPubSubDomain(pubSubDomain); if (selector != null) { diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java index 4bbdbfb262a76..2d4d7b54f2c25 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java @@ -31,7 +31,7 @@ /** * @version $Revision$ */ -public class JmsProducer extends DefaultProducer<JmsExchange> { +public class JmsProducer extends DefaultProducer { private static final transient Log log = LogFactory.getLog(JmsProducer.class); private final JmsEndpoint endpoint; private final JmsOperations template; @@ -42,10 +42,10 @@ public JmsProducer(JmsEndpoint endpoint, JmsOperations template) { this.template = template; } - public void process(final JmsExchange exchange) { + public void process(final Exchange exchange) { template.send(endpoint.getDestination(), new MessageCreator() { public Message createMessage(Session session) throws JMSException { - Message message = endpoint.getBinding().makeJmsMessage(exchange.getIn(), session); + Message message = endpoint.getBinding().makeJmsMessage(exchange, session); if (log.isDebugEnabled()) { log.debug(endpoint + " sending JMS message: " + message); } diff --git a/camel-jms/src/main/java/org/apache/camel/component/jms/MessageListenerProcessor.java b/camel-jms/src/main/java/org/apache/camel/component/jms/MessageListenerProcessor.java index 2ac2afff13436..5843fe951d83d 100644 --- a/camel-jms/src/main/java/org/apache/camel/component/jms/MessageListenerProcessor.java +++ b/camel-jms/src/main/java/org/apache/camel/component/jms/MessageListenerProcessor.java @@ -32,9 +32,9 @@ */ public class MessageListenerProcessor implements MessageListener { private final JmsEndpoint endpoint; - private final Processor<Exchange> processor; + private final Processor processor; - public MessageListenerProcessor(JmsEndpoint endpoint, Processor<Exchange> processor) { + public MessageListenerProcessor(JmsEndpoint endpoint, Processor processor) { this.endpoint = endpoint; this.processor = processor; } diff --git a/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteTest.java b/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteTest.java index d40b12761bc6d..9eaf26bc80996 100644 --- a/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteTest.java +++ b/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteTest.java @@ -22,6 +22,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; import org.apache.camel.impl.DefaultCamelContext; @@ -65,12 +66,11 @@ public void testJmsRouteWithObjectMessage() throws Exception { } protected void sendExchange(final Object expectedBody) { - client.send(endpoint, new Processor<JmsExchange>() { - public void process(JmsExchange exchange) { + client.send(endpoint, new Processor() { + public void process(Exchange exchange) { // now lets fire in a message - JmsMessage in = exchange.getIn(); - in.setBody(expectedBody); - in.setHeader("cheese", 123); + exchange.getIn().setBody(expectedBody); + exchange.getIn().setHeader("cheese", 123); } }); } @@ -103,10 +103,10 @@ protected void setUp() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from("activemq:queue:test.a").to("activemq:queue:test.b"); - from("activemq:queue:test.b").process(new Processor<JmsExchange>() { - public void process(JmsExchange e) { + from("activemq:queue:test.b").process(new Processor() { + public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); - receivedExchange = e; + receivedExchange = (JmsExchange) e; latch.countDown(); } }); diff --git a/camel-jms/src/test/java/org/apache/camel/component/jms/TransactedJmsRouteTest.java b/camel-jms/src/test/java/org/apache/camel/component/jms/TransactedJmsRouteTest.java index f02104294f47f..78e6a98784582 100644 --- a/camel-jms/src/test/java/org/apache/camel/component/jms/TransactedJmsRouteTest.java +++ b/camel-jms/src/test/java/org/apache/camel/component/jms/TransactedJmsRouteTest.java @@ -28,6 +28,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.ContextTestSupport; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.processor.DelegateProcessor; @@ -66,7 +67,7 @@ public void configure() { public Processor wrap(Processor processor) { return new DelegateProcessor(processor) { @Override - public void process(Object exchange) throws Exception { + public void process(Exchange exchange) throws Exception { processNext(exchange); throw new RuntimeException("rollback"); } @@ -83,7 +84,7 @@ public String toString() { public Processor wrap(Processor processor) { return new DelegateProcessor(processor) { @Override - public void process(Object exchange) { + public void process(Exchange exchange) { try { processNext(exchange); } catch ( Throwable e ) { diff --git a/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java b/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java index ae81dc2f7837c..824211564d940 100644 --- a/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java +++ b/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java @@ -47,7 +47,7 @@ public class JpaConsumer extends PollingConsumer<Exchange> { private String namedQuery; private String nativeQuery; - public JpaConsumer(JpaEndpoint endpoint, Processor<Exchange> processor) { + public JpaConsumer(JpaEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; this.template = endpoint.createTransactionStrategy(); diff --git a/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java b/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java index cbd7b175730be..68cb4680954ab 100644 --- a/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java +++ b/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java @@ -60,7 +60,7 @@ public Producer<Exchange> createProducer() throws Exception { return startService(new JpaProducer(this, getProducerExpression())); } - public Consumer<Exchange> createConsumer(Processor<Exchange> processor) throws Exception { + public Consumer<Exchange> createConsumer(Processor processor) throws Exception { JpaConsumer consumer = new JpaConsumer(this, processor); configureConsumer(consumer); return startService(consumer); diff --git a/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaTest.java b/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaTest.java index 3e410c61e3f16..351cb334c143c 100644 --- a/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaTest.java +++ b/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaTest.java @@ -68,7 +68,7 @@ public Object doInJpa(EntityManager entityManager) throws PersistenceException { assertEquals("Should have no results: " + results, 0, results.size()); // lets produce some objects - client.send(endpoint, new Processor<Exchange>() { + client.send(endpoint, new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody(new SendEmail("[email protected]")); } @@ -81,7 +81,7 @@ public void process(Exchange exchange) { assertEquals("address property", "[email protected]", mail.getAddress()); // now lets create a consumer to consume it - consumer = endpoint.createConsumer(new Processor<Exchange>() { + consumer = endpoint.createConsumer(new Processor() { public void process(Exchange e) { log.info("Received exchange: " + e.getIn()); receivedExchange = e; diff --git a/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithNamedQueryTest.java b/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithNamedQueryTest.java index f951d4f222be2..459d1c2f72199 100644 --- a/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithNamedQueryTest.java +++ b/camel-jpa/src/test/java/org/apache/camel/component/jpa/JpaWithNamedQueryTest.java @@ -72,7 +72,7 @@ public Object doInJpa(EntityManager entityManager) throws PersistenceException { assertEquals("Should have no results: " + results, 0, results.size()); // lets produce some objects - client.send(endpoint, new Processor<Exchange>() { + client.send(endpoint, new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody(new MultiSteps("[email protected]")); } @@ -85,7 +85,7 @@ public void process(Exchange exchange) { assertEquals("address property", "[email protected]", mail.getAddress()); // now lets create a consumer to consume it - consumer = endpoint.createConsumer(new Processor<Exchange>() { + consumer = endpoint.createConsumer(new Processor() { public void process(Exchange e) { log.info("Received exchange: " + e.getIn()); receivedExchange = e; diff --git a/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java b/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java index c2b110a264aa0..96ab82165d8bf 100644 --- a/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java +++ b/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java @@ -17,6 +17,8 @@ */ package org.apache.camel.component.mail; +import org.apache.camel.Exchange; + import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Address; @@ -32,7 +34,7 @@ * @version $Revision: 521240 $ */ public class MailBinding { - public void populateMailMessage(MailEndpoint endpoint, MimeMessage mimeMessage, MailExchange exchange) { + public void populateMailMessage(MailEndpoint endpoint, MimeMessage mimeMessage, Exchange exchange) { try { appendMailHeaders(mimeMessage, exchange.getIn()); @@ -75,7 +77,7 @@ public Object extractBodyFromMail(MailExchange exchange, Message message) { /** * Appends the Mail headers from the Camel {@link MailMessage} */ - protected void appendMailHeaders(MimeMessage mimeMessage, MailMessage camelMessage) throws MessagingException { + protected void appendMailHeaders(MimeMessage mimeMessage, org.apache.camel.Message camelMessage) throws MessagingException { Set<Map.Entry<String, Object>> entries = camelMessage.getHeaders().entrySet(); for (Map.Entry<String, Object> entry : entries) { String headerName = entry.getKey(); @@ -91,7 +93,7 @@ protected void appendMailHeaders(MimeMessage mimeMessage, MailMessage camelMessa /** * Strategy to allow filtering of headers which are put on the Mail message */ - protected boolean shouldOutputHeader(MailMessage camelMessage, String headerName, Object headerValue) { + protected boolean shouldOutputHeader(org.apache.camel.Message camelMessage, String headerName, Object headerValue) { return true; } } diff --git a/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java b/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java index 76f773a51d445..b7dcbdfe4f97c 100644 --- a/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java +++ b/camel-mail/src/main/java/org/apache/camel/component/mail/MailConsumer.java @@ -42,7 +42,7 @@ public class MailConsumer extends PollingConsumer<MailExchange> implements Messa private final MailEndpoint endpoint; private final Folder folder; - public MailConsumer(MailEndpoint endpoint, Processor<MailExchange> processor, Folder folder) { + public MailConsumer(MailEndpoint endpoint, Processor processor, Folder folder) { super(endpoint, processor); this.endpoint = endpoint; this.folder = folder; diff --git a/camel-mail/src/main/java/org/apache/camel/component/mail/MailEndpoint.java b/camel-mail/src/main/java/org/apache/camel/component/mail/MailEndpoint.java index a63eb93fdb20f..5e7a4caaa7b18 100644 --- a/camel-mail/src/main/java/org/apache/camel/component/mail/MailEndpoint.java +++ b/camel-mail/src/main/java/org/apache/camel/component/mail/MailEndpoint.java @@ -51,7 +51,7 @@ public Producer<MailExchange> createProducer(JavaMailSender sender) throws Excep return startService(new MailProducer(this, sender)); } - public Consumer<MailExchange> createConsumer(Processor<MailExchange> processor) throws Exception { + public Consumer<MailExchange> createConsumer(Processor processor) throws Exception { JavaMailConnection connection = configuration.createJavaMailConnection(this); String protocol = getConfiguration().getProtocol(); if (protocol.equals("smtp")) { @@ -73,7 +73,7 @@ public Consumer<MailExchange> createConsumer(Processor<MailExchange> processor) * @return a newly created consumer * @throws Exception if the consumer cannot be created */ - public Consumer<MailExchange> createConsumer(Processor<MailExchange> processor, Folder folder) throws Exception { + public Consumer<MailExchange> createConsumer(Processor processor, Folder folder) throws Exception { MailConsumer answer = new MailConsumer(this, processor, folder); configureConsumer(answer); return startService(answer); diff --git a/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java b/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java index d87bb7791e30c..a4041de14c546 100644 --- a/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java +++ b/camel-mail/src/main/java/org/apache/camel/component/mail/MailProducer.java @@ -18,6 +18,7 @@ package org.apache.camel.component.mail; import org.apache.camel.impl.DefaultProducer; +import org.apache.camel.Exchange; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.mail.javamail.JavaMailSender; @@ -40,7 +41,7 @@ public MailProducer(MailEndpoint endpoint, JavaMailSender sender) { } - public void process(final MailExchange exchange) { + public void process(final Exchange exchange) { sender.send(new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { endpoint.getBinding().populateMailMessage(endpoint, mimeMessage, exchange); diff --git a/camel-mail/src/test/java/org/apache/camel/component/mail/MailRouteTest.java b/camel-mail/src/test/java/org/apache/camel/component/mail/MailRouteTest.java index dd24dc914f238..f228de184a1b0 100644 --- a/camel-mail/src/test/java/org/apache/camel/component/mail/MailRouteTest.java +++ b/camel-mail/src/test/java/org/apache/camel/component/mail/MailRouteTest.java @@ -41,7 +41,7 @@ public void testSendAndReceiveMails() throws Exception { resultEndpoint = (MockEndpoint) resolveMandatoryEndpoint("mock:result"); resultEndpoint.expectedBodiesReceived("hello world!"); - client.send("smtp://james@localhost", new Processor<Exchange>() { + client.send("smtp://james@localhost", new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody("hello world!"); } diff --git a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaConsumer.java b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaConsumer.java index 4b1787f175aee..0add4f5dffb5f 100644 --- a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaConsumer.java +++ b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaConsumer.java @@ -40,7 +40,7 @@ public class MinaConsumer extends DefaultConsumer<MinaExchange> { private final SocketAddress address; private final IoAcceptor acceptor; - public MinaConsumer(final MinaEndpoint endpoint, Processor<MinaExchange> processor) { + public MinaConsumer(final MinaEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; address = endpoint.getAddress(); diff --git a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaEndpoint.java b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaEndpoint.java index aed1262ac63e0..a81d540cad95c 100644 --- a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaEndpoint.java +++ b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaEndpoint.java @@ -53,7 +53,7 @@ public Producer<MinaExchange> createProducer() throws Exception { return startService(new MinaProducer(this)); } - public Consumer<MinaExchange> createConsumer(Processor<MinaExchange> processor) throws Exception { + public Consumer<MinaExchange> createConsumer(Processor processor) throws Exception { return startService(new MinaConsumer(this, processor)); } diff --git a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java index edbd27540db26..a356241f1d3b1 100644 --- a/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java +++ b/camel-mina/src/main/java/org/apache/camel/component/mina/MinaProducer.java @@ -18,6 +18,7 @@ package org.apache.camel.component.mina; import org.apache.camel.Producer; +import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultProducer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -34,7 +35,7 @@ * * @version $Revision$ */ -public class MinaProducer extends DefaultProducer<MinaExchange> { +public class MinaProducer extends DefaultProducer { private static final transient Log log = LogFactory.getLog(MinaProducer.class); private IoSession session; private MinaEndpoint endpoint; @@ -44,7 +45,7 @@ public MinaProducer(MinaEndpoint endpoint) { this.endpoint = endpoint; } - public void process(MinaExchange exchange) { + public void process(Exchange exchange) { if (session == null) { throw new IllegalStateException("Not started yet!"); } diff --git a/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVmTest.java b/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVmTest.java index 36d7d298e8c2c..f1bc92e836b63 100644 --- a/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVmTest.java +++ b/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVmTest.java @@ -23,6 +23,7 @@ import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Producer; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; @@ -35,7 +36,7 @@ public class MinaVmTest extends TestCase { protected CamelContext container = new DefaultCamelContext(); protected CountDownLatch latch = new CountDownLatch(1); - protected MinaExchange receivedExchange; + protected Exchange receivedExchange; protected String uri = "mina:vm://localhost:8080"; protected Producer<MinaExchange> producer; @@ -74,8 +75,8 @@ protected void tearDown() throws Exception { protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { - from(uri).process(new Processor<MinaExchange>() { - public void process(MinaExchange e) { + from(uri).process(new Processor() { + public void process(Exchange e) { System.out.println("Received exchange: " + e.getIn()); receivedExchange = e; latch.countDown(); diff --git a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiConsumer.java b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiConsumer.java index 6a67589784660..dd5760b074c05 100644 --- a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiConsumer.java +++ b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiConsumer.java @@ -42,7 +42,7 @@ public class RmiConsumer extends DefaultConsumer<PojoExchange> implements Invoca private Remote stub; private Remote proxy; - public RmiConsumer(RmiEndpoint endpoint, Processor<PojoExchange> processor) { + public RmiConsumer(RmiEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; diff --git a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiEndpoint.java b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiEndpoint.java index e39c1d3bdeb0b..df9065b3610ff 100644 --- a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiEndpoint.java +++ b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiEndpoint.java @@ -54,7 +54,7 @@ public PojoExchange createExchange() { return new PojoExchange(getContext()); } - public Consumer<PojoExchange> createConsumer(Processor<PojoExchange> processor) throws Exception { + public Consumer<PojoExchange> createConsumer(Processor processor) throws Exception { if( remoteInterfaces == null || remoteInterfaces.size()==0 ) throw new RuntimeCamelException("To create an RMI consumer, the RMI endpoint's remoteInterfaces property must be be configured."); return new RmiConsumer(this, processor); diff --git a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiProducer.java b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiProducer.java index 7c045b66e82e9..fad7d954d96ef 100644 --- a/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiProducer.java +++ b/camel-rmi/src/main/java/org/apache/camel/component/rmi/RmiProducer.java @@ -26,11 +26,12 @@ import org.apache.camel.component.pojo.PojoEndpoint; import org.apache.camel.component.pojo.PojoExchange; import org.apache.camel.impl.DefaultProducer; +import org.apache.camel.Exchange; /** * @version $Revision: 533076 $ */ -public class RmiProducer extends DefaultProducer<PojoExchange> { +public class RmiProducer extends DefaultProducer { private final RmiEndpoint endpoint; private Remote remote; @@ -40,9 +41,9 @@ public RmiProducer(RmiEndpoint endpoint) throws AccessException, RemoteException this.endpoint = endpoint; } - public void process(PojoExchange exchange) throws AccessException, RemoteException, NotBoundException { - - PojoEndpoint.invoke(getRemote(), exchange); + public void process(Exchange exchange) throws AccessException, RemoteException, NotBoundException { + PojoExchange pojoExchange = endpoint.toExchangeType(exchange); + PojoEndpoint.invoke(getRemote(), pojoExchange); } public Remote getRemote() throws AccessException, RemoteException, NotBoundException { diff --git a/camel-script/src/main/java/org/apache/camel/builder/script/ScriptBuilder.java b/camel-script/src/main/java/org/apache/camel/builder/script/ScriptBuilder.java index 9a08f62c0d7dc..c42511168a1e1 100644 --- a/camel-script/src/main/java/org/apache/camel/builder/script/ScriptBuilder.java +++ b/camel-script/src/main/java/org/apache/camel/builder/script/ScriptBuilder.java @@ -43,7 +43,7 @@ * * @version $Revision$ */ -public class ScriptBuilder<E extends Exchange> implements Expression<E>, Predicate<E>, Processor<E> { +public class ScriptBuilder<E extends Exchange> implements Expression<E>, Predicate<E>, Processor { private String scriptEngineName; private Resource scriptResource; private String scriptText; @@ -81,7 +81,7 @@ public void assertMatches(String text, E exchange) throws AssertionError { } } - public void process(E exchange) { + public void process(Exchange exchange) { evaluateScript(exchange); } diff --git a/camel-spring/src/main/java/org/apache/camel/spring/spi/SpringTransactionPolicy.java b/camel-spring/src/main/java/org/apache/camel/spring/spi/SpringTransactionPolicy.java index 90e12f4e8649c..9c79aeebc55f5 100644 --- a/camel-spring/src/main/java/org/apache/camel/spring/spi/SpringTransactionPolicy.java +++ b/camel-spring/src/main/java/org/apache/camel/spring/spi/SpringTransactionPolicy.java @@ -19,6 +19,7 @@ import org.apache.camel.Processor; import org.apache.camel.RuntimeCamelException; +import org.apache.camel.Exchange; import org.apache.camel.processor.DelegateProcessor; import org.apache.camel.spi.Policy; import org.apache.commons.logging.Log; @@ -45,16 +46,16 @@ public SpringTransactionPolicy(TransactionTemplate template) { this.template = template; } - public Processor<E> wrap(Processor<E> processor) { + public Processor wrap(Processor processor) { final TransactionTemplate transactionTemplate = getTemplate(); if (transactionTemplate == null) { log.warn("No TransactionTemplate available so transactions will not be enabled!"); return processor; } - return new DelegateProcessor<E>(processor) { + return new DelegateProcessor(processor) { - public void process(final E exchange) { + public void process(final Exchange exchange) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { diff --git a/camel-spring/src/test/java/org/apache/camel/spring/CustomProcessorWithNamespacesTest.java b/camel-spring/src/test/java/org/apache/camel/spring/CustomProcessorWithNamespacesTest.java index c17b6fb39dd78..87d09af197854 100644 --- a/camel-spring/src/test/java/org/apache/camel/spring/CustomProcessorWithNamespacesTest.java +++ b/camel-spring/src/test/java/org/apache/camel/spring/CustomProcessorWithNamespacesTest.java @@ -44,7 +44,7 @@ public void testXMLRouteLoading() throws Exception { // now lets send a message CamelClient<Exchange> client = new CamelClient<Exchange>(context); - client.send("direct:start", new Processor<Exchange>() { + client.send("direct:start", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setHeader("name", "James"); diff --git a/camel-spring/src/test/java/org/apache/camel/spring/RoutingUsingCamelContextFactoryTest.java b/camel-spring/src/test/java/org/apache/camel/spring/RoutingUsingCamelContextFactoryTest.java index f702073b2f9fe..771395d19bdea 100644 --- a/camel-spring/src/test/java/org/apache/camel/spring/RoutingUsingCamelContextFactoryTest.java +++ b/camel-spring/src/test/java/org/apache/camel/spring/RoutingUsingCamelContextFactoryTest.java @@ -47,7 +47,7 @@ public void testXMLRouteLoading() throws Exception { // now lets send a message CamelClient<Exchange> client = new CamelClient<Exchange>(context); - client.send("queue:start", new Processor<Exchange>() { + client.send("queue:start", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setHeader("name", "James"); diff --git a/camel-spring/src/test/java/org/apache/camel/spring/example/MyProcessor.java b/camel-spring/src/test/java/org/apache/camel/spring/example/MyProcessor.java index 4e472e85e4dbd..16c4e3d9637ab 100644 --- a/camel-spring/src/test/java/org/apache/camel/spring/example/MyProcessor.java +++ b/camel-spring/src/test/java/org/apache/camel/spring/example/MyProcessor.java @@ -26,7 +26,7 @@ /** * @version $Revision: 1.1 $ */ -public class MyProcessor implements Processor<Exchange> { +public class MyProcessor implements Processor { private static List exchanges = new CopyOnWriteArrayList(); private String name = "James"; diff --git a/camel-spring/src/test/java/org/apache/camel/spring/xml/XmlRouteBuilderTest.java b/camel-spring/src/test/java/org/apache/camel/spring/xml/XmlRouteBuilderTest.java index f7ec8dcf3efb5..b3332507f3c05 100644 --- a/camel-spring/src/test/java/org/apache/camel/spring/xml/XmlRouteBuilderTest.java +++ b/camel-spring/src/test/java/org/apache/camel/spring/xml/XmlRouteBuilderTest.java @@ -54,7 +54,7 @@ protected RouteBuilder buildSimpleRoute() { @Override protected RouteBuilder buildCustomProcessor() { - myProcessor = (Processor<Exchange>) ctx.getBean("myProcessor"); + myProcessor = (Processor) ctx.getBean("myProcessor"); RouteBuilder builder = (RouteBuilder) ctx.getBean("buildCustomProcessor"); assertNotNull(builder); return builder; @@ -62,7 +62,7 @@ protected RouteBuilder buildCustomProcessor() { @Override protected RouteBuilder buildCustomProcessorWithFilter() { - myProcessor = (Processor<Exchange>) ctx.getBean("myProcessor"); + myProcessor = (Processor) ctx.getBean("myProcessor"); RouteBuilder builder = (RouteBuilder) ctx.getBean("buildCustomProcessorWithFilter"); assertNotNull(builder); return builder; @@ -70,8 +70,8 @@ protected RouteBuilder buildCustomProcessorWithFilter() { @Override protected RouteBuilder buildRouteWithInterceptor() { - interceptor1 = (DelegateProcessor<Exchange>) ctx.getBean("interceptor1"); - interceptor2 = (DelegateProcessor<Exchange>) ctx.getBean("interceptor2"); + interceptor1 = (DelegateProcessor) ctx.getBean("interceptor1"); + interceptor2 = (DelegateProcessor) ctx.getBean("interceptor2"); RouteBuilder builder = (RouteBuilder) ctx.getBean("buildRouteWithInterceptor"); assertNotNull(builder); return builder; diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppBinding.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppBinding.java index 10388b0bb58c2..256c1c86e3be7 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppBinding.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppBinding.java @@ -18,6 +18,7 @@ package org.apache.camel.component.xmpp; import org.jivesoftware.smack.packet.Message; +import org.apache.camel.Exchange; import java.util.Map; import java.util.Set; @@ -32,7 +33,7 @@ public class XmppBinding { /** * Populates the given XMPP message from the inbound exchange */ - public void populateXmppMessage(Message message, XmppExchange exchange) { + public void populateXmppMessage(Message message, Exchange exchange) { message.setBody(exchange.getIn().getBody(String.class)); Set<Map.Entry<String, Object>> entries = exchange.getIn().getHeaders().entrySet(); @@ -62,7 +63,7 @@ public Object extractBodyFromXmpp(XmppExchange exchange, Message message) { /** * Strategy to allow filtering of headers which are put on the XMPP message */ - protected boolean shouldOutputHeader(XmppExchange exchange, String headerName, Object headerValue) { + protected boolean shouldOutputHeader(Exchange exchange, String headerName, Object headerValue) { return true; } } diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java index 0d8e0595474e9..b64ab4d07305e 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppConsumer.java @@ -38,7 +38,7 @@ public class XmppConsumer extends DefaultConsumer<XmppExchange> implements Packe private static final transient Log log = LogFactory.getLog(XmppConsumer.class); private final XmppEndpoint endpoint; - public XmppConsumer(XmppEndpoint endpoint, Processor<XmppExchange> processor) { + public XmppConsumer(XmppEndpoint endpoint, Processor processor) { super(endpoint, processor); this.endpoint = endpoint; } diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java index a9b764d11f824..0addf3b1ff5c7 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppEndpoint.java @@ -75,7 +75,7 @@ public Producer<XmppExchange> createPrivateChatProducer(String participant) thro return startService(new XmppPrivateChatProducer(this, participant)); } - public Consumer<XmppExchange> createConsumer(Processor<XmppExchange> processor) throws Exception { + public Consumer<XmppExchange> createConsumer(Processor processor) throws Exception { return startService(new XmppConsumer(this, processor)); } diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java index 705e950e1043e..604a38c146b02 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java @@ -28,7 +28,7 @@ /** * @version $Revision$ */ -public class XmppGroupChatProducer extends DefaultProducer<XmppExchange> { +public class XmppGroupChatProducer extends DefaultProducer { private static final transient Log log = LogFactory.getLog(XmppGroupChatProducer.class); private final XmppEndpoint endpoint; private final String room; @@ -43,13 +43,7 @@ public XmppGroupChatProducer(XmppEndpoint endpoint, String room) { } } - public void onExchange(Exchange exchange) { - // lets convert to the type of an exchange - XmppExchange xmppExchange = endpoint.convertTo(XmppExchange.class, exchange); - process(xmppExchange); - } - - public void process(XmppExchange exchange) { + public void process(Exchange exchange) { // TODO it would be nice if we could reuse the message from the exchange Message message = chat.createMessage(); message.setTo(room); diff --git a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppPrivateChatProducer.java b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppPrivateChatProducer.java index 0e4a60a094a7a..f4377fb3e9f9c 100644 --- a/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppPrivateChatProducer.java +++ b/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppPrivateChatProducer.java @@ -28,7 +28,7 @@ /** * @version $Revision$ */ -public class XmppPrivateChatProducer extends DefaultProducer<XmppExchange> { +public class XmppPrivateChatProducer extends DefaultProducer { private static final transient Log log = LogFactory.getLog(XmppPrivateChatProducer.class); private final XmppEndpoint endpoint; private final String participant; @@ -43,13 +43,7 @@ public XmppPrivateChatProducer(XmppEndpoint endpoint, String participant) { } } - public void onExchange(Exchange exchange) { - // lets convert to the type of an exchange - XmppExchange xmppExchange = endpoint.convertTo(XmppExchange.class, exchange); - process(xmppExchange); - } - - public void process(XmppExchange exchange) { + public void process(Exchange exchange) { // TODO it would be nice if we could reuse the message from the exchange Message message = chat.createMessage(); message.setTo(participant); diff --git a/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppRouteTest.java b/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppRouteTest.java index 9cc085e0cc2d6..71a06d21bbc53 100644 --- a/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppRouteTest.java +++ b/camel-xmpp/src/test/java/org/apache/camel/component/xmpp/XmppRouteTest.java @@ -23,6 +23,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Processor; +import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.converter.ObjectConverter; import org.apache.camel.impl.DefaultCamelContext; @@ -80,12 +81,11 @@ protected static boolean isXmppServerPresent() { } protected void sendExchange(final Object expectedBody) { - client.send(endpoint, new Processor<XmppExchange>() { - public void process(XmppExchange exchange) { + client.send(endpoint, new Processor() { + public void process(Exchange exchange) { // now lets fire in a message - XmppMessage in = exchange.getIn(); - in.setBody(expectedBody); - in.setHeader("cheese", 123); + exchange.getIn().setBody(expectedBody); + exchange.getIn().setHeader("cheese", 123); } }); } @@ -120,10 +120,10 @@ protected void setUp() throws Exception { container.addRoutes(new RouteBuilder() { public void configure() { from(uri1).to(uri2); - from(uri2).process(new Processor<XmppExchange>() { - public void process(XmppExchange e) { + from(uri2).process(new Processor() { + public void process(Exchange e) { log.info("Received exchange: " + e); - receivedExchange = e; + receivedExchange = (XmppExchange) e; latch.countDown(); } });
747a478c6741b7e9e37bc00dbfe28ddc6982fb9b
orientdb
Issue -1604. Remote bag. Fix save notification.--
c
https://github.com/orientechnologies/orientdb
diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java index fd5f344b74e..35a7ab18158 100755 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java +++ b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java @@ -85,6 +85,7 @@ import com.orientechnologies.orient.core.storage.OStorageAbstract; import com.orientechnologies.orient.core.storage.OStorageOperationResult; import com.orientechnologies.orient.core.storage.OStorageProxy; +import com.orientechnologies.orient.core.storage.impl.local.paginated.ORecordSerializationContext; import com.orientechnologies.orient.core.tx.OTransaction; import com.orientechnologies.orient.core.tx.OTransactionAbstract; import com.orientechnologies.orient.core.version.ORecordVersion; @@ -1170,7 +1171,8 @@ private void readCollectionChanges(OChannelBinaryAsynchClient network) throws IO collectionManager.updateCollectionPointer(new UUID(mBitsOfId, lBitsOfId), pointer); } - collectionManager.clearPendingCollections(); + if (ORecordSerializationContext.getDepth() <= 1) + collectionManager.clearPendingCollections(); } public void rollback(OTransaction iTx) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/ORecordSerializationContext.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/ORecordSerializationContext.java index 0ef0bcdfe0f..1fd4504ee53 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/ORecordSerializationContext.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/ORecordSerializationContext.java @@ -31,6 +31,10 @@ protected Deque<ORecordSerializationContext> initialValue() { } }; + public static int getDepth() { + return ORecordSerializationContext.SERIALIZATION_CONTEXT_STACK.get().size(); + } + public static ORecordSerializationContext pushContext() { final Deque<ORecordSerializationContext> stack = SERIALIZATION_CONTEXT_STACK.get(); final ORecordSerializationContext context = new ORecordSerializationContext(); @@ -66,4 +70,4 @@ void executeOperations(OLocalPaginatedStorage storage) { operation.execute(storage); } } -} \ No newline at end of file +} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ORidBagTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ORidBagTest.java index 2e43b1706d9..27a55faefb9 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ORidBagTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ORidBagTest.java @@ -1159,10 +1159,10 @@ private void massiveInsertionIteration(Random rnd, List<OIdentifiable> rids, ORi while (bagIterator.hasNext()) { OIdentifiable bagValue = bagIterator.next(); - Assert.assertTrue(rids.contains(bagValue)); + Assert.assertTrue(rids.contains(bagValue)); } - Assert.assertEquals(bag.size(), rids.size()); + Assert.assertEquals(bag.size(), rids.size()); for (int i = 0; i < 100; i++) { if (rnd.nextDouble() < 0.2 & rids.size() > 5) { @@ -1183,20 +1183,20 @@ private void massiveInsertionIteration(Random rnd, List<OIdentifiable> rids, ORi while (bagIterator.hasNext()) { final OIdentifiable bagValue = bagIterator.next(); - Assert.assertTrue(rids.contains(bagValue)); + Assert.assertTrue(rids.contains(bagValue)); if (rnd.nextDouble() < 0.05) { bagIterator.remove(); - Assert.assertTrue(rids.remove(bagValue)); + Assert.assertTrue(rids.remove(bagValue)); } } - Assert.assertEquals(bag.size(), rids.size()); + Assert.assertEquals(bag.size(), rids.size()); bagIterator = bag.iterator(); while (bagIterator.hasNext()) { - final OIdentifiable bagValue = bagIterator.next(); - Assert.assertTrue(rids.contains(bagValue)); + final OIdentifiable bagValue = bagIterator.next(); + Assert.assertTrue(rids.contains(bagValue)); } } @@ -1277,83 +1277,83 @@ public void testDocumentHelper() { public void testAddNewItemsAndRemoveThem() { final List<OIdentifiable> rids = new ArrayList<OIdentifiable>(); ORidBag ridBag = new ORidBag(); - for (int i = 0; i < 10; i++) { + int size = 0; + for (int i = 0; i < 0; i++) { ODocument docToAdd = new ODocument(); for (int k = 0; k < 2; k++) { ridBag.add(docToAdd); rids.add(docToAdd); + size++; } - } - Assert.assertEquals(ridBag.size(), 20); + Assert.assertEquals(ridBag.size(), size); ODocument document = new ODocument(); document.field("ridBag", ridBag); document.save(); document = database.load(document.getIdentity(), "*:-1", true); ridBag = document.field("ridBag"); - Assert.assertEquals(ridBag.size(), 20); + Assert.assertEquals(ridBag.size(), size); final List<OIdentifiable> newDocs = new ArrayList<OIdentifiable>(); - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 1; i++) { ODocument docToAdd = new ODocument(); for (int k = 0; k < 2; k++) { ridBag.add(docToAdd); rids.add(docToAdd); newDocs.add(docToAdd); + size++; } } - Assert.assertEquals(ridBag.size(), 40); + Assert.assertEquals(ridBag.size(), size); Random rnd = new Random(); - int size = 40; - - for (int i = 0; i < 10; i++) { - if (rnd.nextBoolean()) { - OIdentifiable newDoc = newDocs.get(i); - rids.remove(newDoc); - ridBag.remove(newDoc); - newDocs.remove(newDoc); + // for (int i = 0; i < newDocs.size(); i++) { + // if (rnd.nextBoolean()) { + // OIdentifiable newDoc = newDocs.get(i); + // rids.remove(newDoc); + // ridBag.remove(newDoc); + // newDocs.remove(newDoc); + // + // size--; + // } + // } + // + // for (OIdentifiable identifiable : ridBag) { + // if (newDocs.contains(identifiable) && rnd.nextBoolean()) { + // ridBag.remove(identifiable); + // rids.remove(identifiable); + // + // size--; + // } + // } - size--; - } - } + Assert.assertEquals(ridBag.size(), size); + List<OIdentifiable> ridsCopy = new ArrayList<OIdentifiable>(rids); for (OIdentifiable identifiable : ridBag) { - if (newDocs.contains(identifiable) && rnd.nextBoolean()) { - ridBag.remove(identifiable); - rids.remove(identifiable); - - size--; - } + Assert.assertTrue(rids.remove(identifiable)); } - Assert.assertEquals(ridBag.size(), size); - List<OIdentifiable> ridsCopy = new ArrayList<OIdentifiable>(rids); - - for (OIdentifiable identifiable : ridBag) { - Assert.assertTrue(rids.remove(identifiable)); - } - - Assert.assertTrue(rids.isEmpty()); + Assert.assertTrue(rids.isEmpty()); - document.save(); + document.save(); - document = database.load(document.getIdentity(), "*:-1", false); - ridBag = document.field("ridBag"); + document = database.load(document.getIdentity(), "*:-1", false); + ridBag = document.field("ridBag"); - rids.addAll(ridsCopy); - for (OIdentifiable identifiable : ridBag) { - Assert.assertTrue(rids.remove(identifiable)); - } + rids.addAll(ridsCopy); + for (OIdentifiable identifiable : ridBag) { + Assert.assertTrue(rids.remove(identifiable)); + } - Assert.assertTrue(rids.isEmpty()); - Assert.assertEquals(ridBag.size(), size); + Assert.assertTrue(rids.isEmpty()); + Assert.assertEquals(ridBag.size(), size); } public void testJsonSerialization() {
9c3fba564ca4c860c1d6783458fb988883ef4f8c
hbase
HBASE-563 TestRowFilterAfterWrite erroneously- sets master address to 0.0.0.0:60100 rather than relying on conf--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@644948 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index 13021466b4e9..7f510efb8cb7 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -10,6 +10,8 @@ Hbase Change Log havoc of reassignments because open processing is done in series HBASE-547 UI shows hadoop version, not hbase version HBASE-561 HBase package does not include LICENSE.txt nor build.xml + HBASE-563 TestRowFilterAfterWrite erroneously sets master address to + 0.0.0.0:60100 rather than relying on conf NEW FEATURES HBASE-548 Tool to online single region diff --git a/src/test/org/apache/hadoop/hbase/filter/TestRowFilterAfterWrite.java b/src/test/org/apache/hadoop/hbase/filter/TestRowFilterAfterWrite.java index 480dd52c964f..2a3d4331752b 100644 --- a/src/test/org/apache/hadoop/hbase/filter/TestRowFilterAfterWrite.java +++ b/src/test/org/apache/hadoop/hbase/filter/TestRowFilterAfterWrite.java @@ -88,19 +88,6 @@ public TestRowFilterAfterWrite() { conf.setInt("ipc.client.timeout", 20 * 60 * 1000); } - /** - * {@inheritDoc} - */ - @Override - public void setUp() throws Exception { - // this.conf.set(HConstants.HBASE_DIR, "file:///opt/benchmark/hadoop/hbase"); - this.conf.set(HConstants.MASTER_ADDRESS, "0.0.0.0:60100"); - // Must call super.setup() after starting mini dfs cluster. Otherwise - // we get a local file system instead of hdfs - - super.setUp(); - } - /** * {@inheritDoc} */
6d11a551dcf9bb2ed2bd10530b1fbaf6f6380804
ReactiveX-RxJava
Added create with initial capacity, minor fix--
c
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java b/rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java index 4ea3e6e385..ff7033c0c5 100644 --- a/rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java +++ b/rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java @@ -17,8 +17,6 @@ import java.util.Arrays; import java.util.Collection; -import java.util.Collections; -import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; @@ -126,7 +124,7 @@ protected void terminate(Action1<Collection<SubjectObserver<? super T>>> onTermi */ try { // had to circumvent type check, we know what the array contains - onTerminate.call((Collection)newState.observersList); + onTerminate.call((Collection)Arrays.asList(newState.observers)); } finally { // mark that termination is completed newState.terminationLatch.countDown(); @@ -141,25 +139,22 @@ public SubjectObserver<Object>[] rawSnapshot() { return state.get().observers; } + @SuppressWarnings("rawtypes") protected static class State<T> { final boolean terminated; final CountDownLatch terminationLatch; final Subscription[] subscriptions; - final SubjectObserver<Object>[] observers; + final SubjectObserver[] observers; // to avoid lots of empty arrays final Subscription[] EMPTY_S = new Subscription[0]; - @SuppressWarnings("rawtypes") // to avoid lots of empty arrays final SubjectObserver[] EMPTY_O = new SubjectObserver[0]; - @SuppressWarnings("rawtypes") - final List<SubjectObserver<Object>> observersList; private State(boolean isTerminated, CountDownLatch terminationLatch, Subscription[] subscriptions, SubjectObserver[] observers) { this.terminationLatch = terminationLatch; this.terminated = isTerminated; this.subscriptions = subscriptions; this.observers = observers; - this.observersList = Arrays.asList(this.observers); } State() { @@ -167,7 +162,6 @@ private State(boolean isTerminated, CountDownLatch terminationLatch, this.terminationLatch = null; this.subscriptions = EMPTY_S; this.observers = EMPTY_O; - observersList = Collections.emptyList(); } public State<T> terminate() {
716aa6974c6c3a0cdfb65e6adbc0e5c59538a289
spring-framework
fixed scheduling tests--
c
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.context/src/main/java/org/springframework/scheduling/support/ScheduledMethodRunnable.java b/org.springframework.context/src/main/java/org/springframework/scheduling/support/ScheduledMethodRunnable.java index 2f7270747e65..207a717a05e1 100644 --- a/org.springframework.context/src/main/java/org/springframework/scheduling/support/ScheduledMethodRunnable.java +++ b/org.springframework.context/src/main/java/org/springframework/scheduling/support/ScheduledMethodRunnable.java @@ -23,12 +23,13 @@ import org.springframework.util.ReflectionUtils; /** - * Variation of {@link MethodInvokingRunnable} meant to be used for processing + * Variant of {@link MethodInvokingRunnable} meant to be used for processing * of no-arg scheduled methods. Propagates user exceptions to the caller, * assuming that an error strategy for Runnables is in place. * * @author Juergen Hoeller * @since 3.0.6 + * @see org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor */ public class ScheduledMethodRunnable implements Runnable { @@ -59,6 +60,7 @@ public Method getMethod() { public void run() { try { + ReflectionUtils.makeAccessible(this.method); this.method.invoke(this.target); } catch (InvocationTargetException ex) { diff --git a/org.springframework.context/src/test/java/org/springframework/scheduling/annotation/taskNamespaceTests.xml b/org.springframework.context/src/test/java/org/springframework/scheduling/annotation/taskNamespaceTests.xml index 9f613201377f..2dc689973c90 100644 --- a/org.springframework.context/src/test/java/org/springframework/scheduling/annotation/taskNamespaceTests.xml +++ b/org.springframework.context/src/test/java/org/springframework/scheduling/annotation/taskNamespaceTests.xml @@ -11,12 +11,20 @@ <context:load-time-weaver aspectj-weaving="on"/> --> - <task:annotation-driven executor="executor"/> + <task:annotation-driven executor="executor" scheduler="scheduler"/> + + <task:scheduled-tasks scheduler="scheduler"> + <task:scheduled ref="target" method="test" fixed-rate="1000"/> + </task:scheduled-tasks> <bean id="executor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="threadNamePrefix" value="testExecutor"/> </bean> + <bean id="scheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler"> + <property name="threadNamePrefix" value="testScheduler"/> + </bean> + <bean id="target" class="org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessorTests$TestBean"/> </beans> diff --git a/org.springframework.context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java b/org.springframework.context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java index 52112929038b..295c282ad0d6 100644 --- a/org.springframework.context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java +++ b/org.springframework.context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,18 @@ package org.springframework.scheduling.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; +import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.scheduling.support.MethodInvokingRunnable; +import org.springframework.scheduling.support.ScheduledMethodRunnable; /** * @author Mark Fisher @@ -64,11 +63,11 @@ public void checkTarget() { Map<Runnable, Long> tasks = (Map<Runnable, Long>) new DirectFieldAccessor( this.registrar).getPropertyValue("fixedRateTasks"); Runnable runnable = tasks.keySet().iterator().next(); - assertEquals(MethodInvokingRunnable.class, runnable.getClass()); - Object targetObject = ((MethodInvokingRunnable) runnable).getTargetObject(); - String targetMethod = ((MethodInvokingRunnable) runnable).getTargetMethod(); + assertEquals(ScheduledMethodRunnable.class, runnable.getClass()); + Object targetObject = ((ScheduledMethodRunnable) runnable).getTarget(); + Method targetMethod = ((ScheduledMethodRunnable) runnable).getMethod(); assertEquals(this.testBean, targetObject); - assertEquals("test", targetMethod); + assertEquals("test", targetMethod.getName()); } @Test
406bbcc65dbfe7f43f20f9ed86fa4f09535f331d
drools
BZ-1006481 - UI support for 'extends' rule keyword- broken--
c
https://github.com/kiegroup/drools
diff --git a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java index 4421e9d5b2a..c1f16e93153 100644 --- a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java +++ b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java @@ -16,6 +16,7 @@ package org.drools.workbench.models.commons.shared.oracle; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; @@ -32,8 +33,12 @@ public interface ProjectDataModelOracle { //Fact and Field related methods String[] getFactTypes(); + Map<String,Collection<String>> getRuleNamesMap(); + List<String> getRuleNames(); + Collection<String> getRuleNamesForPackage(String packageName); + String getFactNameFromType( final String classType ); boolean isFactTypeRecognized( final String factType ); diff --git a/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java b/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java index dde4f87be37..dbf1abeb0e6 100644 --- a/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java +++ b/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; @@ -59,7 +60,7 @@ public class ProjectDataModelOracleImpl implements ProjectDataModelOracle { protected Map<String, Boolean> projectCollectionTypes = new HashMap<String, Boolean>(); // List of available rule names - private List<String> ruleNames = new ArrayList<String>(); + private Map<String, Collection<String>> ruleNames = new HashMap<String, Collection<String>>(); // List of available package names private List<String> packageNames = new ArrayList<String>(); @@ -775,15 +776,29 @@ public Map<String, Boolean> getProjectCollectionTypes() { return this.projectCollectionTypes; } - public void addRuleNames(List<String> ruleNames) { - this.ruleNames.addAll(ruleNames); + public void addRuleNames(String packageName, Collection<String> ruleNames) { + this.ruleNames.put(packageName, ruleNames); } @Override - public List<String> getRuleNames() { + public Map<String, Collection<String>> getRuleNamesMap() { return ruleNames; } + @Override + public List<String> getRuleNames() { + List<String> allTheRuleNames = new ArrayList<String>(); + for (String packageName : ruleNames.keySet()) { + allTheRuleNames.addAll(ruleNames.get(packageName)); + } + return allTheRuleNames; + } + + @Override + public Collection<String> getRuleNamesForPackage(String packageName) { + return ruleNames.get(packageName); + } + public void addPackageNames(List<String> packageNames) { this.packageNames.addAll(packageNames); }
5824fa23d60acca2edd40f1eec0c4687199f0124
camel
CAMEL-1933: Overhaul of JMX. Routes can now be- started/stopped.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@808328 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/CamelContext.java b/camel-core/src/main/java/org/apache/camel/CamelContext.java index bbf01de86716e..a3d862ec94b5f 100644 --- a/camel-core/src/main/java/org/apache/camel/CamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/CamelContext.java @@ -258,18 +258,53 @@ public interface CamelContext extends Service, RuntimeConfiguration { * * @param route the route to start * @throws Exception is thrown if the route could not be started for whatever reason + * @deprecated will be removed in Camel 2.2 */ void startRoute(RouteDefinition route) throws Exception; + /** + * Starts the given route if it has been previously stopped + * + * @param routeId the route id + * @throws Exception is thrown if the route could not be started for whatever reason + */ + void startRoute(String routeId) throws Exception; + /** * Stops the given route. It will remain in the list of route definitions return by {@link #getRouteDefinitions()} * unless you use the {@link #removeRouteDefinitions(java.util.Collection)} * * @param route the route to stop * @throws Exception is thrown if the route could not be stopped for whatever reason + * @deprecated will be removed in Camel 2.2 */ void stopRoute(RouteDefinition route) throws Exception; + /** + * Stops the given route. It will remain in the list of route definitions return by {@link #getRouteDefinitions()} + * unless you use the {@link #removeRouteDefinitions(java.util.Collection)} + * + * @param routeId the route id + * @throws Exception is thrown if the route could not be stopped for whatever reason + */ + void stopRoute(String routeId) throws Exception; + + /** + * Returns the current status of the given route + * + * @param routeId the route id + * @return the status for the route + */ + ServiceStatus getRouteStatus(String routeId); + + /** + * Returns the current status of the given route + * + * @param route the route + * @return the status for the route + * @deprecated will be removed in Camel 2.2 + */ + ServiceStatus getRouteStatus(RouteDefinition route); // Properties //----------------------------------------------------------------------- @@ -430,23 +465,6 @@ public interface CamelContext extends Service, RuntimeConfiguration { */ FactoryFinder getFactoryFinder(String path) throws NoFactoryAvailableException; - /** - * Returns the current status of the given route - * - * @param routeId the route id - * @return the status for the route - */ - ServiceStatus getRouteStatus(String routeId); - - /** - * Returns the current status of the given route - * - * @param route the route - * @return the status for the route - * @deprecated will be removed in Camel 2.2 - */ - ServiceStatus getRouteStatus(RouteDefinition route); - /** * Returns the class resolver to be used for loading/lookup of classes. * diff --git a/camel-core/src/main/java/org/apache/camel/Route.java b/camel-core/src/main/java/org/apache/camel/Route.java index 5dbaca11ccc21..8cd91a52646b1 100644 --- a/camel-core/src/main/java/org/apache/camel/Route.java +++ b/camel-core/src/main/java/org/apache/camel/Route.java @@ -53,15 +53,26 @@ public interface Route { /** * This property map is used to associate information about - * the route. Gets all tbe services for this routes + * the route. Gets all the services for this routes + * </p> + * This implementation is used for initiali * * @return the services * @throws Exception is thrown in case of error + * @deprecated will be removed in Camel 2.2 */ List<Service> getServicesForRoute() throws Exception; /** - * Returns the additional services required for this particular route + * A strategy callback allowing special initialization when services is starting. + * + * @param services the service + * @throws Exception is thrown in case of error + */ + void onStartingServices(List<Service> services) throws Exception; + + /** + * Returns the services for this particular route */ List<Service> getServices(); diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index 2acaac3bf695d..ee9478ee012bd 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -597,6 +597,13 @@ public void startRoute(RouteDefinition route) throws Exception { startRouteService(routeService); } + public synchronized void startRoute(String routeId) throws Exception { + RouteService routeService = routeServices.get(routeId); + if (routeService != null) { + routeService.start(); + } + } + public void stopRoute(RouteDefinition route) throws Exception { stopRoute(route.idOrCreate(nodeIdFactory)); } @@ -605,7 +612,7 @@ public void stopRoute(RouteDefinition route) throws Exception { * Stops the route denoted by the given RouteType id */ public synchronized void stopRoute(String key) throws Exception { - RouteService routeService = routeServices.remove(key); + RouteService routeService = routeServices.get(key); if (routeService != null) { routeService.stop(); } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java index 5294feec7aa6c..4e8ae80151316 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java @@ -86,6 +86,10 @@ public List<Service> getServicesForRoute() throws Exception { return servicesForRoute; } + public void onStartingServices(List<Service> services) throws Exception { + addServices(services); + } + public List<Service> getServices() { return services; } diff --git a/camel-core/src/main/java/org/apache/camel/impl/RouteService.java b/camel-core/src/main/java/org/apache/camel/impl/RouteService.java index 30890b41f5300..ca6434dadc665 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/RouteService.java +++ b/camel-core/src/main/java/org/apache/camel/impl/RouteService.java @@ -29,6 +29,8 @@ import org.apache.camel.spi.RouteContext; import org.apache.camel.util.EventHelper; import org.apache.camel.util.ServiceHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; /** * Represents the runtime objects for a given {@link RouteDefinition} so that it can be stopped independently @@ -38,6 +40,8 @@ */ public class RouteService extends ServiceSupport { + private static final Log LOG = LogFactory.getLog(RouteService.class); + private final DefaultCamelContext camelContext; private final RouteDefinition routeDefinition; private final List<RouteContext> routeContexts; @@ -80,12 +84,19 @@ protected void doStart() throws Exception { } for (Route route : routes) { - List<Service> services = route.getServicesForRoute(); + if (LOG.isTraceEnabled()) { + LOG.trace("Starting route: " + route); + } + + List<Service> services = route.getServices(); + + // callback that we are staring these services + route.onStartingServices(services); // gather list of services to start as we need to start child services as well List<Service> list = new ArrayList<Service>(); for (Service service : services) { - doGetServiesToStart(list, service); + doGetChildServies(list, service); } startChildService(list); @@ -94,37 +105,26 @@ protected void doStart() throws Exception { } } - /** - * Need to recursive start child services for routes - */ - private void doGetServiesToStart(List<Service> services, Service service) throws Exception { - services.add(service); - - if (service instanceof Navigate) { - Navigate<?> nav = (Navigate<?>) service; - if (nav.hasNext()) { - List<?> children = nav.next(); - for (Object child : children) { - if (child instanceof Service) { - doGetServiesToStart(services, (Service) child); - } - } - } - } - } - protected void doStop() throws Exception { for (LifecycleStrategy strategy : camelContext.getLifecycleStrategies()) { strategy.onRoutesRemove(routes); } - // do not stop child services as in doStart - // as route.getServicesForRoute() will restart - // already stopped services, so we end up starting - // stuff when we stop. - - // fire events for (Route route : routes) { + if (LOG.isTraceEnabled()) { + LOG.trace("Stopping route: " + route); + } + // getServices will not add services again + List<Service> services = route.getServices(); + + // gather list of services to stop as we need to start child services as well + List<Service> list = new ArrayList<Service>(); + for (Service service : services) { + doGetChildServies(list, service); + } + stopChildService(list); + + // fire event EventHelper.notifyRouteStopped(camelContext, route); } @@ -141,4 +141,33 @@ protected void startChildService(List<Service> services) throws Exception { } } + protected void stopChildService(List<Service> services) throws Exception { + for (Service service : services) { + for (LifecycleStrategy strategy : camelContext.getLifecycleStrategies()) { + strategy.onServiceRemove(camelContext, service); + } + ServiceHelper.stopService(service); + removeChildService(service); + } + } + + /** + * Need to recursive start child services for routes + */ + private static void doGetChildServies(List<Service> services, Service service) throws Exception { + services.add(service); + + if (service instanceof Navigate) { + Navigate<?> nav = (Navigate<?>) service; + if (nav.hasNext()) { + List<?> children = nav.next(); + for (Object child : children) { + if (child instanceof Service) { + doGetChildServies(services, (Service) child); + } + } + } + } + } + } diff --git a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementStrategy.java b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementStrategy.java index 03f139d27efd7..bd76e8eb1f8b1 100644 --- a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementStrategy.java @@ -94,28 +94,28 @@ public boolean manageProcessor(ProcessorDefinition definition) { return false; } - public void manageObject(Object o) throws Exception { + public void manageObject(Object managedObject) throws Exception { // noop } - public void manageNamedObject(Object o, Object o1) throws Exception { + public void manageNamedObject(Object managedObject, Object preferedName) throws Exception { // noop } - public <T> T getManagedObjectName(Object o, String s, Class<T> tClass) throws Exception { + public <T> T getManagedObjectName(Object managedObject, String customName, Class<T> nameType) throws Exception { // noop return null; } - public void unmanageObject(Object o) throws Exception { + public void unmanageObject(Object managedObject) throws Exception { // noop } - public void unmanageNamedObject(Object o) throws Exception { + public void unmanageNamedObject(Object name) throws Exception { // noop } - public boolean isManaged(Object o, Object o1) { + public boolean isManaged(Object managedObject, Object name) { // noop return false; } diff --git a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java index e6cd8c0b5ac12..e41f2af93a858 100644 --- a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java +++ b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java @@ -68,7 +68,7 @@ public String getEndpointUri() { return ep != null ? ep.getEndpointUri() : VALUE_UNKNOWN; } - @ManagedAttribute(description = "Route state") + @ManagedAttribute(description = "Route State") public String getState() { // must use String type to be sure remote JMX can read the attribute without requiring Camel classes. ServiceStatus status = context.getRouteStatus(route.getId()); @@ -86,11 +86,11 @@ public String getCamelId() { @ManagedOperation(description = "Start Route") public void start() throws Exception { - throw new IllegalArgumentException("Start not supported"); + context.startRoute(getRouteId()); } @ManagedOperation(description = "Stop Route") public void stop() throws Exception { - throw new IllegalArgumentException("Stop not supported"); + context.stopRoute(getRouteId()); } } diff --git a/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopAndStartTest.java b/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopAndStartTest.java new file mode 100644 index 0000000000000..0cf87bf36871e --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopAndStartTest.java @@ -0,0 +1,102 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.management; + +import java.util.Set; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.ServiceStatus; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; + +/** + * @version $Revision$ + */ +public class ManagedRouteStopAndStartTest extends ContextTestSupport { + + @Override + protected void setUp() throws Exception { + deleteDirectory("target/managed"); + super.setUp(); + } + + public void testStopAndStartRoute() throws Exception { + MBeanServer mbeanServer = context.getManagementStrategy().getManagementAgent().getMBeanServer(); + ObjectName on = getRouteObjectName(mbeanServer); + + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedBodiesReceived("Hello World"); + + template.sendBodyAndHeader("file://target/managed", "Hello World", Exchange.FILE_NAME, "hello.txt"); + + assertMockEndpointsSatisfied(); + + // should be started + String state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be started", ServiceStatus.Started.name(), state); + + // stop + mbeanServer.invoke(on, "stop", null, null); + + state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be stopped", ServiceStatus.Stopped.name(), state); + + mock.reset(); + mock.expectedBodiesReceived("Bye World"); + // wait 3 seconds while route is stopped to verify that file was not consumed + mock.setResultWaitTime(3000); + + template.sendBodyAndHeader("file://target/managed", "Bye World", Exchange.FILE_NAME, "bye.txt"); + + // route is stopped so we do not get the file + mock.assertIsNotSatisfied(); + + // prepare mock for starting route + mock.reset(); + mock.expectedBodiesReceived("Bye World"); + + // start + mbeanServer.invoke(on, "start", null, null); + + state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be started", ServiceStatus.Started.name(), state); + + // this time the file is consumed + mock.assertIsSatisfied(); + } + + private static ObjectName getRouteObjectName(MBeanServer mbeanServer) throws Exception { + Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null); + assertEquals(1, set.size()); + + return set.iterator().next(); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("file://target/managed").to("mock:result"); + } + }; + } + +} diff --git a/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopTest.java b/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopTest.java new file mode 100644 index 0000000000000..d8c91b57c4d20 --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/management/ManagedRouteStopTest.java @@ -0,0 +1,76 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.management; + +import java.util.Set; +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.apache.camel.ContextTestSupport; +import org.apache.camel.ServiceStatus; +import org.apache.camel.builder.RouteBuilder; + +/** + * @version $Revision$ + */ +public class ManagedRouteStopTest extends ContextTestSupport { + + public void testStopRoute() throws Exception { + // fire a message to get it running + getMockEndpoint("mock:result").expectedMessageCount(1); + template.sendBody("direct:start", "Hello World"); + assertMockEndpointsSatisfied(); + + MBeanServer mbeanServer = context.getManagementStrategy().getManagementAgent().getMBeanServer(); + + Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null); + assertEquals(1, set.size()); + + ObjectName on = set.iterator().next(); + + boolean registered = mbeanServer.isRegistered(on); + assertEquals("Should be registered", true, registered); + + String uri = (String) mbeanServer.getAttribute(on, "EndpointUri"); + // the route has this starting endpoint uri + assertEquals("direct://start", uri); + + // should be started + String state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be started", ServiceStatus.Started.name(), state); + + mbeanServer.invoke(on, "stop", null, null); + + registered = mbeanServer.isRegistered(on); + assertEquals("Should be registered", true, registered); + + // should be stopped, eg its removed + state = (String) mbeanServer.getAttribute(on, "State"); + assertEquals("Should be stopped", ServiceStatus.Stopped.name(), state); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("direct:start").to("log:foo").to("mock:result"); + } + }; + } + +} \ No newline at end of file diff --git a/camel-core/src/test/java/org/apache/camel/management/ManagedUnregisterCamelContextTest.java b/camel-core/src/test/java/org/apache/camel/management/ManagedUnregisterCamelContextTest.java index 3a37ac30820cb..764eb3a92ce2e 100644 --- a/camel-core/src/test/java/org/apache/camel/management/ManagedUnregisterCamelContextTest.java +++ b/camel-core/src/test/java/org/apache/camel/management/ManagedUnregisterCamelContextTest.java @@ -20,8 +20,8 @@ import javax.management.ObjectName; import org.apache.camel.CamelContext; -import org.apache.camel.TestSupport; import org.apache.camel.ServiceStatus; +import org.apache.camel.TestSupport; import org.apache.camel.impl.DefaultCamelContext; /**
2b0b6845d3c96a4c784d5c0b1b211860909d2f23
ReactiveX-RxJava
Add CompositeSubscription--- also a utility method for creating a Subscription around a Future-
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java b/rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java index 0ad92e1d06..05f804000d 100644 --- a/rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java +++ b/rxjava-core/src/main/java/rx/subscriptions/BooleanSubscription.java @@ -1,3 +1,18 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package rx.subscriptions; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/rxjava-core/src/main/java/rx/subscriptions/CompositeSubscription.java b/rxjava-core/src/main/java/rx/subscriptions/CompositeSubscription.java new file mode 100644 index 0000000000..096500217c --- /dev/null +++ b/rxjava-core/src/main/java/rx/subscriptions/CompositeSubscription.java @@ -0,0 +1,80 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package rx.subscriptions; + +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import rx.Subscription; +import rx.util.functions.Functions; + +/** + * Subscription that represents a group of Subscriptions that are unsubscribed together. + * + * @see Rx.Net equivalent CompositeDisposable at http://msdn.microsoft.com/en-us/library/system.reactive.disposables.compositedisposable(v=vs.103).aspx + */ +public class CompositeSubscription implements Subscription { + + private static final Logger logger = LoggerFactory.getLogger(Functions.class); + + /* + * The reason 'synchronized' is used on 'add' and 'unsubscribe' is because AtomicBoolean/ConcurrentLinkedQueue are both being modified so it needs to be done atomically. + * + * TODO evaluate whether use of synchronized is a performance issue here and if it's worth using an atomic state machine or other non-locking approach + */ + private AtomicBoolean unsubscribed = new AtomicBoolean(false); + private final ConcurrentLinkedQueue<Subscription> subscriptions = new ConcurrentLinkedQueue<Subscription>(); + + public CompositeSubscription(List<Subscription> subscriptions) { + this.subscriptions.addAll(subscriptions); + } + + public CompositeSubscription(Subscription... subscriptions) { + for (Subscription s : subscriptions) { + this.subscriptions.add(s); + } + } + + public boolean isUnsubscribed() { + return unsubscribed.get(); + } + + public synchronized void add(Subscription s) { + if (unsubscribed.get()) { + s.unsubscribe(); + } else { + subscriptions.add(s); + } + } + + @Override + public synchronized void unsubscribe() { + if (unsubscribed.compareAndSet(false, true)) { + for (Subscription s : subscriptions) { + try { + s.unsubscribe(); + } catch (Exception e) { + logger.error("Failed to unsubscribe.", e); + } + } + } + } + +} diff --git a/rxjava-core/src/main/java/rx/subscriptions/Subscriptions.java b/rxjava-core/src/main/java/rx/subscriptions/Subscriptions.java index 4c79ce7bfa..1db0b7a660 100644 --- a/rxjava-core/src/main/java/rx/subscriptions/Subscriptions.java +++ b/rxjava-core/src/main/java/rx/subscriptions/Subscriptions.java @@ -1,5 +1,22 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package rx.subscriptions; +import java.util.concurrent.Future; + import rx.Subscription; import rx.util.functions.Action0; import rx.util.functions.FuncN; @@ -31,6 +48,37 @@ public void unsubscribe() { }; } + /** + * A {@link Subscription} that wraps a {@link Future} and cancels it when unsubscribed. + * + * + * @param f + * {@link Future} + * @return {@link Subscription} + */ + public static Subscription create(final Future<?> f) { + return new Subscription() { + + @Override + public void unsubscribe() { + f.cancel(true); + } + + }; + } + + /** + * A {@link Subscription} that groups multiple Subscriptions together and unsubscribes from all of them together. + * + * @param subscriptions + * Subscriptions to group together + * @return {@link Subscription} + */ + + public static CompositeSubscription create(Subscription... subscriptions) { + return new CompositeSubscription(subscriptions); + } + /** * A {@link Subscription} implemented via an anonymous function (such as closures from other languages). *
5f0f55a4f14fe061e96eeca4cff60a1577cd5969
camel
Added unit test for mistyped URI--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@640963 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaComponentTest.java b/components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaComponentTest.java index 849403e991181..2dceae0b58684 100644 --- a/components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaComponentTest.java +++ b/components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaComponentTest.java @@ -40,4 +40,16 @@ public void testUnknownProtocol() { } } + public void testMistypedProtocol() { + try { + // the protocol is mistyped as a colon is missing after tcp + template.setDefaultEndpointUri("mina:tcp//localhost:8080"); + template.sendBody("mina:tcp//localhost:8080"); + fail("Should have thrown a ResolveEndpointFailedException"); + } catch (ResolveEndpointFailedException e) { + assertTrue("Should be an IAE exception", e.getCause() instanceof IllegalArgumentException); + assertEquals("Unrecognised MINA protocol: null for uri: mina:tcp//localhost:8080", e.getCause().getMessage()); + } + } + }
8ebbd1e7b964b6c81a49c7d4c2476584c6279e06
elasticsearch
Recovery Settings: Change settings (still support- old settings) and allow for more dynamic settings, closes -1303.--
p
https://github.com/elastic/elasticsearch
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/TransportIndicesStatusAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/TransportIndicesStatusAction.java index d37670caf1332..0dad125120bcf 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/TransportIndicesStatusAction.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/TransportIndicesStatusAction.java @@ -39,10 +39,10 @@ import org.elasticsearch.index.gateway.SnapshotStatus; import org.elasticsearch.index.service.InternalIndexService; import org.elasticsearch.index.shard.IndexShardState; -import org.elasticsearch.index.shard.recovery.RecoveryStatus; -import org.elasticsearch.index.shard.recovery.RecoveryTarget; import org.elasticsearch.index.shard.service.InternalIndexShard; import org.elasticsearch.indices.IndicesService; +import org.elasticsearch.indices.recovery.RecoveryStatus; +import org.elasticsearch.indices.recovery.RecoveryTarget; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/common/RateLimiter.java b/modules/elasticsearch/src/main/java/org/elasticsearch/common/RateLimiter.java new file mode 100644 index 0000000000000..64b2d31421d93 --- /dev/null +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/common/RateLimiter.java @@ -0,0 +1,82 @@ +/* + * Licensed to Elastic Search and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. Elastic Search licenses this + * file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.elasticsearch.common; + +import org.elasticsearch.ElasticSearchInterruptedException; + +/** + */ +// LUCENE MONITOR: Taken from trunk of Lucene at 06-09-11 +public class RateLimiter { + + private volatile double nsPerByte; + private volatile long lastNS; + + // TODO: we could also allow eg a sub class to dynamically + // determine the allowed rate, eg if an app wants to + // change the allowed rate over time or something + + /** + * mbPerSec is the MB/sec max IO rate + */ + public RateLimiter(double mbPerSec) { + setMaxRate(mbPerSec); + } + + public void setMaxRate(double mbPerSec) { + nsPerByte = 1000000000. / (1024 * 1024 * mbPerSec); + } + + /** + * Pauses, if necessary, to keep the instantaneous IO + * rate at or below the target. NOTE: multiple threads + * may safely use this, however the implementation is + * not perfectly thread safe but likely in practice this + * is harmless (just means in some rare cases the rate + * might exceed the target). It's best to call this + * with a biggish count, not one byte at a time. + */ + public void pause(long bytes) { + + // TODO: this is purely instantenous rate; maybe we + // should also offer decayed recent history one? + final long targetNS = lastNS = lastNS + ((long) (bytes * nsPerByte)); + long curNS = System.nanoTime(); + if (lastNS < curNS) { + lastNS = curNS; + } + + // While loop because Thread.sleep doesn't alway sleep + // enough: + while (true) { + final long pauseNS = targetNS - curNS; + if (pauseNS > 0) { + try { + Thread.sleep((int) (pauseNS / 1000000), (int) (pauseNS % 1000000)); + } catch (InterruptedException ie) { + throw new ElasticSearchInterruptedException("interrupted while rate limiting", ie); + } + curNS = System.nanoTime(); + continue; + } + break; + } + } +} diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java index d0e5de295372f..0ead6d7276ac4 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/service/InternalIndexShard.java @@ -65,12 +65,12 @@ import org.elasticsearch.index.settings.IndexSettings; import org.elasticsearch.index.settings.IndexSettingsService; import org.elasticsearch.index.shard.*; -import org.elasticsearch.index.shard.recovery.RecoveryStatus; import org.elasticsearch.index.store.Store; import org.elasticsearch.index.store.StoreStats; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.indices.IndicesLifecycle; import org.elasticsearch.indices.InternalIndicesLifecycle; +import org.elasticsearch.indices.recovery.RecoveryStatus; import org.elasticsearch.threadpool.ThreadPool; import java.io.IOException; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/indices/IndicesModule.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/IndicesModule.java index 567001710b237..8f55b4395dc69 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/indices/IndicesModule.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/IndicesModule.java @@ -24,13 +24,14 @@ import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.inject.SpawnModules; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.shard.recovery.RecoverySource; -import org.elasticsearch.index.shard.recovery.RecoveryTarget; import org.elasticsearch.indices.analysis.IndicesAnalysisModule; import org.elasticsearch.indices.cache.filter.IndicesNodeFilterCache; import org.elasticsearch.indices.cluster.IndicesClusterStateService; import org.elasticsearch.indices.memory.IndexingMemoryBufferController; import org.elasticsearch.indices.query.IndicesQueriesModule; +import org.elasticsearch.indices.recovery.RecoverySettings; +import org.elasticsearch.indices.recovery.RecoverySource; +import org.elasticsearch.indices.recovery.RecoveryTarget; import org.elasticsearch.indices.store.TransportNodesListShardStoreMetaData; /** @@ -53,6 +54,7 @@ public IndicesModule(Settings settings) { bind(IndicesService.class).to(InternalIndicesService.class).asEagerSingleton(); + bind(RecoverySettings.class).asEagerSingleton(); bind(RecoveryTarget.class).asEagerSingleton(); bind(RecoverySource.class).asEagerSingleton(); diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/indices/InternalIndicesService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/InternalIndicesService.java index a98f130f0c31e..1ac25b53553e5 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/indices/InternalIndicesService.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/InternalIndicesService.java @@ -75,6 +75,7 @@ import org.elasticsearch.index.store.IndexStoreModule; import org.elasticsearch.index.store.StoreStats; import org.elasticsearch.indices.analysis.IndicesAnalysisService; +import org.elasticsearch.indices.recovery.RecoverySettings; import org.elasticsearch.indices.store.IndicesStore; import org.elasticsearch.plugins.IndexPluginsModule; import org.elasticsearch.plugins.PluginsService; @@ -168,6 +169,7 @@ public class InternalIndicesService extends AbstractLifecycleComponent<IndicesSe } @Override protected void doClose() throws ElasticSearchException { + injector.getInstance(RecoverySettings.class).close(); indicesStore.close(); indicesAnalysisService.close(); } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java index 967d0420adb54..0d350ad23c565 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java @@ -61,13 +61,12 @@ import org.elasticsearch.index.settings.IndexSettingsService; import org.elasticsearch.index.shard.IndexShardState; import org.elasticsearch.index.shard.ShardId; -import org.elasticsearch.index.shard.recovery.RecoveryFailedException; -import org.elasticsearch.index.shard.recovery.RecoverySource; -import org.elasticsearch.index.shard.recovery.RecoveryTarget; -import org.elasticsearch.index.shard.recovery.StartRecoveryRequest; import org.elasticsearch.index.shard.service.IndexShard; import org.elasticsearch.index.shard.service.InternalIndexShard; import org.elasticsearch.indices.IndicesService; +import org.elasticsearch.indices.recovery.RecoveryFailedException; +import org.elasticsearch.indices.recovery.RecoveryTarget; +import org.elasticsearch.indices.recovery.StartRecoveryRequest; import org.elasticsearch.threadpool.ThreadPool; import java.util.List; @@ -88,8 +87,6 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent<Indic private final ThreadPool threadPool; - private final RecoverySource recoverySource; - private final RecoveryTarget recoveryTarget; private final ShardStateAction shardStateAction; @@ -113,7 +110,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent<Indic private final FailedEngineHandler failedEngineHandler = new FailedEngineHandler(); @Inject public IndicesClusterStateService(Settings settings, IndicesService indicesService, ClusterService clusterService, - ThreadPool threadPool, RecoveryTarget recoveryTarget, RecoverySource recoverySource, + ThreadPool threadPool, RecoveryTarget recoveryTarget, ShardStateAction shardStateAction, NodeIndexCreatedAction nodeIndexCreatedAction, NodeIndexDeletedAction nodeIndexDeletedAction, NodeMappingCreatedAction nodeMappingCreatedAction, NodeMappingRefreshAction nodeMappingRefreshAction, @@ -122,7 +119,6 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent<Indic this.indicesService = indicesService; this.clusterService = clusterService; this.threadPool = threadPool; - this.recoverySource = recoverySource; this.recoveryTarget = recoveryTarget; this.shardStateAction = shardStateAction; this.nodeIndexCreatedAction = nodeIndexCreatedAction; @@ -141,7 +137,6 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent<Indic } @Override protected void doClose() throws ElasticSearchException { - recoverySource.close(); } @Override public void clusterChanged(final ClusterChangedEvent event) { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/IgnoreRecoveryException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/IgnoreRecoveryException.java similarity index 96% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/IgnoreRecoveryException.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/IgnoreRecoveryException.java index e1185189127f9..08c28d2f1b7da 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/IgnoreRecoveryException.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/IgnoreRecoveryException.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.ElasticSearchException; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverFilesRecoveryException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverFilesRecoveryException.java similarity index 97% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverFilesRecoveryException.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverFilesRecoveryException.java index e085befed244b..3e12af62b91d1 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverFilesRecoveryException.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverFilesRecoveryException.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.ElasticSearchWrapperException; import org.elasticsearch.common.unit.ByteSizeValue; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryCleanFilesRequest.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryCleanFilesRequest.java similarity index 97% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryCleanFilesRequest.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryCleanFilesRequest.java index 185381279a1cd..b42df9a941a62 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryCleanFilesRequest.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryCleanFilesRequest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.common.collect.Sets; import org.elasticsearch.common.io.stream.StreamInput; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFailedException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFailedException.java similarity index 96% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFailedException.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFailedException.java index f823046b5189e..08ed81b70d143 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFailedException.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFailedException.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.cluster.node.DiscoveryNode; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFileChunkRequest.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFileChunkRequest.java similarity index 98% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFileChunkRequest.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFileChunkRequest.java index 4a04ffc79304b..24f2292fd7d54 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFileChunkRequest.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFileChunkRequest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.StreamInput; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFilesInfoRequest.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFilesInfoRequest.java similarity index 98% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFilesInfoRequest.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFilesInfoRequest.java index ff899e04c9c73..7683172e51eaa 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFilesInfoRequest.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFilesInfoRequest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFinalizeRecoveryRequest.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFinalizeRecoveryRequest.java similarity index 97% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFinalizeRecoveryRequest.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFinalizeRecoveryRequest.java index 67ec3c2117987..029403e8dfba8 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFinalizeRecoveryRequest.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryFinalizeRecoveryRequest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryPrepareForTranslogOperationsRequest.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryPrepareForTranslogOperationsRequest.java similarity index 97% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryPrepareForTranslogOperationsRequest.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryPrepareForTranslogOperationsRequest.java index c784ee2bc259d..65bc7113438e8 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryPrepareForTranslogOperationsRequest.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryPrepareForTranslogOperationsRequest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryResponse.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryResponse.java similarity index 98% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryResponse.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryResponse.java index cfecc67527615..738b5052a99db 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryResponse.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryResponse.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.common.collect.Lists; import org.elasticsearch.common.io.stream.StreamInput; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java new file mode 100644 index 0000000000000..121f7a894b0de --- /dev/null +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java @@ -0,0 +1,135 @@ +/* + * Licensed to Elastic Search and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. Elastic Search licenses this + * file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.elasticsearch.indices.recovery; + +import org.elasticsearch.cluster.metadata.MetaData; +import org.elasticsearch.common.component.AbstractComponent; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.unit.ByteSizeUnit; +import org.elasticsearch.common.unit.ByteSizeValue; +import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.util.concurrent.DynamicExecutors; +import org.elasticsearch.common.util.concurrent.EsExecutors; +import org.elasticsearch.node.settings.NodeSettingsService; + +import java.util.concurrent.ThreadPoolExecutor; + +/** + */ +public class RecoverySettings extends AbstractComponent { + + static { + MetaData.addDynamicSettings("indices.recovery.file_chunk_size"); + MetaData.addDynamicSettings("indices.recovery.translog_ops"); + MetaData.addDynamicSettings("indices.recovery.translog_size"); + MetaData.addDynamicSettings("indices.recovery.compress"); + MetaData.addDynamicSettings("`"); + } + + private volatile ByteSizeValue fileChunkSize; + + private volatile boolean compress; + private volatile int translogOps; + private volatile ByteSizeValue translogSize; + + private volatile int concurrentStreams; + private final ThreadPoolExecutor concurrentStreamPool; + + @Inject public RecoverySettings(Settings settings, NodeSettingsService nodeSettingsService) { + super(settings); + + this.fileChunkSize = componentSettings.getAsBytesSize("file_chunk_size", settings.getAsBytesSize("index.shard.recovery.file_chunk_size", new ByteSizeValue(100, ByteSizeUnit.KB))); + this.translogOps = componentSettings.getAsInt("translog_ops", settings.getAsInt("index.shard.recovery.translog_ops", 1000)); + this.translogSize = componentSettings.getAsBytesSize("translog_size", settings.getAsBytesSize("index.shard.recovery.translog_size", new ByteSizeValue(100, ByteSizeUnit.KB))); + this.compress = componentSettings.getAsBoolean("compress", true); + + this.concurrentStreams = componentSettings.getAsInt("concurrent_streams", settings.getAsInt("index.shard.recovery.concurrent_streams", 5)); + this.concurrentStreamPool = (ThreadPoolExecutor) DynamicExecutors.newScalingThreadPool(1, concurrentStreams, TimeValue.timeValueSeconds(5).millis(), EsExecutors.daemonThreadFactory(settings, "[recovery_stream]")); + + logger.debug("using concurrent_streams [{}], file_chunk_size [{}], translog_size [{}], translog_ops [{}], and compress [{}]", + concurrentStreams, fileChunkSize, translogSize, translogOps, compress); + + nodeSettingsService.addListener(new ApplySettings()); + } + + public void close() { + concurrentStreamPool.shutdown(); + } + + public ByteSizeValue fileChunkSize() { + return fileChunkSize; + } + + public boolean compress() { + return compress; + } + + public int translogOps() { + return translogOps; + } + + public ByteSizeValue translogSize() { + return translogSize; + } + + public int concurrentStreams() { + return concurrentStreams; + } + + public ThreadPoolExecutor concurrentStreamPool() { + return concurrentStreamPool; + } + + class ApplySettings implements NodeSettingsService.Listener { + @Override public void onRefreshSettings(Settings settings) { + ByteSizeValue fileChunkSize = settings.getAsBytesSize("indices.recovery.file_chunk_size", RecoverySettings.this.fileChunkSize); + if (!fileChunkSize.equals(RecoverySettings.this.fileChunkSize)) { + logger.info("updating [indices.recovery.file_chunk_size] from [{}] to [{}]", RecoverySettings.this.fileChunkSize, fileChunkSize); + RecoverySettings.this.fileChunkSize = fileChunkSize; + } + + int translogOps = settings.getAsInt("indices.recovery.translog_ops", RecoverySettings.this.translogOps); + if (translogOps != RecoverySettings.this.translogOps) { + logger.info("updating [indices.recovery.translog_ops] from [{}] to [{}]", RecoverySettings.this.translogOps, translogOps); + RecoverySettings.this.translogOps = translogOps; + } + + ByteSizeValue translogSize = settings.getAsBytesSize("indices.recovery.translog_size", RecoverySettings.this.translogSize); + if (!translogSize.equals(RecoverySettings.this.translogSize)) { + logger.info("updating [indices.recovery.translog_size] from [{}] to [{}]", RecoverySettings.this.translogSize, translogSize); + RecoverySettings.this.translogSize = translogSize; + } + + boolean compress = settings.getAsBoolean("indices.recovery.compress", RecoverySettings.this.compress); + if (compress != RecoverySettings.this.compress) { + logger.info("updating [indices.recovery.compress] from [{}] to [{}]", RecoverySettings.this.compress, compress); + RecoverySettings.this.compress = compress; + } + + int concurrentStreams = settings.getAsInt("indices.recovery.concurrent_streams", RecoverySettings.this.concurrentStreams); + if (concurrentStreams != RecoverySettings.this.concurrentStreams) { + logger.info("updating [indices.recovery.concurrent_streams] from [{}] to [{}]", RecoverySettings.this.concurrentStreams, concurrentStreams); + RecoverySettings.this.concurrentStreams = concurrentStreams; + RecoverySettings.this.concurrentStreamPool.setMaximumPoolSize(concurrentStreams); + } + } + } +} diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverySource.java similarity index 83% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverySource.java index 55370faf84cff..c3d912428b2f8 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoverySource.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.apache.lucene.store.IndexInput; import org.elasticsearch.ElasticSearchException; @@ -28,11 +28,7 @@ import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; -import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.util.concurrent.DynamicExecutors; -import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.index.deletionpolicy.SnapshotIndexCommit; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.shard.IllegalIndexShardStateException; @@ -42,7 +38,6 @@ import org.elasticsearch.index.store.StoreFileMetaData; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.indices.IndicesService; -import org.elasticsearch.node.settings.NodeSettingsService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.BaseTransportRequestHandler; import org.elasticsearch.transport.TransportChannel; @@ -54,14 +49,11 @@ import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicReference; /** * The source recovery accepts recovery requests from other peer shards and start the recovery process from this * source shard to the target shard. - * - * @author kimchy (shay.banon) */ public class RecoverySource extends AbstractComponent { @@ -79,42 +71,19 @@ public static class Actions { private final IndicesService indicesService; + private final RecoverySettings recoverySettings; - private final ByteSizeValue fileChunkSize; - - private final boolean compress; - - private final int translogOps; - private final ByteSizeValue translogSize; - - private volatile int concurrentStreams; - private final ThreadPoolExecutor concurrentStreamPool; @Inject public RecoverySource(Settings settings, ThreadPool threadPool, TransportService transportService, IndicesService indicesService, - NodeSettingsService nodeSettingsService) { + RecoverySettings recoverySettings) { super(settings); this.threadPool = threadPool; this.transportService = transportService; this.indicesService = indicesService; - this.concurrentStreams = componentSettings.getAsInt("concurrent_streams", 5); - this.concurrentStreamPool = (ThreadPoolExecutor) DynamicExecutors.newScalingThreadPool(1, concurrentStreams, TimeValue.timeValueSeconds(5).millis(), EsExecutors.daemonThreadFactory(settings, "[recovery_stream]")); - - this.fileChunkSize = componentSettings.getAsBytesSize("file_chunk_size", new ByteSizeValue(100, ByteSizeUnit.KB)); - this.translogOps = componentSettings.getAsInt("translog_ops", 1000); - this.translogSize = componentSettings.getAsBytesSize("translog_size", new ByteSizeValue(100, ByteSizeUnit.KB)); - this.compress = componentSettings.getAsBoolean("compress", true); - - logger.debug("using concurrent_streams [{}], file_chunk_size [{}], translog_size [{}], translog_ops [{}], and compress [{}]", - concurrentStreams, fileChunkSize, translogSize, translogOps, compress); + this.recoverySettings = recoverySettings; transportService.registerHandler(Actions.START_RECOVERY, new StartRecoveryTransportRequestHandler()); - - nodeSettingsService.addListener(new ApplySettings()); - } - - public void close() { - concurrentStreamPool.shutdown(); } private RecoveryResponse recover(final StartRecoveryRequest request) { @@ -166,11 +135,11 @@ private RecoveryResponse recover(final StartRecoveryRequest request) { final CountDownLatch latch = new CountDownLatch(response.phase1FileNames.size()); final AtomicReference<Exception> lastException = new AtomicReference<Exception>(); for (final String name : response.phase1FileNames) { - concurrentStreamPool.execute(new Runnable() { + recoverySettings.concurrentStreamPool().execute(new Runnable() { @Override public void run() { IndexInput indexInput = null; try { - final int BUFFER_SIZE = (int) fileChunkSize.bytes(); + final int BUFFER_SIZE = (int) recoverySettings.fileChunkSize().bytes(); byte[] buf = new byte[BUFFER_SIZE]; StoreFileMetaData md = shard.store().metaData(name); indexInput = snapshot.getDirectory().openInput(name); @@ -184,7 +153,7 @@ private RecoveryResponse recover(final StartRecoveryRequest request) { long position = indexInput.getFilePointer(); indexInput.readBytes(buf, 0, toRead, false); transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.FILE_CHUNK, new RecoveryFileChunkRequest(request.shardId(), name, position, len, md.checksum(), buf, toRead), - TransportRequestOptions.options().withCompress(compress).withLowType(), VoidTransportResponseHandler.INSTANCE_SAME).txGet(); + TransportRequestOptions.options().withCompress(recoverySettings.compress()).withLowType(), VoidTransportResponseHandler.INSTANCE_SAME).txGet(); readCount += toRead; } indexInput.close(); @@ -277,9 +246,9 @@ private int sendSnapshot(Translog.Snapshot snapshot) throws ElasticSearchExcepti ops += 1; size += operation.estimateSize(); totalOperations++; - if (ops >= translogOps || size >= translogSize.bytes()) { + if (ops >= recoverySettings.translogOps() || size >= recoverySettings.translogSize().bytes()) { RecoveryTranslogOperationsRequest translogOperationsRequest = new RecoveryTranslogOperationsRequest(request.shardId(), operations); - transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.TRANSLOG_OPS, translogOperationsRequest, TransportRequestOptions.options().withCompress(compress).withLowType(), VoidTransportResponseHandler.INSTANCE_SAME).txGet(); + transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.TRANSLOG_OPS, translogOperationsRequest, TransportRequestOptions.options().withCompress(recoverySettings.compress()).withLowType(), VoidTransportResponseHandler.INSTANCE_SAME).txGet(); ops = 0; size = 0; operations.clear(); @@ -288,7 +257,7 @@ private int sendSnapshot(Translog.Snapshot snapshot) throws ElasticSearchExcepti // send the leftover if (!operations.isEmpty()) { RecoveryTranslogOperationsRequest translogOperationsRequest = new RecoveryTranslogOperationsRequest(request.shardId(), operations); - transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.TRANSLOG_OPS, translogOperationsRequest, TransportRequestOptions.options().withCompress(compress).withLowType(), VoidTransportResponseHandler.INSTANCE_SAME).txGet(); + transportService.submitRequest(request.targetNode(), RecoveryTarget.Actions.TRANSLOG_OPS, translogOperationsRequest, TransportRequestOptions.options().withCompress(recoverySettings.compress()).withLowType(), VoidTransportResponseHandler.INSTANCE_SAME).txGet(); } return totalOperations; } @@ -311,16 +280,5 @@ class StartRecoveryTransportRequestHandler extends BaseTransportRequestHandler<S channel.sendResponse(response); } } - - class ApplySettings implements NodeSettingsService.Listener { - @Override public void onRefreshSettings(Settings settings) { - int concurrentStreams = settings.getAsInt("index.shard.recovery.concurrent_streams", RecoverySource.this.concurrentStreams); - if (concurrentStreams != RecoverySource.this.concurrentStreams) { - logger.info("updating [index.shard.recovery.concurrent_streams] from [{}] to [{}]", RecoverySource.this.concurrentStreams, concurrentStreams); - RecoverySource.this.concurrentStreams = concurrentStreams; - RecoverySource.this.concurrentStreamPool.setMaximumPoolSize(concurrentStreams); - } - } - } } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryStatus.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryStatus.java similarity index 98% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryStatus.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryStatus.java index c20c2f01c3bc2..bc43f54ba5683 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryStatus.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryStatus.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.apache.lucene.store.IndexOutput; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTarget.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java similarity index 99% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTarget.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java index 0385fe9d9969b..428cc7e358448 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTarget.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.IndexOutput; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTranslogOperationsRequest.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryTranslogOperationsRequest.java similarity index 98% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTranslogOperationsRequest.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryTranslogOperationsRequest.java index cbcb1830fd657..7db2df0c4dd1e 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTranslogOperationsRequest.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/RecoveryTranslogOperationsRequest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.common.collect.Lists; import org.elasticsearch.common.io.stream.StreamInput; diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/StartRecoveryRequest.java b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/StartRecoveryRequest.java similarity index 98% rename from modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/StartRecoveryRequest.java rename to modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/StartRecoveryRequest.java index c413eacbcf2c6..bddbd0d803cf4 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/StartRecoveryRequest.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/indices/recovery/StartRecoveryRequest.java @@ -17,7 +17,7 @@ * under the License. */ -package org.elasticsearch.index.shard.recovery; +package org.elasticsearch.indices.recovery; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.collect.Maps;
89cafb31528e6d9edd1503deff0e2afa75209a44
kotlin
tuple literals--
a
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/codegen/ExpressionCodegen.java b/idea/src/org/jetbrains/jet/codegen/ExpressionCodegen.java index 6f6ef95c26d39..1e31dc1d109df 100644 --- a/idea/src/org/jetbrains/jet/codegen/ExpressionCodegen.java +++ b/idea/src/org/jetbrains/jet/codegen/ExpressionCodegen.java @@ -1788,6 +1788,29 @@ public void run() { myMap.leaveTemp(subjectType.getSize()); } + @Override + public void visitTupleExpression(JetTupleExpression expression) { + final List<JetExpression> entries = expression.getEntries(); + if (entries.size() > 22) { + throw new UnsupportedOperationException("tuple too large"); + } + final String className = "jet/Tuple" + entries.size(); + Type tupleType = Type.getObjectType(className); + StringBuilder signature = new StringBuilder("("); + for (JetExpression entry : entries) { + signature.append("Ljava/lang/Object;"); + } + signature.append(")V"); + + v.anew(tupleType); + v.dup(); + for (JetExpression entry : entries) { + gen(entry, OBJECT_TYPE); + } + v.invokespecial(className, "<init>", signature.toString()); + myStack.push(StackValue.onStack(tupleType)); + } + private void throwNewException(final String className) { v.anew(Type.getObjectType(className)); v.dup(); diff --git a/idea/tests/org/jetbrains/jet/codegen/NamespaceGenTest.java b/idea/tests/org/jetbrains/jet/codegen/NamespaceGenTest.java index 8f34886b5374e..daf24b69b3d83 100644 --- a/idea/tests/org/jetbrains/jet/codegen/NamespaceGenTest.java +++ b/idea/tests/org/jetbrains/jet/codegen/NamespaceGenTest.java @@ -1,6 +1,7 @@ package org.jetbrains.jet.codegen; import jet.IntRange; +import jet.Tuple2; import org.jetbrains.jet.parsing.JetParsingTest; import java.awt.*; @@ -435,4 +436,12 @@ public void testArrayAccessForArrayList() throws Exception { main.invoke(null, list); assertEquals("JetLanguage", list.get(0)); } + + public void testTupleLiteral() throws Exception { + loadText("fun foo() = (1, \"foo\")"); + final Method main = generateFunction(); + Tuple2 tuple2 = (Tuple2) main.invoke(null); + assertEquals(1, tuple2._1); + assertEquals("foo", tuple2._2); + } }
e5b505224b77bb2428ab9ca85e894a1ba51f8994
spring-framework
Improve exception message--Issue: SPR-12898-
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java index ba07727422de..ecec4ffda92a 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java @@ -184,7 +184,8 @@ public void afterSingletonsInstantiated() { } catch (NoUniqueBeanDefinitionException ex) { throw new IllegalStateException("No CacheResolver specified, and no unique bean of type " + - "CacheManager found. Mark one as primary or declare a specific CacheManager to use."); + "CacheManager found. Mark one as primary (or give it the name 'cacheManager') or " + + "declare a specific CacheManager to use, that serves as the default one."); } catch (NoSuchBeanDefinitionException ex) { throw new IllegalStateException("No CacheResolver specified, and no bean of type CacheManager found. " +
4b87a5ba9069e373969842dd915f3271f36631a5
hadoop
HADOOP-7657. Add support for LZ4 compression.- Contributed by Binglin Chang.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1220312 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/hadoop
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt index 281704a036577..f0e7a9a2956fd 100644 --- a/hadoop-common-project/hadoop-common/CHANGES.txt +++ b/hadoop-common-project/hadoop-common/CHANGES.txt @@ -9,6 +9,8 @@ Release 0.23.1 - Unreleased HADOOP-7777 Implement a base class for DNSToSwitchMapping implementations that can offer extra topology information. (stevel) + HADOOP-7657. Add support for LZ4 compression. (Binglin Chang via todd) + IMPROVEMENTS HADOOP-7801. HADOOP_PREFIX cannot be overriden. (Bruno Mahé via tomwhite) diff --git a/hadoop-common-project/hadoop-common/LICENSE.txt b/hadoop-common-project/hadoop-common/LICENSE.txt index 111653695f066..6ccfd0927759f 100644 --- a/hadoop-common-project/hadoop-common/LICENSE.txt +++ b/hadoop-common-project/hadoop-common/LICENSE.txt @@ -251,3 +251,34 @@ in src/main/native/src/org/apache/hadoop/util: * All rights reserved. Use of this source code is governed by a * BSD-style license that can be found in the LICENSE file. */ + + For src/main/native/src/org/apache/hadoop/io/compress/lz4/lz4.c: + +/* + LZ4 - Fast LZ compression algorithm + Copyright (C) 2011, Yann Collet. + BSD License + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ diff --git a/hadoop-common-project/hadoop-common/pom.xml b/hadoop-common-project/hadoop-common/pom.xml index 272158231b59c..53fbd01b08e7b 100644 --- a/hadoop-common-project/hadoop-common/pom.xml +++ b/hadoop-common-project/hadoop-common/pom.xml @@ -542,6 +542,8 @@ <javahClassName>org.apache.hadoop.security.JniBasedUnixGroupsNetgroupMapping</javahClassName> <javahClassName>org.apache.hadoop.io.compress.snappy.SnappyCompressor</javahClassName> <javahClassName>org.apache.hadoop.io.compress.snappy.SnappyDecompressor</javahClassName> + <javahClassName>org.apache.hadoop.io.compress.lz4.Lz4Compressor</javahClassName> + <javahClassName>org.apache.hadoop.io.compress.lz4.Lz4Decompressor</javahClassName> <javahClassName>org.apache.hadoop.util.NativeCrc32</javahClassName> </javahClassNames> <javahOutputDirectory>${project.build.directory}/native/javah</javahOutputDirectory> diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/CommonConfigurationKeys.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/CommonConfigurationKeys.java index aaac349cd2b78..7c9b25c957bd0 100644 --- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/CommonConfigurationKeys.java +++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/CommonConfigurationKeys.java @@ -93,7 +93,15 @@ public class CommonConfigurationKeys extends CommonConfigurationKeysPublic { /** Default value for IO_COMPRESSION_CODEC_SNAPPY_BUFFERSIZE_KEY */ public static final int IO_COMPRESSION_CODEC_SNAPPY_BUFFERSIZE_DEFAULT = 256 * 1024; - + + /** Internal buffer size for Snappy compressor/decompressors */ + public static final String IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_KEY = + "io.compression.codec.lz4.buffersize"; + + /** Default value for IO_COMPRESSION_CODEC_SNAPPY_BUFFERSIZE_KEY */ + public static final int IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_DEFAULT = + 256 * 1024; + /** * Service Authorization */ diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/Lz4Codec.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/Lz4Codec.java new file mode 100644 index 0000000000000..4613ebff40aea --- /dev/null +++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/Lz4Codec.java @@ -0,0 +1,217 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.io.compress; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.io.compress.lz4.Lz4Compressor; +import org.apache.hadoop.io.compress.lz4.Lz4Decompressor; +import org.apache.hadoop.fs.CommonConfigurationKeys; +import org.apache.hadoop.util.NativeCodeLoader; + +/** + * This class creates lz4 compressors/decompressors. + */ +public class Lz4Codec implements Configurable, CompressionCodec { + + static { + NativeCodeLoader.isNativeCodeLoaded(); + } + + Configuration conf; + + /** + * Set the configuration to be used by this object. + * + * @param conf the configuration object. + */ + @Override + public void setConf(Configuration conf) { + this.conf = conf; + } + + /** + * Return the configuration used by this object. + * + * @return the configuration object used by this objec. + */ + @Override + public Configuration getConf() { + return conf; + } + + /** + * Are the native lz4 libraries loaded & initialized? + * + * @return true if loaded & initialized, otherwise false + */ + public static boolean isNativeCodeLoaded() { + return NativeCodeLoader.isNativeCodeLoaded(); + } + + /** + * Create a {@link CompressionOutputStream} that will write to the given + * {@link OutputStream}. + * + * @param out the location for the final output stream + * @return a stream the user can write uncompressed data to have it compressed + * @throws IOException + */ + @Override + public CompressionOutputStream createOutputStream(OutputStream out) + throws IOException { + return createOutputStream(out, createCompressor()); + } + + /** + * Create a {@link CompressionOutputStream} that will write to the given + * {@link OutputStream} with the given {@link Compressor}. + * + * @param out the location for the final output stream + * @param compressor compressor to use + * @return a stream the user can write uncompressed data to have it compressed + * @throws IOException + */ + @Override + public CompressionOutputStream createOutputStream(OutputStream out, + Compressor compressor) + throws IOException { + if (!isNativeCodeLoaded()) { + throw new RuntimeException("native lz4 library not available"); + } + int bufferSize = conf.getInt( + CommonConfigurationKeys.IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_KEY, + CommonConfigurationKeys.IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_DEFAULT); + + int compressionOverhead = Math.max((int)(bufferSize * 0.01), 10); + + return new BlockCompressorStream(out, compressor, bufferSize, + compressionOverhead); + } + + /** + * Get the type of {@link Compressor} needed by this {@link CompressionCodec}. + * + * @return the type of compressor needed by this codec. + */ + @Override + public Class<? extends Compressor> getCompressorType() { + if (!isNativeCodeLoaded()) { + throw new RuntimeException("native lz4 library not available"); + } + + return Lz4Compressor.class; + } + + /** + * Create a new {@link Compressor} for use by this {@link CompressionCodec}. + * + * @return a new compressor for use by this codec + */ + @Override + public Compressor createCompressor() { + if (!isNativeCodeLoaded()) { + throw new RuntimeException("native lz4 library not available"); + } + int bufferSize = conf.getInt( + CommonConfigurationKeys.IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_KEY, + CommonConfigurationKeys.IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_DEFAULT); + return new Lz4Compressor(bufferSize); + } + + /** + * Create a {@link CompressionInputStream} that will read from the given + * input stream. + * + * @param in the stream to read compressed bytes from + * @return a stream to read uncompressed bytes from + * @throws IOException + */ + @Override + public CompressionInputStream createInputStream(InputStream in) + throws IOException { + return createInputStream(in, createDecompressor()); + } + + /** + * Create a {@link CompressionInputStream} that will read from the given + * {@link InputStream} with the given {@link Decompressor}. + * + * @param in the stream to read compressed bytes from + * @param decompressor decompressor to use + * @return a stream to read uncompressed bytes from + * @throws IOException + */ + @Override + public CompressionInputStream createInputStream(InputStream in, + Decompressor decompressor) + throws IOException { + if (!isNativeCodeLoaded()) { + throw new RuntimeException("native lz4 library not available"); + } + + return new BlockDecompressorStream(in, decompressor, conf.getInt( + CommonConfigurationKeys.IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_KEY, + CommonConfigurationKeys.IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_DEFAULT)); + } + + /** + * Get the type of {@link Decompressor} needed by this {@link CompressionCodec}. + * + * @return the type of decompressor needed by this codec. + */ + @Override + public Class<? extends Decompressor> getDecompressorType() { + if (!isNativeCodeLoaded()) { + throw new RuntimeException("native lz4 library not available"); + } + + return Lz4Decompressor.class; + } + + /** + * Create a new {@link Decompressor} for use by this {@link CompressionCodec}. + * + * @return a new decompressor for use by this codec + */ + @Override + public Decompressor createDecompressor() { + if (!isNativeCodeLoaded()) { + throw new RuntimeException("native lz4 library not available"); + } + int bufferSize = conf.getInt( + CommonConfigurationKeys.IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_KEY, + CommonConfigurationKeys.IO_COMPRESSION_CODEC_LZ4_BUFFERSIZE_DEFAULT); + return new Lz4Decompressor(bufferSize); + } + + /** + * Get the default filename extension for this kind of compression. + * + * @return <code>.lz4</code>. + */ + @Override + public String getDefaultExtension() { + return ".lz4"; + } +} diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/Lz4Compressor.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/Lz4Compressor.java new file mode 100644 index 0000000000000..63a3afb7d42c4 --- /dev/null +++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/Lz4Compressor.java @@ -0,0 +1,299 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.io.compress.lz4; + +import java.io.IOException; +import java.nio.Buffer; +import java.nio.ByteBuffer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.io.compress.Compressor; +import org.apache.hadoop.util.NativeCodeLoader; + +/** + * A {@link Compressor} based on the lz4 compression algorithm. + * http://code.google.com/p/lz4/ + */ +public class Lz4Compressor implements Compressor { + private static final Log LOG = + LogFactory.getLog(Lz4Compressor.class.getName()); + private static final int DEFAULT_DIRECT_BUFFER_SIZE = 64 * 1024; + + // HACK - Use this as a global lock in the JNI layer + @SuppressWarnings({"unchecked", "unused"}) + private static Class clazz = Lz4Compressor.class; + + private int directBufferSize; + private Buffer compressedDirectBuf = null; + private int uncompressedDirectBufLen; + private Buffer uncompressedDirectBuf = null; + private byte[] userBuf = null; + private int userBufOff = 0, userBufLen = 0; + private boolean finish, finished; + + private long bytesRead = 0L; + private long bytesWritten = 0L; + + + static { + if (NativeCodeLoader.isNativeCodeLoaded()) { + // Initialize the native library + try { + initIDs(); + } catch (Throwable t) { + // Ignore failure to load/initialize lz4 + LOG.warn(t.toString()); + } + } else { + LOG.error("Cannot load " + Lz4Compressor.class.getName() + + " without native hadoop library!"); + } + } + + /** + * Creates a new compressor. + * + * @param directBufferSize size of the direct buffer to be used. + */ + public Lz4Compressor(int directBufferSize) { + this.directBufferSize = directBufferSize; + + uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); + compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); + compressedDirectBuf.position(directBufferSize); + } + + /** + * Creates a new compressor with the default buffer size. + */ + public Lz4Compressor() { + this(DEFAULT_DIRECT_BUFFER_SIZE); + } + + /** + * Sets input data for compression. + * This should be called whenever #needsInput() returns + * <code>true</code> indicating that more input data is required. + * + * @param b Input data + * @param off Start offset + * @param len Length + */ + @Override + public synchronized void setInput(byte[] b, int off, int len) { + if (b == null) { + throw new NullPointerException(); + } + if (off < 0 || len < 0 || off > b.length - len) { + throw new ArrayIndexOutOfBoundsException(); + } + finished = false; + + if (len > uncompressedDirectBuf.remaining()) { + // save data; now !needsInput + this.userBuf = b; + this.userBufOff = off; + this.userBufLen = len; + } else { + ((ByteBuffer) uncompressedDirectBuf).put(b, off, len); + uncompressedDirectBufLen = uncompressedDirectBuf.position(); + } + + bytesRead += len; + } + + /** + * If a write would exceed the capacity of the direct buffers, it is set + * aside to be loaded by this function while the compressed data are + * consumed. + */ + synchronized void setInputFromSavedData() { + if (0 >= userBufLen) { + return; + } + finished = false; + + uncompressedDirectBufLen = Math.min(userBufLen, directBufferSize); + ((ByteBuffer) uncompressedDirectBuf).put(userBuf, userBufOff, + uncompressedDirectBufLen); + + // Note how much data is being fed to lz4 + userBufOff += uncompressedDirectBufLen; + userBufLen -= uncompressedDirectBufLen; + } + + /** + * Does nothing. + */ + @Override + public synchronized void setDictionary(byte[] b, int off, int len) { + // do nothing + } + + /** + * Returns true if the input data buffer is empty and + * #setInput() should be called to provide more input. + * + * @return <code>true</code> if the input data buffer is empty and + * #setInput() should be called in order to provide more input. + */ + @Override + public synchronized boolean needsInput() { + return !(compressedDirectBuf.remaining() > 0 + || uncompressedDirectBuf.remaining() == 0 || userBufLen > 0); + } + + /** + * When called, indicates that compression should end + * with the current contents of the input buffer. + */ + @Override + public synchronized void finish() { + finish = true; + } + + /** + * Returns true if the end of the compressed + * data output stream has been reached. + * + * @return <code>true</code> if the end of the compressed + * data output stream has been reached. + */ + @Override + public synchronized boolean finished() { + // Check if all uncompressed data has been consumed + return (finish && finished && compressedDirectBuf.remaining() == 0); + } + + /** + * Fills specified buffer with compressed data. Returns actual number + * of bytes of compressed data. A return value of 0 indicates that + * needsInput() should be called in order to determine if more input + * data is required. + * + * @param b Buffer for the compressed data + * @param off Start offset of the data + * @param len Size of the buffer + * @return The actual number of bytes of compressed data. + */ + @Override + public synchronized int compress(byte[] b, int off, int len) + throws IOException { + if (b == null) { + throw new NullPointerException(); + } + if (off < 0 || len < 0 || off > b.length - len) { + throw new ArrayIndexOutOfBoundsException(); + } + + // Check if there is compressed data + int n = compressedDirectBuf.remaining(); + if (n > 0) { + n = Math.min(n, len); + ((ByteBuffer) compressedDirectBuf).get(b, off, n); + bytesWritten += n; + return n; + } + + // Re-initialize the lz4's output direct-buffer + compressedDirectBuf.clear(); + compressedDirectBuf.limit(0); + if (0 == uncompressedDirectBuf.position()) { + // No compressed data, so we should have !needsInput or !finished + setInputFromSavedData(); + if (0 == uncompressedDirectBuf.position()) { + // Called without data; write nothing + finished = true; + return 0; + } + } + + // Compress data + n = compressBytesDirect(); + compressedDirectBuf.limit(n); + uncompressedDirectBuf.clear(); // lz4 consumes all buffer input + + // Set 'finished' if snapy has consumed all user-data + if (0 == userBufLen) { + finished = true; + } + + // Get atmost 'len' bytes + n = Math.min(n, len); + bytesWritten += n; + ((ByteBuffer) compressedDirectBuf).get(b, off, n); + + return n; + } + + /** + * Resets compressor so that a new set of input data can be processed. + */ + @Override + public synchronized void reset() { + finish = false; + finished = false; + uncompressedDirectBuf.clear(); + uncompressedDirectBufLen = 0; + compressedDirectBuf.clear(); + compressedDirectBuf.limit(0); + userBufOff = userBufLen = 0; + bytesRead = bytesWritten = 0L; + } + + /** + * Prepare the compressor to be used in a new stream with settings defined in + * the given Configuration + * + * @param conf Configuration from which new setting are fetched + */ + @Override + public synchronized void reinit(Configuration conf) { + reset(); + } + + /** + * Return number of bytes given to this compressor since last reset. + */ + @Override + public synchronized long getBytesRead() { + return bytesRead; + } + + /** + * Return number of bytes consumed by callers of compress since last reset. + */ + @Override + public synchronized long getBytesWritten() { + return bytesWritten; + } + + /** + * Closes the compressor and discards any unprocessed input. + */ + @Override + public synchronized void end() { + } + + private native static void initIDs(); + + private native int compressBytesDirect(); +} diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/Lz4Decompressor.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/Lz4Decompressor.java new file mode 100644 index 0000000000000..0cf65e5144266 --- /dev/null +++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/Lz4Decompressor.java @@ -0,0 +1,281 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.io.compress.lz4; + +import java.io.IOException; +import java.nio.Buffer; +import java.nio.ByteBuffer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.io.compress.Decompressor; +import org.apache.hadoop.util.NativeCodeLoader; + +/** + * A {@link Decompressor} based on the lz4 compression algorithm. + * http://code.google.com/p/lz4/ + */ +public class Lz4Decompressor implements Decompressor { + private static final Log LOG = + LogFactory.getLog(Lz4Compressor.class.getName()); + private static final int DEFAULT_DIRECT_BUFFER_SIZE = 64 * 1024; + + // HACK - Use this as a global lock in the JNI layer + @SuppressWarnings({"unchecked", "unused"}) + private static Class clazz = Lz4Decompressor.class; + + private int directBufferSize; + private Buffer compressedDirectBuf = null; + private int compressedDirectBufLen; + private Buffer uncompressedDirectBuf = null; + private byte[] userBuf = null; + private int userBufOff = 0, userBufLen = 0; + private boolean finished; + + static { + if (NativeCodeLoader.isNativeCodeLoaded()) { + // Initialize the native library + try { + initIDs(); + } catch (Throwable t) { + // Ignore failure to load/initialize lz4 + LOG.warn(t.toString()); + } + } else { + LOG.error("Cannot load " + Lz4Compressor.class.getName() + + " without native hadoop library!"); + } + } + + /** + * Creates a new compressor. + * + * @param directBufferSize size of the direct buffer to be used. + */ + public Lz4Decompressor(int directBufferSize) { + this.directBufferSize = directBufferSize; + + compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); + uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); + uncompressedDirectBuf.position(directBufferSize); + + } + + /** + * Creates a new decompressor with the default buffer size. + */ + public Lz4Decompressor() { + this(DEFAULT_DIRECT_BUFFER_SIZE); + } + + /** + * Sets input data for decompression. + * This should be called if and only if {@link #needsInput()} returns + * <code>true</code> indicating that more input data is required. + * (Both native and non-native versions of various Decompressors require + * that the data passed in via <code>b[]</code> remain unmodified until + * the caller is explicitly notified--via {@link #needsInput()}--that the + * buffer may be safely modified. With this requirement, an extra + * buffer-copy can be avoided.) + * + * @param b Input data + * @param off Start offset + * @param len Length + */ + @Override + public synchronized void setInput(byte[] b, int off, int len) { + if (b == null) { + throw new NullPointerException(); + } + if (off < 0 || len < 0 || off > b.length - len) { + throw new ArrayIndexOutOfBoundsException(); + } + + this.userBuf = b; + this.userBufOff = off; + this.userBufLen = len; + + setInputFromSavedData(); + + // Reinitialize lz4's output direct-buffer + uncompressedDirectBuf.limit(directBufferSize); + uncompressedDirectBuf.position(directBufferSize); + } + + /** + * If a write would exceed the capacity of the direct buffers, it is set + * aside to be loaded by this function while the compressed data are + * consumed. + */ + synchronized void setInputFromSavedData() { + compressedDirectBufLen = Math.min(userBufLen, directBufferSize); + + // Reinitialize lz4's input direct buffer + compressedDirectBuf.rewind(); + ((ByteBuffer) compressedDirectBuf).put(userBuf, userBufOff, + compressedDirectBufLen); + + // Note how much data is being fed to lz4 + userBufOff += compressedDirectBufLen; + userBufLen -= compressedDirectBufLen; + } + + /** + * Does nothing. + */ + @Override + public synchronized void setDictionary(byte[] b, int off, int len) { + // do nothing + } + + /** + * Returns true if the input data buffer is empty and + * {@link #setInput(byte[], int, int)} should be called to + * provide more input. + * + * @return <code>true</code> if the input data buffer is empty and + * {@link #setInput(byte[], int, int)} should be called in + * order to provide more input. + */ + @Override + public synchronized boolean needsInput() { + // Consume remaining compressed data? + if (uncompressedDirectBuf.remaining() > 0) { + return false; + } + + // Check if lz4 has consumed all input + if (compressedDirectBufLen <= 0) { + // Check if we have consumed all user-input + if (userBufLen <= 0) { + return true; + } else { + setInputFromSavedData(); + } + } + + return false; + } + + /** + * Returns <code>false</code>. + * + * @return <code>false</code>. + */ + @Override + public synchronized boolean needsDictionary() { + return false; + } + + /** + * Returns true if the end of the decompressed + * data output stream has been reached. + * + * @return <code>true</code> if the end of the decompressed + * data output stream has been reached. + */ + @Override + public synchronized boolean finished() { + return (finished && uncompressedDirectBuf.remaining() == 0); + } + + /** + * Fills specified buffer with uncompressed data. Returns actual number + * of bytes of uncompressed data. A return value of 0 indicates that + * {@link #needsInput()} should be called in order to determine if more + * input data is required. + * + * @param b Buffer for the compressed data + * @param off Start offset of the data + * @param len Size of the buffer + * @return The actual number of bytes of compressed data. + * @throws IOException + */ + @Override + public synchronized int decompress(byte[] b, int off, int len) + throws IOException { + if (b == null) { + throw new NullPointerException(); + } + if (off < 0 || len < 0 || off > b.length - len) { + throw new ArrayIndexOutOfBoundsException(); + } + + int n = 0; + + // Check if there is uncompressed data + n = uncompressedDirectBuf.remaining(); + if (n > 0) { + n = Math.min(n, len); + ((ByteBuffer) uncompressedDirectBuf).get(b, off, n); + return n; + } + if (compressedDirectBufLen > 0) { + // Re-initialize the lz4's output direct buffer + uncompressedDirectBuf.rewind(); + uncompressedDirectBuf.limit(directBufferSize); + + // Decompress data + n = decompressBytesDirect(); + uncompressedDirectBuf.limit(n); + + if (userBufLen <= 0) { + finished = true; + } + + // Get atmost 'len' bytes + n = Math.min(n, len); + ((ByteBuffer) uncompressedDirectBuf).get(b, off, n); + } + + return n; + } + + /** + * Returns <code>0</code>. + * + * @return <code>0</code>. + */ + @Override + public synchronized int getRemaining() { + // Never use this function in BlockDecompressorStream. + return 0; + } + + public synchronized void reset() { + finished = false; + compressedDirectBufLen = 0; + uncompressedDirectBuf.limit(directBufferSize); + uncompressedDirectBuf.position(directBufferSize); + userBufOff = userBufLen = 0; + } + + /** + * Resets decompressor and input and output buffers so that a new set of + * input data can be processed. + */ + @Override + public synchronized void end() { + // do nothing + } + + private native static void initIDs(); + + private native int decompressBytesDirect(); +} diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/package-info.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/package-info.java new file mode 100644 index 0000000000000..11827f1748628 --- /dev/null +++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/lz4/package-info.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ [email protected] [email protected] +package org.apache.hadoop.io.compress.lz4; +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; + diff --git a/hadoop-common-project/hadoop-common/src/main/native/Makefile.am b/hadoop-common-project/hadoop-common/src/main/native/Makefile.am index 3afc0b88a02e8..c4ca564c2be7b 100644 --- a/hadoop-common-project/hadoop-common/src/main/native/Makefile.am +++ b/hadoop-common-project/hadoop-common/src/main/native/Makefile.am @@ -46,6 +46,9 @@ libhadoop_la_SOURCES = src/org/apache/hadoop/io/compress/zlib/ZlibCompressor.c \ src/org/apache/hadoop/io/compress/zlib/ZlibDecompressor.c \ src/org/apache/hadoop/io/compress/snappy/SnappyCompressor.c \ src/org/apache/hadoop/io/compress/snappy/SnappyDecompressor.c \ + src/org/apache/hadoop/io/compress/lz4/lz4.c \ + src/org/apache/hadoop/io/compress/lz4/Lz4Compressor.c \ + src/org/apache/hadoop/io/compress/lz4/Lz4Decompressor.c \ src/org/apache/hadoop/security/getGroup.c \ src/org/apache/hadoop/security/JniBasedUnixGroupsMapping.c \ src/org/apache/hadoop/security/JniBasedUnixGroupsNetgroupMapping.c \ diff --git a/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/Lz4Compressor.c b/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/Lz4Compressor.c new file mode 100644 index 0000000000000..d52a4f6b2a3ef --- /dev/null +++ b/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/Lz4Compressor.c @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if defined HAVE_CONFIG_H + #include <config.h> +#endif + +#include "org_apache_hadoop.h" +#include "org_apache_hadoop_io_compress_lz4_Lz4Compressor.h" + +//**************************** +// Simple Functions +//**************************** + +extern int LZ4_compress (char* source, char* dest, int isize); + +/* +LZ4_compress() : + return : the number of bytes in compressed buffer dest + note : destination buffer must be already allocated. + To avoid any problem, size it to handle worst cases situations (input data not compressible) + Worst case size is : "inputsize + 0.4%", with "0.4%" being at least 8 bytes. + +*/ + +static jfieldID Lz4Compressor_clazz; +static jfieldID Lz4Compressor_uncompressedDirectBuf; +static jfieldID Lz4Compressor_uncompressedDirectBufLen; +static jfieldID Lz4Compressor_compressedDirectBuf; +static jfieldID Lz4Compressor_directBufferSize; + + +JNIEXPORT void JNICALL Java_org_apache_hadoop_io_compress_lz4_Lz4Compressor_initIDs +(JNIEnv *env, jclass clazz){ + + Lz4Compressor_clazz = (*env)->GetStaticFieldID(env, clazz, "clazz", + "Ljava/lang/Class;"); + Lz4Compressor_uncompressedDirectBuf = (*env)->GetFieldID(env, clazz, + "uncompressedDirectBuf", + "Ljava/nio/Buffer;"); + Lz4Compressor_uncompressedDirectBufLen = (*env)->GetFieldID(env, clazz, + "uncompressedDirectBufLen", "I"); + Lz4Compressor_compressedDirectBuf = (*env)->GetFieldID(env, clazz, + "compressedDirectBuf", + "Ljava/nio/Buffer;"); + Lz4Compressor_directBufferSize = (*env)->GetFieldID(env, clazz, + "directBufferSize", "I"); +} + +JNIEXPORT jint JNICALL Java_org_apache_hadoop_io_compress_lz4_Lz4Compressor_compressBytesDirect +(JNIEnv *env, jobject thisj){ + // Get members of Lz4Compressor + jobject clazz = (*env)->GetStaticObjectField(env, thisj, Lz4Compressor_clazz); + jobject uncompressed_direct_buf = (*env)->GetObjectField(env, thisj, Lz4Compressor_uncompressedDirectBuf); + jint uncompressed_direct_buf_len = (*env)->GetIntField(env, thisj, Lz4Compressor_uncompressedDirectBufLen); + jobject compressed_direct_buf = (*env)->GetObjectField(env, thisj, Lz4Compressor_compressedDirectBuf); + jint compressed_direct_buf_len = (*env)->GetIntField(env, thisj, Lz4Compressor_directBufferSize); + + // Get the input direct buffer + LOCK_CLASS(env, clazz, "Lz4Compressor"); + const char* uncompressed_bytes = (const char*)(*env)->GetDirectBufferAddress(env, uncompressed_direct_buf); + UNLOCK_CLASS(env, clazz, "Lz4Compressor"); + + if (uncompressed_bytes == 0) { + return (jint)0; + } + + // Get the output direct buffer + LOCK_CLASS(env, clazz, "Lz4Compressor"); + char* compressed_bytes = (char *)(*env)->GetDirectBufferAddress(env, compressed_direct_buf); + UNLOCK_CLASS(env, clazz, "Lz4Compressor"); + + if (compressed_bytes == 0) { + return (jint)0; + } + + compressed_direct_buf_len = LZ4_compress(uncompressed_bytes, compressed_bytes, uncompressed_direct_buf_len); + if (compressed_direct_buf_len < 0){ + THROW(env, "Ljava/lang/InternalError", "LZ4_compress failed"); + } + + (*env)->SetIntField(env, thisj, Lz4Compressor_uncompressedDirectBufLen, 0); + + return (jint)compressed_direct_buf_len; +} + diff --git a/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/Lz4Decompressor.c b/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/Lz4Decompressor.c new file mode 100644 index 0000000000000..547b027cc14c5 --- /dev/null +++ b/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/Lz4Decompressor.c @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if defined HAVE_CONFIG_H + #include <config.h> +#endif + +#include "org_apache_hadoop.h" +#include "org_apache_hadoop_io_compress_lz4_Lz4Decompressor.h" + +int LZ4_uncompress_unknownOutputSize (char* source, char* dest, int isize, int maxOutputSize); + +/* +LZ4_uncompress_unknownOutputSize() : + isize : is the input size, therefore the compressed size + maxOutputSize : is the size of the destination buffer (which must be already allocated) + return : the number of bytes decoded in the destination buffer (necessarily <= maxOutputSize) + If the source stream is malformed, the function will stop decoding and return a negative result, indicating the byte position of the faulty instruction + This version never writes beyond dest + maxOutputSize, and is therefore protected against malicious data packets + note : This version is a bit slower than LZ4_uncompress +*/ + + +static jfieldID Lz4Decompressor_clazz; +static jfieldID Lz4Decompressor_compressedDirectBuf; +static jfieldID Lz4Decompressor_compressedDirectBufLen; +static jfieldID Lz4Decompressor_uncompressedDirectBuf; +static jfieldID Lz4Decompressor_directBufferSize; + +JNIEXPORT void JNICALL Java_org_apache_hadoop_io_compress_lz4_Lz4Decompressor_initIDs +(JNIEnv *env, jclass clazz){ + + Lz4Decompressor_clazz = (*env)->GetStaticFieldID(env, clazz, "clazz", + "Ljava/lang/Class;"); + Lz4Decompressor_compressedDirectBuf = (*env)->GetFieldID(env,clazz, + "compressedDirectBuf", + "Ljava/nio/Buffer;"); + Lz4Decompressor_compressedDirectBufLen = (*env)->GetFieldID(env,clazz, + "compressedDirectBufLen", "I"); + Lz4Decompressor_uncompressedDirectBuf = (*env)->GetFieldID(env,clazz, + "uncompressedDirectBuf", + "Ljava/nio/Buffer;"); + Lz4Decompressor_directBufferSize = (*env)->GetFieldID(env, clazz, + "directBufferSize", "I"); +} + +JNIEXPORT jint JNICALL Java_org_apache_hadoop_io_compress_lz4_Lz4Decompressor_decompressBytesDirect +(JNIEnv *env, jobject thisj){ + // Get members of Lz4Decompressor + jobject clazz = (*env)->GetStaticObjectField(env,thisj, Lz4Decompressor_clazz); + jobject compressed_direct_buf = (*env)->GetObjectField(env,thisj, Lz4Decompressor_compressedDirectBuf); + jint compressed_direct_buf_len = (*env)->GetIntField(env,thisj, Lz4Decompressor_compressedDirectBufLen); + jobject uncompressed_direct_buf = (*env)->GetObjectField(env,thisj, Lz4Decompressor_uncompressedDirectBuf); + size_t uncompressed_direct_buf_len = (*env)->GetIntField(env, thisj, Lz4Decompressor_directBufferSize); + + // Get the input direct buffer + LOCK_CLASS(env, clazz, "Lz4Decompressor"); + const char* compressed_bytes = (const char*)(*env)->GetDirectBufferAddress(env, compressed_direct_buf); + UNLOCK_CLASS(env, clazz, "Lz4Decompressor"); + + if (compressed_bytes == 0) { + return (jint)0; + } + + // Get the output direct buffer + LOCK_CLASS(env, clazz, "Lz4Decompressor"); + char* uncompressed_bytes = (char *)(*env)->GetDirectBufferAddress(env, uncompressed_direct_buf); + UNLOCK_CLASS(env, clazz, "Lz4Decompressor"); + + if (uncompressed_bytes == 0) { + return (jint)0; + } + + uncompressed_direct_buf_len = LZ4_uncompress_unknownOutputSize(compressed_bytes, uncompressed_bytes, compressed_direct_buf_len, uncompressed_direct_buf_len); + if (uncompressed_direct_buf_len < 0) { + THROW(env, "Ljava/lang/InternalError", "LZ4_uncompress_unknownOutputSize failed."); + } + + (*env)->SetIntField(env, thisj, Lz4Decompressor_compressedDirectBufLen, 0); + + return (jint)uncompressed_direct_buf_len; +} diff --git a/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/lz4.c b/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/lz4.c new file mode 100644 index 0000000000000..549bf229eca27 --- /dev/null +++ b/hadoop-common-project/hadoop-common/src/main/native/src/org/apache/hadoop/io/compress/lz4/lz4.c @@ -0,0 +1,646 @@ +/* + LZ4 - Fast LZ compression algorithm + Copyright (C) 2011, Yann Collet. + BSD License + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +//************************************** +// Copy from: +// URL: http://lz4.googlecode.com/svn/trunk/lz4.c +// Repository Root: http://lz4.googlecode.com/svn +// Repository UUID: 650e7d94-2a16-8b24-b05c-7c0b3f6821cd +// Revision: 43 +// Node Kind: file +// Last Changed Author: [email protected] +// Last Changed Rev: 43 +// Last Changed Date: 2011-12-16 15:41:46 -0800 (Fri, 16 Dec 2011) +// Sha1: 9db7b2c57698c528d79572e6bce2e7dc33fa5998 +//************************************** + +//************************************** +// Compilation Directives +//************************************** +#if __STDC_VERSION__ >= 199901L + /* "restrict" is a known keyword */ +#else +#define restrict // Disable restrict +#endif + + +//************************************** +// Includes +//************************************** +#include <stdlib.h> // for malloc +#include <string.h> // for memset +#include "lz4.h" + + +//************************************** +// Performance parameter +//************************************** +// Increasing this value improves compression ratio +// Lowering this value reduces memory usage +// Lowering may also improve speed, typically on reaching cache size limits (L1 32KB for Intel, 64KB for AMD) +// Memory usage formula for 32 bits systems : N->2^(N+2) Bytes (examples : 17 -> 512KB ; 12 -> 16KB) +#define HASH_LOG 12 + + +//************************************** +// Basic Types +//************************************** +#if defined(_MSC_VER) // Visual Studio does not support 'stdint' natively +#define BYTE unsigned __int8 +#define U16 unsigned __int16 +#define U32 unsigned __int32 +#define S32 __int32 +#else +#include <stdint.h> +#define BYTE uint8_t +#define U16 uint16_t +#define U32 uint32_t +#define S32 int32_t +#endif + + +//************************************** +// Constants +//************************************** +#define MINMATCH 4 +#define SKIPSTRENGTH 6 +#define STACKLIMIT 13 +#define HEAPMODE (HASH_LOG>STACKLIMIT) // Defines if memory is allocated into the stack (local variable), or into the heap (malloc()). +#define COPYTOKEN 4 +#define COPYLENGTH 8 +#define LASTLITERALS 5 +#define MFLIMIT (COPYLENGTH+MINMATCH) +#define MINLENGTH (MFLIMIT+1) + +#define MAXD_LOG 16 +#define MAX_DISTANCE ((1 << MAXD_LOG) - 1) + +#define HASHTABLESIZE (1 << HASH_LOG) +#define HASH_MASK (HASHTABLESIZE - 1) + +#define ML_BITS 4 +#define ML_MASK ((1U<<ML_BITS)-1) +#define RUN_BITS (8-ML_BITS) +#define RUN_MASK ((1U<<RUN_BITS)-1) + + +//************************************** +// Local structures +//************************************** +struct refTables +{ + const BYTE* hashTable[HASHTABLESIZE]; +}; + +#ifdef __GNUC__ +# define _PACKED __attribute__ ((packed)) +#else +# define _PACKED +#endif + +typedef struct _U32_S +{ + U32 v; +} _PACKED U32_S; + +typedef struct _U16_S +{ + U16 v; +} _PACKED U16_S; + +#define A32(x) (((U32_S *)(x))->v) +#define A16(x) (((U16_S *)(x))->v) + + +//************************************** +// Macros +//************************************** +#define LZ4_HASH_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG)) +#define LZ4_HASH_VALUE(p) LZ4_HASH_FUNCTION(A32(p)) +#define LZ4_COPYPACKET(s,d) A32(d) = A32(s); d+=4; s+=4; A32(d) = A32(s); d+=4; s+=4; +#define LZ4_WILDCOPY(s,d,e) do { LZ4_COPYPACKET(s,d) } while (d<e); +#define LZ4_BLINDCOPY(s,d,l) { BYTE* e=d+l; LZ4_WILDCOPY(s,d,e); d=e; } + + + +//**************************** +// Compression CODE +//**************************** + +int LZ4_compressCtx(void** ctx, + char* source, + char* dest, + int isize) +{ +#if HEAPMODE + struct refTables *srt = (struct refTables *) (*ctx); + const BYTE** HashTable; +#else + const BYTE* HashTable[HASHTABLESIZE] = {0}; +#endif + + const BYTE* ip = (BYTE*) source; + const BYTE* anchor = ip; + const BYTE* const iend = ip + isize; + const BYTE* const mflimit = iend - MFLIMIT; +#define matchlimit (iend - LASTLITERALS) + + BYTE* op = (BYTE*) dest; + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + const size_t DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; +#endif + int len, length; + const int skipStrength = SKIPSTRENGTH; + U32 forwardH; + + + // Init + if (isize<MINLENGTH) goto _last_literals; +#if HEAPMODE + if (*ctx == NULL) + { + srt = (struct refTables *) malloc ( sizeof(struct refTables) ); + *ctx = (void*) srt; + } + HashTable = srt->hashTable; + memset((void*)HashTable, 0, sizeof(srt->hashTable)); +#else + (void) ctx; +#endif + + + // First Byte + HashTable[LZ4_HASH_VALUE(ip)] = ip; + ip++; forwardH = LZ4_HASH_VALUE(ip); + + // Main Loop + for ( ; ; ) + { + int findMatchAttempts = (1U << skipStrength) + 3; + const BYTE* forwardIp = ip; + const BYTE* ref; + BYTE* token; + + // Find a match + do { + U32 h = forwardH; + int step = findMatchAttempts++ >> skipStrength; + ip = forwardIp; + forwardIp = ip + step; + + if (forwardIp > mflimit) { goto _last_literals; } + + forwardH = LZ4_HASH_VALUE(forwardIp); + ref = HashTable[h]; + HashTable[h] = ip; + + } while ((ref < ip - MAX_DISTANCE) || (A32(ref) != A32(ip))); + + // Catch up + while ((ip>anchor) && (ref>(BYTE*)source) && (ip[-1]==ref[-1])) { ip--; ref--; } + + // Encode Literal length + length = ip - anchor; + token = op++; + if (length>=(int)RUN_MASK) { *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *op++ = 255; *op++ = (BYTE)len; } + else *token = (length<<ML_BITS); + + // Copy Literals + LZ4_BLINDCOPY(anchor, op, length); + + +_next_match: + // Encode Offset +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + A16(op) = (ip-ref); op+=2; +#else + { int delta = ip-ref; *op++ = delta; *op++ = delta>>8; } +#endif + + // Start Counting + ip+=MINMATCH; ref+=MINMATCH; // MinMatch verified + anchor = ip; + while (ip<matchlimit-3) + { +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + int diff = A32(ref) ^ A32(ip); + if (!diff) { ip+=4; ref+=4; continue; } + ip += DeBruijnBytePos[((U32)((diff & -diff) * 0x077CB531U)) >> 27]; +#else + if (A32(ref) == A32(ip)) { ip+=4; ref+=4; continue; } + if (A16(ref) == A16(ip)) { ip+=2; ref+=2; } + if (*ref == *ip) ip++; +#endif + goto _endCount; + } + if ((ip<(matchlimit-1)) && (A16(ref) == A16(ip))) { ip+=2; ref+=2; } + if ((ip<matchlimit) && (*ref == *ip)) ip++; +_endCount: + len = (ip - anchor); + + // Encode MatchLength + if (len>=(int)ML_MASK) { *token+=ML_MASK; len-=ML_MASK; for(; len > 509 ; len-=510) { *op++ = 255; *op++ = 255; } if (len > 254) { len-=255; *op++ = 255; } *op++ = (BYTE)len; } + else *token += len; + + // Test end of chunk + if (ip > mflimit) { anchor = ip; break; } + + // Fill table + HashTable[LZ4_HASH_VALUE(ip-2)] = ip-2; + + // Test next position + ref = HashTable[LZ4_HASH_VALUE(ip)]; + HashTable[LZ4_HASH_VALUE(ip)] = ip; + if ((ref > ip - (MAX_DISTANCE + 1)) && (A32(ref) == A32(ip))) { token = op++; *token=0; goto _next_match; } + + // Prepare next loop + anchor = ip++; + forwardH = LZ4_HASH_VALUE(ip); + } + +_last_literals: + // Encode Last Literals + { + int lastRun = iend - anchor; + if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; } + else *op++ = (lastRun<<ML_BITS); + memcpy(op, anchor, iend - anchor); + op += iend-anchor; + } + + // End + return (int) (((char*)op)-dest); +} + + + +// Note : this function is valid only if isize < LZ4_64KLIMIT +#define LZ4_64KLIMIT ((1U<<16) + (MFLIMIT-1)) +#define HASHLOG64K (HASH_LOG+1) +#define LZ4_HASH64K_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-HASHLOG64K)) +#define LZ4_HASH64K_VALUE(p) LZ4_HASH64K_FUNCTION(A32(p)) +int LZ4_compress64kCtx(void** ctx, + char* source, + char* dest, + int isize) +{ +#if HEAPMODE + struct refTables *srt = (struct refTables *) (*ctx); + U16* HashTable; +#else + U16 HashTable[HASHTABLESIZE<<1] = {0}; +#endif + + const BYTE* ip = (BYTE*) source; + const BYTE* anchor = ip; + const BYTE* const base = ip; + const BYTE* const iend = ip + isize; + const BYTE* const mflimit = iend - MFLIMIT; +#define matchlimit (iend - LASTLITERALS) + + BYTE* op = (BYTE*) dest; + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + const size_t DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; +#endif + int len, length; + const int skipStrength = SKIPSTRENGTH; + U32 forwardH; + + + // Init + if (isize<MINLENGTH) goto _last_literals; +#if HEAPMODE + if (*ctx == NULL) + { + srt = (struct refTables *) malloc ( sizeof(struct refTables) ); + *ctx = (void*) srt; + } + HashTable = (U16*)(srt->hashTable); + memset((void*)HashTable, 0, sizeof(srt->hashTable)); +#else + (void) ctx; +#endif + + + // First Byte + ip++; forwardH = LZ4_HASH64K_VALUE(ip); + + // Main Loop + for ( ; ; ) + { + int findMatchAttempts = (1U << skipStrength) + 3; + const BYTE* forwardIp = ip; + const BYTE* ref; + BYTE* token; + + // Find a match + do { + U32 h = forwardH; + int step = findMatchAttempts++ >> skipStrength; + ip = forwardIp; + forwardIp = ip + step; + + if (forwardIp > mflimit) { goto _last_literals; } + + forwardH = LZ4_HASH64K_VALUE(forwardIp); + ref = base + HashTable[h]; + HashTable[h] = ip - base; + + } while (A32(ref) != A32(ip)); + + // Catch up + while ((ip>anchor) && (ref>(BYTE*)source) && (ip[-1]==ref[-1])) { ip--; ref--; } + + // Encode Literal length + length = ip - anchor; + token = op++; + if (length>=(int)RUN_MASK) { *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *op++ = 255; *op++ = (BYTE)len; } + else *token = (length<<ML_BITS); + + // Copy Literals + LZ4_BLINDCOPY(anchor, op, length); + + +_next_match: + // Encode Offset +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + A16(op) = (ip-ref); op+=2; +#else + { int delta = ip-ref; *op++ = delta; *op++ = delta>>8; } +#endif + + // Start Counting + ip+=MINMATCH; ref+=MINMATCH; // MinMatch verified + anchor = ip; + while (ip<matchlimit-3) + { +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + int diff = A32(ref) ^ A32(ip); + if (!diff) { ip+=4; ref+=4; continue; } + ip += DeBruijnBytePos[((U32)((diff & -diff) * 0x077CB531U)) >> 27]; +#else + if (A32(ref) == A32(ip)) { ip+=4; ref+=4; continue; } + if (A16(ref) == A16(ip)) { ip+=2; ref+=2; } + if (*ref == *ip) ip++; +#endif + goto _endCount; + } + if ((ip<(matchlimit-1)) && (A16(ref) == A16(ip))) { ip+=2; ref+=2; } + if ((ip<matchlimit) && (*ref == *ip)) ip++; +_endCount: + len = (ip - anchor); + + // Encode MatchLength + if (len>=(int)ML_MASK) { *token+=ML_MASK; len-=ML_MASK; for(; len > 509 ; len-=510) { *op++ = 255; *op++ = 255; } if (len > 254) { len-=255; *op++ = 255; } *op++ = (BYTE)len; } + else *token += len; + + // Test end of chunk + if (ip > mflimit) { anchor = ip; break; } + + // Test next position + ref = base + HashTable[LZ4_HASH64K_VALUE(ip)]; + HashTable[LZ4_HASH64K_VALUE(ip)] = ip - base; + if (A32(ref) == A32(ip)) { token = op++; *token=0; goto _next_match; } + + // Prepare next loop + anchor = ip++; + forwardH = LZ4_HASH64K_VALUE(ip); + } + +_last_literals: + // Encode Last Literals + { + int lastRun = iend - anchor; + if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; } + else *op++ = (lastRun<<ML_BITS); + memcpy(op, anchor, iend - anchor); + op += iend-anchor; + } + + // End + return (int) (((char*)op)-dest); +} + + + +int LZ4_compress(char* source, + char* dest, + int isize) +{ +#if HEAPMODE + void* ctx = malloc(sizeof(struct refTables)); + int result; + if (isize < LZ4_64KLIMIT) + result = LZ4_compress64kCtx(&ctx, source, dest, isize); + else result = LZ4_compressCtx(&ctx, source, dest, isize); + free(ctx); + return result; +#else + if (isize < (int)LZ4_64KLIMIT) return LZ4_compress64kCtx(NULL, source, dest, isize); + return LZ4_compressCtx(NULL, source, dest, isize); +#endif +} + + + + +//**************************** +// Decompression CODE +//**************************** + +// Note : The decoding functions LZ4_uncompress() and LZ4_uncompress_unknownOutputSize() +// are safe against "buffer overflow" attack type +// since they will *never* write outside of the provided output buffer : +// they both check this condition *before* writing anything. +// A corrupted packet however can make them *read* within the first 64K before the output buffer. + +int LZ4_uncompress(char* source, + char* dest, + int osize) +{ + // Local Variables + const BYTE* restrict ip = (const BYTE*) source; + const BYTE* restrict ref; + + BYTE* restrict op = (BYTE*) dest; + BYTE* const oend = op + osize; + BYTE* cpy; + + BYTE token; + + U32 dec[4]={0, 3, 2, 3}; + int len, length; + + + // Main Loop + while (1) + { + // get runlength + token = *ip++; + if ((length=(token>>ML_BITS)) == RUN_MASK) { for (;(len=*ip++)==255;length+=255){} length += len; } + + // copy literals + cpy = op+length; + if (cpy>oend-COPYLENGTH) + { + if (cpy > oend) goto _output_error; + memcpy(op, ip, length); + ip += length; + break; // Necessarily EOF + } + LZ4_WILDCOPY(ip, op, cpy); ip -= (op-cpy); op = cpy; + + + // get offset +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + ref = cpy - A16(ip); ip+=2; +#else + { int delta = *ip++; delta += *ip++ << 8; ref = cpy - delta; } +#endif + + // get matchlength + if ((length=(token&ML_MASK)) == ML_MASK) { for (;*ip==255;length+=255) {ip++;} length += *ip++; } + + // copy repeated sequence + if (op-ref<COPYTOKEN) + { + *op++ = *ref++; + *op++ = *ref++; + *op++ = *ref++; + *op++ = *ref++; + ref -= dec[op-ref]; + A32(op)=A32(ref); + } else { A32(op)=A32(ref); op+=4; ref+=4; } + cpy = op + length; + if (cpy > oend-COPYLENGTH) + { + if (cpy > oend) goto _output_error; + LZ4_WILDCOPY(ref, op, (oend-COPYLENGTH)); + while(op<cpy) *op++=*ref++; + op=cpy; + if (op == oend) break; // Check EOF (should never happen, since last 5 bytes are supposed to be literals) + continue; + } + LZ4_WILDCOPY(ref, op, cpy); + op=cpy; // correction + } + + // end of decoding + return (int) (((char*)ip)-source); + + // write overflow error detected +_output_error: + return (int) (-(((char*)ip)-source)); +} + + +int LZ4_uncompress_unknownOutputSize( + char* source, + char* dest, + int isize, + int maxOutputSize) +{ + // Local Variables + const BYTE* restrict ip = (const BYTE*) source; + const BYTE* const iend = ip + isize; + const BYTE* restrict ref; + + BYTE* restrict op = (BYTE*) dest; + BYTE* const oend = op + maxOutputSize; + BYTE* cpy; + + BYTE token; + + U32 dec[4]={0, 3, 2, 3}; + int len, length; + + + // Main Loop + while (ip<iend) + { + // get runlength + token = *ip++; + if ((length=(token>>ML_BITS)) == RUN_MASK) { for (;(len=*ip++)==255;length+=255){} length += len; } + + // copy literals + cpy = op+length; + if (cpy>oend-COPYLENGTH) + { + if (cpy > oend) goto _output_error; + memcpy(op, ip, length); + op += length; + break; // Necessarily EOF + } + LZ4_WILDCOPY(ip, op, cpy); ip -= (op-cpy); op = cpy; + if (ip>=iend) break; // check EOF + + // get offset +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + ref = cpy - A16(ip); ip+=2; +#else + { int delta = *ip++; delta += *ip++ << 8; ref = cpy - delta; } +#endif + + // get matchlength + if ((length=(token&ML_MASK)) == ML_MASK) { for (;(len=*ip++)==255;length+=255){} length += len; } + + // copy repeated sequence + if (op-ref<COPYTOKEN) + { + *op++ = *ref++; + *op++ = *ref++; + *op++ = *ref++; + *op++ = *ref++; + ref -= dec[op-ref]; + A32(op)=A32(ref); + } else { A32(op)=A32(ref); op+=4; ref+=4; } + cpy = op + length; + if (cpy>oend-COPYLENGTH) + { + if (cpy > oend) goto _output_error; + LZ4_WILDCOPY(ref, op, (oend-COPYLENGTH)); + while(op<cpy) *op++=*ref++; + op=cpy; + if (op == oend) break; // Check EOF (should never happen, since last 5 bytes are supposed to be literals) + continue; + } + LZ4_WILDCOPY(ref, op, cpy); + op=cpy; // correction + } + + // end of decoding + return (int) (((char*)op)-dest); + + // write overflow error detected +_output_error: + return (int) (-(((char*)ip)-source)); +} + diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/TestCodec.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/TestCodec.java index d1783f28aeac5..119fb3c14e49b 100644 --- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/TestCodec.java +++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/TestCodec.java @@ -60,6 +60,7 @@ import org.apache.hadoop.io.compress.zlib.ZlibCompressor.CompressionStrategy; import org.apache.hadoop.io.compress.zlib.ZlibFactory; import org.apache.hadoop.util.LineReader; +import org.apache.hadoop.util.NativeCodeLoader; import org.apache.hadoop.util.ReflectionUtils; import org.apache.commons.codec.binary.Base64; @@ -108,6 +109,18 @@ public void testSnappyCodec() throws IOException { } } } + + @Test + public void testLz4Codec() throws IOException { + if (NativeCodeLoader.isNativeCodeLoaded()) { + if (Lz4Codec.isNativeCodeLoaded()) { + codecTest(conf, seed, 0, "org.apache.hadoop.io.compress.Lz4Codec"); + codecTest(conf, seed, count, "org.apache.hadoop.io.compress.Lz4Codec"); + } else { + Assert.fail("Native hadoop library available but lz4 not"); + } + } + } @Test public void testDeflateCodec() throws IOException {
ad5306f24ccb42ced48a95419850f41d662fc5ac
hadoop
HADOOP-6906. FileContext copy() utility doesn't- work with recursive copying of directories. (vinod k v via mahadev)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@987374 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index 29261198d9086..4ca817d7b59a5 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -205,6 +205,9 @@ Trunk (unreleased changes) HADOOP-6482. GenericOptionsParser constructor that takes Options and String[] ignores options. (Eli Collins via jghoman) + HADOOP-6906. FileContext copy() utility doesn't work with recursive + copying of directories. (vinod k v via mahadev) + Release 0.21.0 - Unreleased INCOMPATIBLE CHANGES diff --git a/src/java/org/apache/hadoop/fs/ChecksumFs.java b/src/java/org/apache/hadoop/fs/ChecksumFs.java index cc5123af56058..89f386611cf92 100644 --- a/src/java/org/apache/hadoop/fs/ChecksumFs.java +++ b/src/java/org/apache/hadoop/fs/ChecksumFs.java @@ -20,6 +20,7 @@ import java.io.*; import java.net.URISyntaxException; +import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; @@ -478,4 +479,19 @@ public boolean reportChecksumFailure(Path f, FSDataInputStream in, long inPos, FSDataInputStream sums, long sumsPos) { return false; } + + @Override + protected FileStatus[] listStatus(Path f) throws IOException, + UnresolvedLinkException { + ArrayList<FileStatus> results = new ArrayList<FileStatus>(); + FileStatus[] listing = getMyFs().listStatus(f); + if (listing != null) { + for (int i = 0; i < listing.length; i++) { + if (!isChecksumFile(listing[i].getPath())) { + results.add(listing[i]); + } + } + } + return results.toArray(new FileStatus[results.size()]); + } } diff --git a/src/java/org/apache/hadoop/fs/FileContext.java b/src/java/org/apache/hadoop/fs/FileContext.java index efc1d8a2d2a7f..01765743f8c05 100644 --- a/src/java/org/apache/hadoop/fs/FileContext.java +++ b/src/java/org/apache/hadoop/fs/FileContext.java @@ -2017,8 +2017,8 @@ public boolean copy(final Path src, final Path dst, boolean deleteSource, mkdir(qDst, FsPermission.getDefault(), true); FileStatus[] contents = listStatus(qSrc); for (FileStatus content : contents) { - copy(content.getPath(), new Path(qDst, content.getPath()), - deleteSource, overwrite); + copy(makeQualified(content.getPath()), makeQualified(new Path(qDst, + content.getPath().getName())), deleteSource, overwrite); } } else { InputStream in=null; @@ -2062,7 +2062,8 @@ private void checkDest(String srcName, Path dst, boolean overwrite) // Recurse to check if dst/srcName exists. checkDest(null, new Path(dst, srcName), overwrite); } else if (!overwrite) { - throw new IOException("Target " + dst + " already exists"); + throw new IOException("Target " + new Path(dst, srcName) + + " already exists"); } } catch (FileNotFoundException e) { // dst does not exist - OK to copy. @@ -2098,8 +2099,9 @@ private static void checkDependencies(Path qualSrc, Path qualDst) private static boolean isSameFS(Path qualPath1, Path qualPath2) { URI srcUri = qualPath1.toUri(); URI dstUri = qualPath2.toUri(); - return (srcUri.getAuthority().equals(dstUri.getAuthority()) && srcUri - .getAuthority().equals(dstUri.getAuthority())); + return (srcUri.getScheme().equals(dstUri.getScheme()) && + !(srcUri.getAuthority() != null && dstUri.getAuthority() != null && srcUri + .getAuthority().equals(dstUri.getAuthority()))); } /** @@ -2176,7 +2178,7 @@ public T resolve(final FileContext fc, Path p) throws IOException { // NB: More than one AbstractFileSystem can match a scheme, eg // "file" resolves to LocalFs but could have come by RawLocalFs. AbstractFileSystem fs = fc.getFSofPath(p); - + // Loop until all symlinks are resolved or the limit is reached for (boolean isLink = true; isLink;) { try { diff --git a/src/test/core/org/apache/hadoop/fs/FileContextUtilBase.java b/src/test/core/org/apache/hadoop/fs/FileContextUtilBase.java index 1eac238e0483b..108993385195d 100644 --- a/src/test/core/org/apache/hadoop/fs/FileContextUtilBase.java +++ b/src/test/core/org/apache/hadoop/fs/FileContextUtilBase.java @@ -17,15 +17,17 @@ */ package org.apache.hadoop.fs; +import static org.apache.hadoop.fs.FileContextTestHelper.getTestRootPath; +import static org.apache.hadoop.fs.FileContextTestHelper.readFile; +import static org.apache.hadoop.fs.FileContextTestHelper.writeFile; +import static org.junit.Assert.assertTrue; + import java.util.Arrays; import org.apache.hadoop.util.StringUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; - -import static org.apache.hadoop.fs.FileContextTestHelper.*; /** * <p> @@ -80,4 +82,27 @@ public void testFcCopy() throws Exception{ assertTrue("Copied files does not match ",Arrays.equals(ts.getBytes(), readFile(fc,file2,ts.getBytes().length))); } -} \ No newline at end of file + + @Test + public void testRecursiveFcCopy() throws Exception { + + final String ts = "some random text"; + Path dir1 = getTestRootPath(fc, "dir1"); + Path dir2 = getTestRootPath(fc, "dir2"); + + Path file1 = new Path(dir1, "file1"); + fc.mkdir(dir1, null, false); + writeFile(fc, file1, ts.getBytes()); + assertTrue(fc.util().exists(file1)); + + Path file2 = new Path(dir2, "file1"); + + fc.util().copy(dir1, dir2); + + // verify that newly copied file2 exists + assertTrue("Failed to copy file2 ", fc.util().exists(file2)); + // verify that file2 contains test string + assertTrue("Copied files does not match ",Arrays.equals(ts.getBytes(), + readFile(fc,file2,ts.getBytes().length))); + } +}
0ed50ca00c1d9abacff4f667afa3d366c9b04e01
elasticsearch
NullPointerException for invalid faceted query,- closes -1136.--
a
https://github.com/elastic/elasticsearch
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/FacetParseElement.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/FacetParseElement.java index eeb63859e77b6..36128b82efb00 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/FacetParseElement.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/FacetParseElement.java @@ -127,6 +127,10 @@ public class FacetParseElement implements SearchParseElement { facet = new NestedChildrenCollector(facet, context.filterCache().cache(NonNestedDocsFilter.INSTANCE), context.filterCache().cache(objectMapper.nestedTypeFilter())); } + if (facet == null) { + throw new SearchParseException(context, "no facet type found for facet named [" + topLevelFieldName + "]"); + } + if (facetCollectors == null) { facetCollectors = Lists.newArrayList(); }
2d15eb12204048e9c8a6530a029bbf60dbc11e7b
camel
Polish the unit test of JmsMessageBindTest--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1023715 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFGreeterRouterTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFGreeterRouterTest.java index a14125211992f..9aab540e90ed9 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFGreeterRouterTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFGreeterRouterTest.java @@ -83,6 +83,7 @@ public static void stopService() { @Test public void testInvokingServiceFromCXFClient() throws Exception { + Thread.sleep(330000); Service service = Service.create(serviceName); service.addPort(routerPortName, "http://schemas.xmlsoap.org/soap/", "http://localhost:9003/CamelContext/RouterPort"); diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/bind/JmsMessageBindTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/bind/JmsMessageBindTest.java index a8b022323da8f..aabb5e7311a22 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/bind/JmsMessageBindTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/bind/JmsMessageBindTest.java @@ -16,8 +16,10 @@ */ package org.apache.camel.component.jms.bind; +import java.util.HashMap; import java.util.Map; +import org.apache.camel.component.jms.JmsBinding; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelSpringTestSupport; import org.junit.Test; @@ -32,8 +34,13 @@ public class JmsMessageBindTest extends CamelSpringTestSupport { public void testSendAMessageToBean() throws Exception { MockEndpoint endpoint = getMockEndpoint("mock:result"); endpoint.expectedBodiesReceived("Completed"); + + Map<String, Object> headers = new HashMap<String, Object>(); + headers.put("foo", "bar"); + // this header should not be sent as its value cannot be serialized + headers.put("binding", new JmsBinding()); - template.sendBodyAndHeader("activemq:Test.BindingQueue", "SomeBody", "foo", "bar"); + template.sendBodyAndHeaders("activemq:Test.BindingQueue", "SomeBody", headers); // lets wait for the method to be invoked assertMockEndpointsSatisfied(); @@ -42,9 +49,11 @@ public void testSendAMessageToBean() throws Exception { MyBean bean = getMandatoryBean(MyBean.class, "myBean"); assertEquals("body", "SomeBody", bean.getBody()); - Map headers = bean.getHeaders(); - assertNotNull("No headers!", headers); - assertEquals("foo header", "bar", headers.get("foo")); + Map beanHeaders = bean.getHeaders(); + assertNotNull("No headers!", beanHeaders); + + assertEquals("foo header", "bar", beanHeaders.get("foo")); + assertNull("Should get a null value", beanHeaders.get("binding")); } @Override
5d8fac86d749c9ea98eb7eda58655fe5fa3616d0
spring-framework
Add timeout async request handling to OSIV- components--This change adds async web request timeout handling to OSIV filters-and interceptors to ensure the session or entity manager is released.--Issue: SPR-10874-
c
https://github.com/spring-projects/spring-framework
diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/AsyncRequestInterceptor.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/AsyncRequestInterceptor.java new file mode 100644 index 000000000000..38879158544a --- /dev/null +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/AsyncRequestInterceptor.java @@ -0,0 +1,109 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.orm.hibernate4.support; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.SessionFactory; +import org.springframework.orm.hibernate4.SessionFactoryUtils; +import org.springframework.orm.hibernate4.SessionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; + +import java.util.concurrent.Callable; + +/** + * An interceptor with asynchronous web requests used in OpenSessionInViewFilter and + * OpenSessionInViewInterceptor. + * + * Ensures the following: + * 1) The session is bound/unbound when "callable processing" is started + * 2) The session is closed if an async request times out + * + * @author Rossen Stoyanchev + * @since 3.2.5 + */ +public class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter + implements DeferredResultProcessingInterceptor { + + private static Log logger = LogFactory.getLog(AsyncRequestInterceptor.class); + + private final SessionFactory sessionFactory; + + private final SessionHolder sessionHolder; + + private volatile boolean timeoutInProgress; + + public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { + this.sessionFactory = sessionFactory; + this.sessionHolder = sessionHolder; + } + + @Override + public <T> void preProcess(NativeWebRequest request, Callable<T> task) { + bindSession(); + } + + public void bindSession() { + this.timeoutInProgress = false; + TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); + } + + @Override + public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.sessionFactory); + } + + @Override + public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) { + this.timeoutInProgress = true; + return RESULT_NONE; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, Callable<T> task) throws Exception { + closeAfterTimeout(); + } + + private void closeAfterTimeout() { + if (this.timeoutInProgress) { + logger.debug("Closing Hibernate Session after async request timeout"); + SessionFactoryUtils.closeSession(sessionHolder.getSession()); + } + } + + // Implementation of DeferredResultProcessingInterceptor methods + + public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) { } + public <T> void preProcess(NativeWebRequest request, DeferredResult<T> deferredResult) { } + public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferredResult, Object result) { } + + @Override + public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) { + this.timeoutInProgress = true; + return true; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) { + closeAfterTimeout(); + } +} diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java index 0045a5d3f873..6ab5668293c2 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java @@ -16,14 +16,6 @@ package org.springframework.orm.hibernate4.support; -import java.io.IOException; -import java.util.concurrent.Callable; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -33,13 +25,17 @@ import org.springframework.orm.hibernate4.SessionHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + /** * Servlet 2.3 Filter that binds a Hibernate Session to the thread for the entire * processing of the request. Intended for the "Open Session in View" pattern, @@ -143,8 +139,9 @@ protected void doFilterInternal( SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); - asyncManager.registerCallableInterceptor(key, - new SessionBindingCallableInterceptor(sessionFactory, sessionHolder)); + AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(sessionFactory, sessionHolder); + asyncManager.registerCallableInterceptor(key, interceptor); + asyncManager.registerDeferredResultInterceptor(key, interceptor); } } @@ -216,37 +213,8 @@ private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, Str if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private static class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final SessionFactory sessionFactory; - - private final SessionHolder sessionHolder; - - public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { - this.sessionFactory = sessionFactory; - this.sessionHolder = sessionHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(this.sessionFactory); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); - } - } } diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java index 4d82160eb7c5..c1c46bc24865 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java @@ -33,9 +33,7 @@ import org.springframework.web.context.request.AsyncWebRequestInterceptor; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.*; /** * Spring web request interceptor that binds a Hibernate {@code Session} to the @@ -119,8 +117,10 @@ public void preHandle(WebRequest request) throws DataAccessException { SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); - asyncManager.registerCallableInterceptor(participateAttributeName, - new SessionBindingCallableInterceptor(sessionHolder)); + AsyncRequestInterceptor asyncRequestInterceptor = + new AsyncRequestInterceptor(getSessionFactory(), sessionHolder); + asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor); + asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor); } } @@ -200,35 +200,8 @@ private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, Str if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final SessionHolder sessionHolder; - - public SessionBindingCallableInterceptor(SessionHolder sessionHolder) { - this.sessionHolder = sessionHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(getSessionFactory()); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(getSessionFactory(), this.sessionHolder); - } - } - } diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/AsyncRequestInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/AsyncRequestInterceptor.java new file mode 100644 index 000000000000..4e161d87df7b --- /dev/null +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/AsyncRequestInterceptor.java @@ -0,0 +1,110 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.orm.hibernate3.support; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.SessionFactory; +import org.springframework.orm.hibernate3.SessionFactoryUtils; +import org.springframework.orm.hibernate3.SessionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; + +import java.util.concurrent.Callable; + +/** + * An interceptor with asynchronous web requests used in OpenSessionInViewFilter and + * OpenSessionInViewInterceptor. + * + * Ensures the following: + * 1) The session is bound/unbound when "callable processing" is started + * 2) The session is closed if an async request times out + * + * @author Rossen Stoyanchev + * @since 3.2.5 + */ +class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter + implements DeferredResultProcessingInterceptor { + + private static final Log logger = LogFactory.getLog(AsyncRequestInterceptor.class); + + private final SessionFactory sessionFactory; + + private final SessionHolder sessionHolder; + + private volatile boolean timeoutInProgress; + + + public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { + this.sessionFactory = sessionFactory; + this.sessionHolder = sessionHolder; + } + + @Override + public <T> void preProcess(NativeWebRequest request, Callable<T> task) { + bindSession(); + } + + public void bindSession() { + this.timeoutInProgress = false; + TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); + } + + @Override + public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.sessionFactory); + } + + @Override + public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) { + this.timeoutInProgress = true; + return RESULT_NONE; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, Callable<T> task) throws Exception { + closeAfterTimeout(); + } + + private void closeAfterTimeout() { + if (this.timeoutInProgress) { + logger.debug("Closing Hibernate Session after async request timeout"); + SessionFactoryUtils.closeSession(sessionHolder.getSession()); + } + } + + // Implementation of DeferredResultProcessingInterceptor methods + + public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) {} + public <T> void preProcess(NativeWebRequest request, DeferredResult<T> deferredResult) {} + public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferredResult, Object result) {} + + @Override + public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) { + this.timeoutInProgress = true; + return true; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) { + closeAfterTimeout(); + } + +} diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java index 7aab7c89100a..ced44d6f5e27 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java @@ -17,7 +17,6 @@ package org.springframework.orm.hibernate3.support; import java.io.IOException; -import java.util.concurrent.Callable; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -33,10 +32,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.*; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -212,8 +208,9 @@ protected void doFilterInternal( SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); - asyncManager.registerCallableInterceptor(key, - new SessionBindingCallableInterceptor(sessionFactory, sessionHolder)); + AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(sessionFactory, sessionHolder); + asyncManager.registerCallableInterceptor(key, interceptor); + asyncManager.registerDeferredResultInterceptor(key, interceptor); } } } @@ -319,38 +316,8 @@ private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, Str if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private static class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final SessionFactory sessionFactory; - - private final SessionHolder sessionHolder; - - public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { - this.sessionFactory = sessionFactory; - this.sessionHolder = sessionHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(this.sessionFactory); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); - } - } - } diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java index 9daf211d5034..d42ce03c129d 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java @@ -29,9 +29,7 @@ import org.springframework.web.context.request.AsyncWebRequestInterceptor; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.*; /** * Spring web request interceptor that binds a Hibernate {@code Session} to the @@ -173,8 +171,10 @@ public void preHandle(WebRequest request) throws DataAccessException { SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); - asyncManager.registerCallableInterceptor(participateAttributeName, - new SessionBindingCallableInterceptor(sessionHolder)); + AsyncRequestInterceptor asyncRequestInterceptor = + new AsyncRequestInterceptor(getSessionFactory(), sessionHolder); + asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor); + asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor); } else { // deferred close mode @@ -272,34 +272,8 @@ private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, Str if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final SessionHolder sessionHolder; - - public SessionBindingCallableInterceptor(SessionHolder sessionHolder) { - this.sessionHolder = sessionHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(getSessionFactory()); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(getSessionFactory(), this.sessionHolder); - } - } } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/AsyncRequestInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/AsyncRequestInterceptor.java new file mode 100644 index 000000000000..046bd8f65014 --- /dev/null +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/AsyncRequestInterceptor.java @@ -0,0 +1,111 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.orm.jpa.support; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.orm.jpa.EntityManagerFactoryUtils; +import org.springframework.orm.jpa.EntityManagerHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; + +import javax.persistence.EntityManagerFactory; +import java.util.concurrent.Callable; + +/** + * An interceptor with asynchronous web requests used in OpenSessionInViewFilter and + * OpenSessionInViewInterceptor. + * + * Ensures the following: + * 1) The session is bound/unbound when "callable processing" is started + * 2) The session is closed if an async request times out + * + * @author Rossen Stoyanchev + * @since 3.2.5 + */ +public class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter + implements DeferredResultProcessingInterceptor { + + private static Log logger = LogFactory.getLog(AsyncRequestInterceptor.class); + + private final EntityManagerFactory emFactory; + + private final EntityManagerHolder emHolder; + + private volatile boolean timeoutInProgress; + + + public AsyncRequestInterceptor(EntityManagerFactory emFactory, EntityManagerHolder emHolder) { + this.emFactory = emFactory; + this.emHolder = emHolder; + } + + @Override + public <T> void preProcess(NativeWebRequest request, Callable<T> task) { + bindSession(); + } + + public void bindSession() { + this.timeoutInProgress = false; + TransactionSynchronizationManager.bindResource(this.emFactory, this.emHolder); + } + + @Override + public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.emFactory); + } + + @Override + public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) { + this.timeoutInProgress = true; + return RESULT_NONE; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, Callable<T> task) throws Exception { + closeAfterTimeout(); + } + + private void closeAfterTimeout() { + if (this.timeoutInProgress) { + logger.debug("Closing JPA EntityManager after async request timeout"); + EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager()); + } + } + + // Implementation of DeferredResultProcessingInterceptor methods + + public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) { } + public <T> void preProcess(NativeWebRequest request, DeferredResult<T> deferredResult) { } + public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferredResult, Object result) { } + + @Override + public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) { + this.timeoutInProgress = true; + return true; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) { + closeAfterTimeout(); + } +} + diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java index 24febab2514a..b518fe262d22 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java @@ -34,9 +34,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.*; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -166,7 +164,9 @@ protected void doFilterInternal( EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(emf, emHolder); - asyncManager.registerCallableInterceptor(key, new EntityManagerBindingCallableInterceptor(emf, emHolder)); + AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder); + asyncManager.registerCallableInterceptor(key, interceptor); + asyncManager.registerDeferredResultInterceptor(key, interceptor); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); @@ -242,38 +242,8 @@ private boolean applyEntityManagerBindingInterceptor(WebAsyncManager asyncManage if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((EntityManagerBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - /** - * Bind and unbind the {@code EntityManager} to the current thread. - */ - private static class EntityManagerBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final EntityManagerFactory emFactory; - - private final EntityManagerHolder emHolder; - - - public EntityManagerBindingCallableInterceptor(EntityManagerFactory emFactory, EntityManagerHolder emHolder) { - this.emFactory = emFactory; - this.emHolder = emHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(this.emFactory); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(this.emFactory, this.emHolder); - } - } - } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java index fdebb8c8c867..dbc88b73e381 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java @@ -93,8 +93,9 @@ public void preHandle(WebRequest request) throws DataAccessException { EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder); - asyncManager.registerCallableInterceptor(participateAttributeName, - new EntityManagerBindingCallableInterceptor(emHolder)); + AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder); + asyncManager.registerCallableInterceptor(participateAttributeName, interceptor); + asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); @@ -154,36 +155,8 @@ private boolean applyCallableInterceptor(WebAsyncManager asyncManager, String ke if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((EntityManagerBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private class EntityManagerBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final EntityManagerHolder emHolder; - - - public EntityManagerBindingCallableInterceptor(EntityManagerHolder emHolder) { - this.emHolder = emHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), this.emHolder); - } - } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java index 0777c3ae11c2..c57dbcfc1e4f 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java @@ -18,13 +18,11 @@ import java.io.IOException; import java.sql.Connection; +import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.transaction.TransactionManager; import org.hibernate.FlushMode; @@ -35,11 +33,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.mock.web.test.MockFilterConfig; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.mock.web.test.MockServletContext; -import org.springframework.mock.web.test.PassThroughFilterChain; +import org.springframework.mock.web.test.*; import org.springframework.orm.hibernate3.HibernateAccessor; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.orm.hibernate3.SessionFactoryUtils; @@ -50,9 +44,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.async.AsyncWebRequest; +import org.springframework.web.context.request.async.StandardServletAsyncWebRequest; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.StaticWebApplicationContext; +import org.springframework.web.util.NestedServletException; import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; @@ -79,6 +75,7 @@ public class OpenSessionInViewTests { public void setup() { this.sc = new MockServletContext(); this.request = new MockHttpServletRequest(sc); + this.request.setAsyncSupported(true); this.response = new MockHttpServletResponse(); this.webRequest = new ServletWebRequest(this.request); } @@ -142,12 +139,10 @@ public void testOpenSessionInViewInterceptorAsyncScenario() throws Exception { interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(sf)); - AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); - + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); - asyncManager.startCallableProcessing(new Callable<String>() { @Override public String call() throws Exception { @@ -166,13 +161,58 @@ public String call() throws Exception { interceptor.postHandle(this.webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(sf)); + verify(session, never()).close(); + interceptor.afterCompletion(this.webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(sf)); verify(session).setFlushMode(FlushMode.MANUAL); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); - verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); - verify(asyncWebRequest).startAsync(); + verify(session).close(); + } + + @Test + public void testOpenSessionInViewInterceptorAsyncTimeoutScenario() throws Exception { + + // Initial request thread + + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + + OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor(); + interceptor.setSessionFactory(sf); + + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + + interceptor.preHandle(this.webRequest); + assertTrue(TransactionSynchronizationManager.hasResource(sf)); + + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); + asyncManager.setAsyncWebRequest(asyncWebRequest); + asyncManager.startCallableProcessing(new Callable<String>() { + @Override + public String call() throws Exception { + return "anything"; + } + }); + + interceptor.afterConcurrentHandlingStarted(this.webRequest); + assertFalse(TransactionSynchronizationManager.hasResource(sf)); + verify(session, never()).close(); + + // Async request timeout + + MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext(); + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onTimeout(new AsyncEvent(asyncContext)); + } + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onComplete(new AsyncEvent(asyncContext)); + } + + verify(session).close(); } @Test @@ -376,9 +416,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } }; - AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); - given(asyncWebRequest.isAsyncStarted()).willReturn(true); - + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); @@ -393,19 +431,89 @@ public String call() throws Exception { filter.doFilter(this.request, this.response, filterChain); assertFalse(TransactionSynchronizationManager.hasResource(sf)); assertEquals(1, count.get()); - + verify(session, never()).close(); // Async dispatch after concurrent handling produces result ... + this.request.setAsyncStarted(false); assertFalse(TransactionSynchronizationManager.hasResource(sf)); filter.doFilter(this.request, this.response, filterChain); assertFalse(TransactionSynchronizationManager.hasResource(sf)); assertEquals(2, count.get()); verify(session).setFlushMode(FlushMode.MANUAL); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); - verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); - verify(asyncWebRequest).startAsync(); + verify(session).close(); + + wac.close(); + } + + @Test + public void testOpenSessionInViewFilterAsyncTimeoutScenario() throws Exception { + + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + + // Initial request during which concurrent handling starts.. + + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + + StaticWebApplicationContext wac = new StaticWebApplicationContext(); + wac.setServletContext(sc); + wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf); + wac.refresh(); + sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); + + MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter"); + final OpenSessionInViewFilter filter = new OpenSessionInViewFilter(); + filter.init(filterConfig); + + final AtomicInteger count = new AtomicInteger(0); + final AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); + final MockHttpServletRequest request = this.request; + + final FilterChain filterChain = new FilterChain() { + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) + throws NestedServletException { + + assertTrue(TransactionSynchronizationManager.hasResource(sf)); + count.incrementAndGet(); + + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); + asyncManager.setAsyncWebRequest(asyncWebRequest); + try { + asyncManager.startCallableProcessing(new Callable<String>() { + @Override + public String call() throws Exception { + return "anything"; + } + }); + } + catch (Exception e) { + throw new NestedServletException("", e); + } + } + }; + + assertFalse(TransactionSynchronizationManager.hasResource(sf)); + filter.doFilter(this.request, this.response, filterChain); + assertFalse(TransactionSynchronizationManager.hasResource(sf)); + assertEquals(1, count.get()); + verify(session, never()).close(); + + // Async request timeout ... + + MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext(); + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onTimeout(new AsyncEvent(asyncContext)); + } + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onComplete(new AsyncEvent(asyncContext)); + } + + verify(session).close(); wac.close(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java index 901448e0a6d2..5ad164e9dc36 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java @@ -21,25 +21,19 @@ import java.util.concurrent.atomic.AtomicInteger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.mock.web.test.MockFilterConfig; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.mock.web.test.MockServletContext; -import org.springframework.mock.web.test.PassThroughFilterChain; +import org.springframework.mock.web.test.*; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.async.AsyncWebRequest; +import org.springframework.web.context.request.async.StandardServletAsyncWebRequest; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.StaticWebApplicationContext; @@ -59,6 +53,12 @@ public class OpenEntityManagerInViewTests { private EntityManagerFactory factory; + private MockHttpServletRequest request; + + private MockHttpServletResponse response; + + private ServletWebRequest webRequest; + @Before public void setUp() throws Exception { @@ -66,6 +66,11 @@ public void setUp() throws Exception { manager = mock(EntityManager.class); given(factory.createEntityManager()).willReturn(manager); + + this.request = new MockHttpServletRequest(); + this.request.setAsyncSupported(true); + this.response = new MockHttpServletResponse(); + this.webRequest = new ServletWebRequest(this.request); } @After @@ -79,13 +84,13 @@ public void tearDown() throws Exception { @Test public void testOpenEntityManagerInViewInterceptor() throws Exception { OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor(); - interceptor.setEntityManagerFactory(factory); + interceptor.setEntityManagerFactory(this.factory); MockServletContext sc = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(sc); interceptor.preHandle(new ServletWebRequest(request)); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertTrue(TransactionSynchronizationManager.hasResource(this.factory)); // check that further invocations simply participate interceptor.preHandle(new ServletWebRequest(request)); @@ -120,16 +125,13 @@ public void testOpenEntityManagerInViewInterceptorAsyncScenario() throws Excepti OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor(); interceptor.setEntityManagerFactory(factory); - MockServletContext sc = new MockServletContext(); - MockHttpServletRequest request = new MockHttpServletRequest(sc); - ServletWebRequest webRequest = new ServletWebRequest(request); + given(factory.createEntityManager()).willReturn(this.manager); - interceptor.preHandle(webRequest); + interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(factory)); - AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); - - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(webRequest); + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.webRequest); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { @@ -139,17 +141,12 @@ public String call() throws Exception { } }); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); - verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); - verify(asyncWebRequest).startAsync(); - - interceptor.afterConcurrentHandlingStarted(webRequest); + interceptor.afterConcurrentHandlingStarted(this.webRequest); assertFalse(TransactionSynchronizationManager.hasResource(factory)); // Async dispatch thread - interceptor.preHandle(webRequest); + interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(factory)); asyncManager.clearConcurrentResult(); @@ -168,15 +165,57 @@ public String call() throws Exception { interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); - interceptor.postHandle(webRequest, null); + interceptor.postHandle(this.webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(factory)); - given(manager.isOpen()).willReturn(true); + given(this.manager.isOpen()).willReturn(true); - interceptor.afterCompletion(webRequest, null); + interceptor.afterCompletion(this.webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(factory)); - verify(manager).close(); + verify(this.manager).close(); + } + + @Test + public void testOpenEntityManagerInViewInterceptorAsyncTimeoutScenario() throws Exception { + + // Initial request thread + + OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor(); + interceptor.setEntityManagerFactory(factory); + + given(this.factory.createEntityManager()).willReturn(this.manager); + + interceptor.preHandle(this.webRequest); + assertTrue(TransactionSynchronizationManager.hasResource(this.factory)); + + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); + asyncManager.setAsyncWebRequest(asyncWebRequest); + asyncManager.startCallableProcessing(new Callable<String>() { + @Override + public String call() throws Exception { + return "anything"; + } + }); + + interceptor.afterConcurrentHandlingStarted(this.webRequest); + assertFalse(TransactionSynchronizationManager.hasResource(this.factory)); + + // Async request timeout + + given(this.manager.isOpen()).willReturn(true); + + MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext(); + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onTimeout(new AsyncEvent(asyncContext)); + } + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onComplete(new AsyncEvent(asyncContext)); + } + + verify(this.manager).close(); } @Test @@ -257,8 +296,6 @@ public void testOpenEntityManagerInViewFilterAsyncScenario() throws Exception { wac.getDefaultListableBeanFactory().registerSingleton("myEntityManagerFactory", factory2); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); - MockHttpServletRequest request = new MockHttpServletRequest(sc); - MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter"); MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2"); @@ -297,7 +334,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); given(asyncWebRequest.isAsyncStarted()).willReturn(true); - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { @@ -309,13 +346,12 @@ public String call() throws Exception { assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); - filter2.doFilter(request, response, filterChain3); + filter2.doFilter(this.request, this.response, filterChain3); assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); assertEquals(1, count.get()); assertEquals(1, count2.get()); assertNotNull(request.getAttribute("invoked")); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); @@ -328,13 +364,13 @@ public String call() throws Exception { assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); - filter.doFilter(request, response, filterChain3); + filter.doFilter(this.request, this.response, filterChain3); assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); assertEquals(2, count.get()); assertEquals(2, count2.get()); - verify(manager).close(); + verify(this.manager).close(); verify(manager2).close(); wac.close(); diff --git a/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java b/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java index 42409c6fe2fa..0298f7db4fe4 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java @@ -31,7 +31,8 @@ public abstract class DeferredResultProcessingInterceptorAdapter implements Defe * This implementation is empty. */ @Override - public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception { + public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) + throws Exception { } /** @@ -50,7 +51,8 @@ public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferred } /** - * This implementation returns {@code true} by default. + * This implementation returns {@code true} by default allowing other interceptors + * to be given a chance to handle the timeout. */ @Override public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception {
6cb363ffc6c515d1b9df760d31ee489b3877c4d5
restlet-framework-java
Fix issue -853--DefaultSslContextFactory would ignore enabledCipherSuites unless you also specified enabledProtocols, due to a copy-paste error.-
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/ssl/DefaultSslContextFactory.java b/modules/org.restlet/src/org/restlet/engine/ssl/DefaultSslContextFactory.java index ee444ce008..d1b7addff2 100644 --- a/modules/org.restlet/src/org/restlet/engine/ssl/DefaultSslContextFactory.java +++ b/modules/org.restlet/src/org/restlet/engine/ssl/DefaultSslContextFactory.java @@ -686,7 +686,7 @@ public void init(Series<Parameter> helperParameters) { enabledProtocols.toArray(enabledProtocolsArray); setEnabledProtocols(enabledProtocolsArray); } else { - setEnabledCipherSuites(null); + setEnabledProtocols(null); } setKeyManagerAlgorithm(helperParameters.getFirstValue(
ed8ba5dff378f6ebd3edca10994ca63976af541b
hbase
HBASE-1773 Fix broken tests (setWriteBuffer now- throws IOE)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@805236 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/src/test/org/apache/hadoop/hbase/client/TestBatchUpdate.java b/src/test/org/apache/hadoop/hbase/client/TestBatchUpdate.java index 724201f3cdcb..48277a361159 100644 --- a/src/test/org/apache/hadoop/hbase/client/TestBatchUpdate.java +++ b/src/test/org/apache/hadoop/hbase/client/TestBatchUpdate.java @@ -104,7 +104,7 @@ public void testRowsBatchUpdateBufferedOneFlush() { } } - public void testRowsBatchUpdateBufferedManyManyFlushes() { + public void testRowsBatchUpdateBufferedManyManyFlushes() throws IOException { table.setAutoFlush(false); table.setWriteBufferSize(10); ArrayList<BatchUpdate> rowsUpdate = new ArrayList<BatchUpdate>(); diff --git a/src/test/org/apache/hadoop/hbase/client/TestPut.java b/src/test/org/apache/hadoop/hbase/client/TestPut.java index 972c72e1abfb..3fb6ba5a6bbd 100644 --- a/src/test/org/apache/hadoop/hbase/client/TestPut.java +++ b/src/test/org/apache/hadoop/hbase/client/TestPut.java @@ -42,7 +42,6 @@ public class TestPut extends HBaseClusterTestCase { private static final int SMALL_LENGTH = 1; private static final int NB_BATCH_ROWS = 10; private byte [] value; - private byte [] smallValue; private HTableDescriptor desc = null; private HTable table = null; @@ -53,7 +52,6 @@ public class TestPut extends HBaseClusterTestCase { public TestPut() throws UnsupportedEncodingException { super(); value = Bytes.toBytes("abcd"); - smallValue = Bytes.toBytes("a"); } @Override @@ -164,7 +162,7 @@ public void testRowsPutBufferedOneFlush() { } } - public void testRowsPutBufferedManyManyFlushes() { + public void testRowsPutBufferedManyManyFlushes() throws IOException { table.setAutoFlush(false); table.setWriteBufferSize(10); ArrayList<Put> rowsUpdate = new ArrayList<Put>();
eff73c243eabb0f63129eed9ad3ccf6be36c56b4
drools
[DROOLS-94] fix BaseObjectClassFieldReader when- reading numeric values--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java index 2bc60ce137a..ff2ed967dc4 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java @@ -1589,9 +1589,9 @@ public void testJitCastOfPrimitiveType() { // DROOLS-79 String str = "rule R when\n" + - " Number(longValue < (Long)7)\n" + - "then\n" + - "end\n"; + " Number(longValue < (Long)7)\n" + + "then\n" + + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); @@ -1599,4 +1599,35 @@ public void testJitCastOfPrimitiveType() { ksession.insert(new Long(6)); assertEquals(1, ksession.fireAllRules()); } + + @Test + public void testMatchIntegers() { + // DROOLS-94 + String str = + "global java.util.List list; \n" + + "rule R when\n" + + " $i : Integer( this == 1 )\n" + + "then\n" + + " list.add( $i );\n" + + "end\n" + + "rule S when\n" + + " $i : Integer( this == 2 )\n" + + "then\n" + + " list.add( $i );\n" + + "end\n" + + "rule T when\n" + + " $i : Integer( this == 3 )\n" + + "then\n" + + " list.add( $i );\n" + + "end\n"; + + KnowledgeBase kbase = loadKnowledgeBaseFromString(str); + StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); + + List list = new ArrayList(); + ksession.setGlobal( "list", list ); + + ksession.insert( new Integer( 1 ) ); + ksession.fireAllRules(); + } } diff --git a/drools-core/src/main/java/org/drools/core/base/extractors/BaseObjectClassFieldReader.java b/drools-core/src/main/java/org/drools/core/base/extractors/BaseObjectClassFieldReader.java index 50cfb1e8ffe..2effc8528b5 100755 --- a/drools-core/src/main/java/org/drools/core/base/extractors/BaseObjectClassFieldReader.java +++ b/drools-core/src/main/java/org/drools/core/base/extractors/BaseObjectClassFieldReader.java @@ -85,6 +85,8 @@ public double getDoubleValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).doubleValue(); } throw new RuntimeDroolsException( "Conversion to double not supported from " + getExtractToClass().getName() ); @@ -97,6 +99,8 @@ public float getFloatValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).floatValue(); } throw new RuntimeDroolsException( "Conversion to float not supported from " + getExtractToClass().getName() ); @@ -109,6 +113,8 @@ public int getIntValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).intValue(); } throw new RuntimeDroolsException( "Conversion to int not supported from " + getExtractToClass().getName() ); @@ -121,6 +127,8 @@ public long getLongValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).longValue(); } throw new RuntimeDroolsException( "Conversion to long not supported from " + getExtractToClass().getName() ); @@ -133,8 +141,10 @@ public short getShortValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return (short) ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).shortValue(); } - + throw new RuntimeDroolsException( "Conversion to short not supported from " + getExtractToClass().getName() ); }
9d48f996e4ee55e89dc3c60d9dd7a8d644316140
ReactiveX-RxJava
Refactoring for consistent implementation approach.--Combined ObservableExtensions into Observable to match how Rx works (Observable.* methods)-
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/org/rx/operations/AtomicWatchableSubscription.java b/rxjava-core/src/main/java/org/rx/operations/AtomicObservableSubscription.java similarity index 95% rename from rxjava-core/src/main/java/org/rx/operations/AtomicWatchableSubscription.java rename to rxjava-core/src/main/java/org/rx/operations/AtomicObservableSubscription.java index f01666e6ab..055d0025dd 100644 --- a/rxjava-core/src/main/java/org/rx/operations/AtomicWatchableSubscription.java +++ b/rxjava-core/src/main/java/org/rx/operations/AtomicObservableSubscription.java @@ -11,7 +11,7 @@ * Thread-safe wrapper around ObservableSubscription that ensures unsubscribe can be called only once. */ @ThreadSafe -/* package */class AtomicObservableSubscription implements Subscription { +/* package */final class AtomicObservableSubscription implements Subscription { private AtomicReference<Subscription> actualSubscription = new AtomicReference<Subscription>(); private AtomicBoolean unsubscribed = new AtomicBoolean(false); diff --git a/rxjava-core/src/main/java/org/rx/operations/AtomicWatcher.java b/rxjava-core/src/main/java/org/rx/operations/AtomicObserver.java similarity index 97% rename from rxjava-core/src/main/java/org/rx/operations/AtomicWatcher.java rename to rxjava-core/src/main/java/org/rx/operations/AtomicObserver.java index c9518e1ee3..aafe260ae0 100644 --- a/rxjava-core/src/main/java/org/rx/operations/AtomicWatcher.java +++ b/rxjava-core/src/main/java/org/rx/operations/AtomicObserver.java @@ -29,7 +29,7 @@ * @param <T> */ @ThreadSafe -/* package */class AtomicObserver<T> implements Observer<T> { +/* package */final class AtomicObserver<T> implements Observer<T> { /** Allow changing between forcing single or allowing multi-threaded execution of onNext */ private static boolean allowMultiThreaded = true; diff --git a/rxjava-core/src/main/java/org/rx/operations/AtomicWatcherMultiThreaded.java b/rxjava-core/src/main/java/org/rx/operations/AtomicObserverMultiThreaded.java similarity index 99% rename from rxjava-core/src/main/java/org/rx/operations/AtomicWatcherMultiThreaded.java rename to rxjava-core/src/main/java/org/rx/operations/AtomicObserverMultiThreaded.java index 1e5ead04e0..e267950b51 100644 --- a/rxjava-core/src/main/java/org/rx/operations/AtomicWatcherMultiThreaded.java +++ b/rxjava-core/src/main/java/org/rx/operations/AtomicObserverMultiThreaded.java @@ -37,7 +37,7 @@ * @param <T> */ @ThreadSafe -/* package */class AtomicObserverMultiThreaded<T> implements Observer<T> { +/* package */final class AtomicObserverMultiThreaded<T> implements Observer<T> { private final Observer<T> Observer; private final AtomicObservableSubscription subscription; diff --git a/rxjava-core/src/main/java/org/rx/operations/AtomicWatcherSingleThreaded.java b/rxjava-core/src/main/java/org/rx/operations/AtomicObserverSingleThreaded.java similarity index 99% rename from rxjava-core/src/main/java/org/rx/operations/AtomicWatcherSingleThreaded.java rename to rxjava-core/src/main/java/org/rx/operations/AtomicObserverSingleThreaded.java index d2c2ffb5af..74bed86347 100644 --- a/rxjava-core/src/main/java/org/rx/operations/AtomicWatcherSingleThreaded.java +++ b/rxjava-core/src/main/java/org/rx/operations/AtomicObserverSingleThreaded.java @@ -34,7 +34,7 @@ * @param <T> */ @ThreadSafe -/* package */class AtomicObserverSingleThreaded<T> implements Observer<T> { +/* package */final class AtomicObserverSingleThreaded<T> implements Observer<T> { /** * Intrinsic synchronized locking with double-check short-circuiting was chosen after testing several other implementations. diff --git a/rxjava-core/src/main/java/org/rx/operations/ObservableExtensions.java b/rxjava-core/src/main/java/org/rx/operations/ObservableExtensions.java deleted file mode 100644 index f5b26b759b..0000000000 --- a/rxjava-core/src/main/java/org/rx/operations/ObservableExtensions.java +++ /dev/null @@ -1,1459 +0,0 @@ -package org.rx.operations; - -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; -import groovy.lang.Binding; -import groovy.lang.GroovyClassLoader; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.codehaus.groovy.runtime.InvokerHelper; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.rx.functions.Func1; -import org.rx.functions.Func2; -import org.rx.functions.Func3; -import org.rx.functions.Func4; -import org.rx.functions.Functions; -import org.rx.reactive.Notification; -import org.rx.reactive.Observable; -import org.rx.reactive.Observer; -import org.rx.reactive.Subscription; - -/** - * A set of methods for creating, combining, and consuming Observables. - * <p> - * Includes overloaded methods that handle the generic Object types being passed in for closures so that we can support Closure and RubyProc and other such types from dynamic languages. - * <p> - * See Functions.execute for supported types. - * <p> - * The documentation for this class makes use of marble diagrams. The following legend explains these diagrams: - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.legend&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.legend.png"></a> - * - * @see <a href="https://confluence.corp.netflix.com/display/API/Observers%2C+Observables%2C+and+the+Reactive+Pattern">API.Next Programmer's Guide: Observers, Observables, and the Reactive Pattern</a> - * @see <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.Seq">scala.collection: Seq</a> - * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable(v=vs.103).aspx">MSDN: Observable Class</a> - * @see <a href="http://rxwiki.wikidot.com/observable-operators">Reactive Framework Wiki: Observable Operators</a> - */ -public class ObservableExtensions { - - /** - * A Observable that never sends any information to a Observer. - * - * This Observable is useful primarily for testing purposes. - * - * @param <T> - * the type of item emitted by the Observable - */ - private static class NeverObservable<T> extends Observable<T> { - public Subscription subscribe(Observer<T> observer) { - return new NullObservableSubscription(); - } - } - - /** - * A disposable object that does nothing when its unsubscribe method is called. - */ - private static class NullObservableSubscription implements Subscription { - public void unsubscribe() { - } - } - - /** - * A Observable that calls a Observer's <code>onError</code> closure when the Observer subscribes. - * - * @param <T> - * the type of object returned by the Observable - */ - private static class ThrowObservable<T> extends Observable<T> { - private Exception exception; - - public ThrowObservable(Exception exception) { - this.exception = exception; - } - - /** - * Accepts a Observer and calls its <code>onError</code> method. - * - * @param observer - * a Observer of this Observable - * @return a reference to the subscription - */ - public Subscription subscribe(Observer<T> observer) { - observer.onError(this.exception); - return new NullObservableSubscription(); - } - } - - /** - * Creates a Observable that will execute the given function when a Observer subscribes to it. - * <p> - * You can create a simple Observable from scratch by using the <code>create</code> method. You pass this method a closure that accepts as a parameter the map of closures that a Observer passes to a - * Observable's <code>subscribe</code> method. Write - * the closure you pass to <code>create</code> so that it behaves as a Observable - calling the passed-in <code>onNext</code>, <code>onError</code>, and <code>onCompleted</code> methods - * appropriately. - * <p> - * A well-formed Observable must call either the Observer's <code>onCompleted</code> method exactly once or its <code>onError</code> method exactly once. - * - * @param <T> - * the type emitted by the Observable sequence - * @param func - * a closure that accepts a <code>Observer<T></code> and calls its <code>onNext</code>, <code>onError</code>, and <code>onCompleted</code> methods - * as appropriate, and returns a <code>ObservableSubscription</code> to allow - * cancelling the subscription (if applicable) - * @return a Observable that, when a Observer subscribes to it, will execute the given function - */ - public static <T> Observable<T> create(Func1<Subscription, Observer<T>> func) { - return wrap(new OperationToObservableFunction<T>(func)); - } - - /** - * Creates a Observable that will execute the given function when a Observer subscribes to it. - * <p> - * You can create a simple Observable from scratch by using the <code>create</code> method. You pass this method a closure that accepts as a parameter the map of closures that a Observer passes to a - * Observable's <code>subscribe</code> method. Write - * the closure you pass to <code>create</code> so that it behaves as a Observable - calling the passed-in <code>onNext</code>, <code>onError</code>, and <code>onCompleted</code> methods - * appropriately. - * <p> - * A well-formed Observable must call either the Observer's <code>onCompleted</code> method exactly once or its <code>onError</code> method exactly once. - * - * @param <T> - * the type of the observable sequence - * @param func - * a closure that accepts a <code>Observer<T></code> and calls its <code>onNext</code>, <code>onError</code>, and <code>onCompleted</code> methods - * as appropriate, and returns a <code>ObservableSubscription</code> to allow - * cancelling the subscription (if applicable) - * @return a Observable that, when a Observer subscribes to it, will execute the given function - */ - public static <T> Observable<T> create(final Object callback) { - return create(new Func1<Subscription, Observer<T>>() { - - @Override - public Subscription call(Observer<T> t1) { - return Functions.execute(callback, t1); - } - - }); - } - - /** - * Returns a Observable that returns no data to the Observer and immediately invokes its <code>onCompleted</code> method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.empty&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.empty.png"></a> - * - * @param <T> - * the type of item emitted by the Observable - * @return a Observable that returns no data to the Observer and immediately invokes the - * Observer's <code>onCompleted</code> method - */ - public static <T> Observable<T> empty() { - return toObservable(new ArrayList<T>()); - } - - /** - * Returns a Observable that calls <code>onError</code> when a Observer subscribes to it. - * <p> - * Note: Maps to <code>Observable.Throw</code> in Rx - throw is a reserved word in Java. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.error&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.error.png"></a> - * - * @param exception - * the error to throw - * @param <T> - * the type of object returned by the Observable - * @return a Observable object that calls <code>onError</code> when a Observer subscribes - */ - public static <T> Observable<T> error(Exception exception) { - return wrap(new ThrowObservable<T>(exception)); - } - - /** - * Filters a Observable by discarding any of its emissions that do not meet some test. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.filter&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.filter.png"></a> - * - * @param that - * the Observable to filter - * @param predicate - * a closure that evaluates the items emitted by the source Observable, returning <code>true</code> if they pass the filter - * @return a Observable that emits only those items in the original Observable that the filter - * evaluates as true - */ - public static <T> Observable<T> filter(Observable<T> that, Func1<Boolean, T> predicate) { - return new OperationFilter<T>(that, predicate); - } - - /** - * Filters a Observable by discarding any of its emissions that do not meet some test. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.filter&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.filter.png"></a> - * - * @param that - * the Observable to filter - * @param predicate - * a closure that evaluates the items emitted by the source Observable, returning <code>true</code> if they pass the filter - * @return a Observable that emits only those items in the original Observable that the filter - * evaluates as true - */ - public static <T> Observable<T> filter(Observable<T> that, final Object function) { - return filter(that, new Func1<Boolean, T>() { - - @Override - public Boolean call(T t1) { - return Functions.execute(function, t1); - - } - - }); - } - - /** - * Returns a Observable that notifies an observer of a single value and then completes. - * <p> - * To convert any object into a Observable that emits that object, pass that object into the <code>just</code> method. - * <p> - * This is similar to the {@link toObservable} method, except that <code>toObservable</code> will convert an iterable object into a Observable that emits each of the items in the iterable, one at a - * time, while the <code>just</code> method would - * convert the iterable into a Observable that emits the entire iterable as a single item. - * <p> - * This value is the equivalent of <code>Observable.Return</code> in the Reactive Extensions library. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.just&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.just.png"></a> - * - * @param value - * the value to pass to the Observer's <code>onNext</code> method - * @param <T> - * the type of the value - * @return a Observable that notifies a Observer of a single value and then completes - */ - public static <T> Observable<T> just(T value) { - List<T> list = new ArrayList<T>(); - list.add(value); - - return toObservable(list); - } - - /** - * Takes the last item emitted by a source Observable and returns a Observable that emits only - * that item as its sole emission. - * <p> - * To convert a Observable that emits a sequence of objects into one that only emits the last object in this sequence before completing, use the <code>last</code> method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.last&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.last.png"></a> - * - * @param that - * the source Observable - * @return a Observable that emits a single item, which is identical to the last item emitted - * by the source Observable - */ - public static <T> Observable<T> last(final Observable<T> that) { - return wrap(new OperationLast<T>(that)); - } - - /** - * Applies a closure of your choosing to every notification emitted by a Observable, and returns - * this transformation as a new Observable sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.map&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.map.png"></a> - * - * @param sequence - * the source Observable - * @param func - * a closure to apply to each item in the sequence emitted by the source Observable - * @param <T> - * the type of items emitted by the the source Observable - * @param <R> - * the type of items returned by map closure <code>func</code> - * @return a Observable that is the result of applying the transformation function to each item - * in the sequence emitted by the source Observable - */ - public static <T, R> Observable<R> map(Observable<T> sequence, Func1<R, T> func) { - return wrap(OperationMap.map(sequence, func)); - } - - /** - * Applies a closure of your choosing to every notification emitted by a Observable, and returns - * this transformation as a new Observable sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.map&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.map.png"></a> - * - * @param sequence - * the source Observable - * @param function - * a closure to apply to each item in the sequence emitted by the source Observable - * @param <T> - * the type of items emitted by the the source Observable - * @param <R> - * the type of items returned by map closure <code>function</code> - * @return a Observable that is the result of applying the transformation function to each item - * in the sequence emitted by the source Observable - */ - public static <T, R> Observable<R> map(Observable<T> sequence, final Object function) { - return map(sequence, new Func1<R, T>() { - - @Override - public R call(T t1) { - return Functions.execute(function, t1); - } - - }); - } - - /** - * Creates a new Observable sequence by applying a closure that you supply to each object in the - * original Observable sequence, where that closure is itself a Observable that emits objects, - * and then merges the results of that closure applied to every item emitted by the original - * Observable, emitting these merged results as its own sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mapmany&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mapMany.png"></a> - * - * @param sequence - * the source Observable - * @param func - * a closure to apply to each item emitted by the source Observable, generating a - * Observable - * @param <T> - * the type emitted by the source Observable - * @param <R> - * the type emitted by the Observables emitted by <code>func</code> - * @return a Observable that emits a sequence that is the result of applying the transformation - * function to each item emitted by the source Observable and merging the results of - * the Observables obtained from this transformation - */ - public static <T, R> Observable<R> mapMany(Observable<T> sequence, Func1<Observable<R>, T> func) { - return wrap(OperationMap.mapMany(sequence, func)); - } - - /** - * Creates a new Observable sequence by applying a closure that you supply to each object in the - * original Observable sequence, where that closure is itself a Observable that emits objects, - * and then merges the results of that closure applied to every item emitted by the original - * Observable, emitting these merged results as its own sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mapmany&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mapMany.png"></a> - * - * @param sequence - * the source Observable - * @param function - * a closure to apply to each item emitted by the source Observable, generating a - * Observable - * @param <T> - * the type emitted by the source Observable - * @param <R> - * the type emitted by the Observables emitted by <code>function</code> - * @return a Observable that emits a sequence that is the result of applying the transformation - * function to each item emitted by the source Observable and merging the results of the - * Observables obtained from this transformation - */ - public static <T, R> Observable<R> mapMany(Observable<T> sequence, final Object function) { - return mapMany(sequence, new Func1<R, T>() { - - @Override - public R call(T t1) { - return Functions.execute(function, t1); - } - - }); - } - - /** - * Materializes the implicit notifications of an observable sequence as explicit notification values. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.materialize&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.materialize.png"></a> - * - * @param source - * An observable sequence of elements to project. - * @return An observable sequence whose elements are the result of materializing the notifications of the given sequence. - * @see http://msdn.microsoft.com/en-us/library/hh229453(v=VS.103).aspx - */ - public static <T> Observable<Notification<T>> materialize(final Observable<T> sequence) { - return OperationMaterialize.materialize(sequence); - } - - /** - * Flattens the Observable sequences from a list of Observables into one Observable sequence - * without any transformation. You can combine the output of multiple Observables so that they - * act like a single Observable, by using the <code>merge</code> method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.merge&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.merge.png"></a> - * - * @param source - * a list of Observables that emit sequences of items - * @return a Observable that emits a sequence of elements that are the result of flattening the - * output from the <code>source</code> list of Observables - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> - */ - public static <T> Observable<T> merge(List<Observable<T>> source) { - return wrap(OperationMerge.merge(source)); - } - - /** - * Flattens the Observable sequences from a series of Observables into one Observable sequence - * without any transformation. You can combine the output of multiple Observables so that they - * act like a single Observable, by using the <code>merge</code> method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.merge&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.merge.png"></a> - * - * @param source - * a series of Observables that emit sequences of items - * @return a Observable that emits a sequence of elements that are the result of flattening the - * output from the <code>source</code> Observables - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> - */ - public static <T> Observable<T> merge(Observable<T>... source) { - return wrap(OperationMerge.merge(source)); - } - - /** - * Flattens the Observable sequences emitted by a sequence of Observables that are emitted by a - * Observable into one Observable sequence without any transformation. You can combine the output - * of multiple Observables so that they act like a single Observable, by using the <code>merge</code> method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.merge.W&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.merge.W.png"></a> - * - * @param source - * a Observable that emits Observables - * @return a Observable that emits a sequence of elements that are the result of flattening the - * output from the Observables emitted by the <code>source</code> Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> - */ - public static <T> Observable<T> merge(Observable<Observable<T>> source) { - return wrap(OperationMerge.merge(source)); - } - - /** - * Same functionality as <code>merge</code> except that errors received to onError will be held until all sequences have finished (onComplete/onError) before sending the error. - * <p> - * Only the first onError received will be sent. - * <p> - * This enables receiving all successes from merged sequences without one onError from one sequence causing all onNext calls to be prevented. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mergeDelayError&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mergeDelayError.png"></a> - * - * @param source - * a list of Observables that emit sequences of items - * @return a Observable that emits a sequence of elements that are the result of flattening the - * output from the <code>source</code> list of Observables - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> - */ - public static <T> Observable<T> mergeDelayError(List<Observable<T>> source) { - return wrap(OperationMergeDelayError.mergeDelayError(source)); - } - - /** - * Same functionality as <code>merge</code> except that errors received to onError will be held until all sequences have finished (onComplete/onError) before sending the error. - * <p> - * Only the first onError received will be sent. - * <p> - * This enables receiving all successes from merged sequences without one onError from one sequence causing all onNext calls to be prevented. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mergeDelayError&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mergeDelayError.png"></a> - * - * @param source - * a series of Observables that emit sequences of items - * @return a Observable that emits a sequence of elements that are the result of flattening the - * output from the <code>source</code> Observables - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> - */ - public static <T> Observable<T> mergeDelayError(Observable<T>... source) { - return wrap(OperationMergeDelayError.mergeDelayError(source)); - } - - /** - * Same functionality as <code>merge</code> except that errors received to onError will be held until all sequences have finished (onComplete/onError) before sending the error. - * <p> - * Only the first onError received will be sent. - * <p> - * This enables receiving all successes from merged sequences without one onError from one sequence causing all onNext calls to be prevented. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mergeDelayError.W&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mergeDelayError.W.png"></a> - * - * @param source - * a Observable that emits Observables - * @return a Observable that emits a sequence of elements that are the result of flattening the - * output from the Observables emitted by the <code>source</code> Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> - */ - public static <T> Observable<T> mergeDelayError(Observable<Observable<T>> source) { - return wrap(OperationMergeDelayError.mergeDelayError(source)); - } - - /** - * Returns a Observable that never sends any information to a Observer. - * - * This observable is useful primarily for testing purposes. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.never&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.never.png"></a> - * - * @param <T> - * the type of item (not) emitted by the Observable - * @return a Observable that never sends any information to a Observer - */ - public static <T> Observable<T> never() { - return wrap(new NeverObservable<T>()); - } - - /** - * A ObservableSubscription that does nothing. - * - * @return - */ - public static Subscription noOpSubscription() { - return new NullObservableSubscription(); - } - - /** - * Instruct a Observable to pass control to another Observable rather than calling <code>onError</code> if it encounters an error. - * <p> - * By default, when a Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and then quits - * without calling any more of its Observer's - * closures. The <code>onErrorResumeNext</code> method changes this behavior. If you pass another Observable (<code>resumeSequence</code>) to a Observable's <code>onErrorResumeNext</code> method, if - * the original Observable encounters an error, - * instead of calling its Observer's <code>onError</code> closure, it will instead relinquish control to <code>resumeSequence</code> which will call the Observer's <code>onNext</code> method if it - * is able to do so. In such a case, because no - * Observable necessarily invokes <code>onError</code>, the Observer may never know that an error happened. - * <p> - * You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorresumenext&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorresumenext.png"></a> - * - * @param that - * the source Observable - * @param resumeSequence - * the Observable that will take over if the source Observable encounters an error - * @return the source Observable, with its behavior modified as described - */ - public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, final Observable<T> resumeSequence) { - return wrap(new OperationOnErrorResumeNextViaObservable<T>(that, resumeSequence)); - } - - /** - * Instruct a Observable to pass control to another Observable (the return value of a function) - * rather than calling <code>onError</code> if it encounters an error. - * <p> - * By default, when a Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and then quits - * without calling any more of its Observer's - * closures. The <code>onErrorResumeNext</code> method changes this behavior. If you pass a closure that emits a Observable (<code>resumeFunction</code>) to a Observable's - * <code>onErrorResumeNext</code> method, if the original Observable encounters - * an error, instead of calling its Observer's <code>onError</code> closure, it will instead relinquish control to this new Observable, which will call the Observer's <code>onNext</code> method if it - * is able to do so. In such a case, because no - * Observable necessarily invokes <code>onError</code>, the Observer may never know that an error happened. - * <p> - * You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorresumenext&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorresumenext.png"></a> - * - * @param that - * the source Observable - * @param resumeFunction - * a closure that returns a Observable that will take over if the source Observable - * encounters an error - * @return the source Observable, with its behavior modified as described - */ - public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, final Func1<Observable<T>, Exception> resumeFunction) { - return wrap(new OperationOnErrorResumeNextViaFunction<T>(that, resumeFunction)); - } - - /** - * Instruct a Observable to emit a particular object (as returned by a closure) to its Observer - * rather than calling <code>onError</code> if it encounters an error. - * <p> - * By default, when a Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and then quits - * without calling any more of its Observer's - * closures. The <code>onErrorResumeNext</code> method changes this behavior. If you pass a function that returns another Observable (<code>resumeFunction</code>) to a Observable's - * <code>onErrorResumeNext</code> method, if the original Observable - * encounters an error, instead of calling its Observer's <code>onError</code> closure, it will instead relinquish control to this new Observable which will call the Observer's <code>onNext</code> - * method if it is able to do so. In such a case, - * because no Observable necessarily invokes <code>onError</code>, the Observer may never know that an error happened. - * <p> - * You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorresumenext&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorresumenext.png"></a> - * - * @param that - * the source Observable - * @param resumeFunction - * a closure that returns a Observable that will take over if the source Observable - * encounters an error - * @return the source Observable, with its behavior modified as described - */ - public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, final Object resumeFunction) { - return onErrorResumeNext(that, new Func1<Observable<T>, Exception>() { - - @Override - public Observable<T> call(Exception e) { - return Functions.execute(resumeFunction, e); - } - }); - } - - /** - * Instruct a Observable to emit a particular item to its Observer's <code>onNext</code> closure - * rather than calling <code>onError</code> if it encounters an error. - * <p> - * By default, when a Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and then quits - * without calling any more of its Observer's - * closures. The <code>onErrorReturn</code> method changes this behavior. If you pass a closure (<code>resumeFunction</code>) to a Observable's <code>onErrorReturn</code> method, if the original - * Observable encounters an error, instead of calling - * its Observer's <code>onError</code> closure, it will instead pass the return value of <code>resumeFunction</code> to the Observer's <code>onNext</code> method. - * <p> - * You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorreturn&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorreturn.png"></a> - * - * @param that - * the source Observable - * @param resumeFunction - * a closure that returns a value that will be passed into a Observer's <code>onNext</code> closure if the Observable encounters an error that would - * otherwise cause it to call <code>onError</code> - * @return the source Observable, with its behavior modified as described - */ - public static <T> Observable<T> onErrorReturn(final Observable<T> that, Func1<T, Exception> resumeFunction) { - return wrap(new OperationOnErrorReturn<T>(that, resumeFunction)); - } - - /** - * Returns a Observable that applies a closure of your choosing to the first item emitted by a - * source Observable, then feeds the result of that closure along with the second item emitted - * by a Observable into the same closure, and so on until all items have been emitted by the - * source Observable, emitting the final result from the final call to your closure as its sole - * output. - * <p> - * This technique, which is called "reduce" here, is sometimes called "fold," "accumulate," "compress," or "inject" in other programming contexts. Groovy, for instance, has an <code>inject</code> - * method that does a similar operation on lists. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.reduce.noseed&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.reduce.noseed.png"></a> - * - * @param <T> - * the type item emitted by the source Observable - * @param sequence - * the source Observable - * @param accumulator - * an accumulator closure to be invoked on each element from the sequence, whose - * result will be used in the next accumulator call (if applicable) - * - * @return a Observable that emits a single element that is the result of accumulating the - * output from applying the accumulator to the sequence of items emitted by the source - * Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> - * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> - */ - public static <T> Observable<T> reduce(Observable<T> sequence, Func2<T, T, T> accumulator) { - return wrap(OperationScan.scan(sequence, accumulator).last()); - } - - /** - * Returns a Observable that applies a closure of your choosing to the first item emitted by a - * source Observable, then feeds the result of that closure along with the second item emitted - * by a Observable into the same closure, and so on until all items have been emitted by the - * source Observable, emitting the final result from the final call to your closure as its sole - * output. - * <p> - * This technique, which is called "reduce" here, is sometimes called "fold," "accumulate," "compress," or "inject" in other programming contexts. Groovy, for instance, has an <code>inject</code> - * method that does a similar operation on lists. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.reduce.noseed&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.reduce.noseed.png"></a> - * - * @param <T> - * the type item emitted by the source Observable - * @param sequence - * the source Observable - * @param accumulator - * an accumulator closure to be invoked on each element from the sequence, whose - * result will be used in the next accumulator call (if applicable) - * - * @return a Observable that emits a single element that is the result of accumulating the - * output from applying the accumulator to the sequence of items emitted by the source - * Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> - * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> - */ - public static <T> Observable<T> reduce(final Observable<T> sequence, final Object accumulator) { - return reduce(sequence, new Func2<T, T, T>() { - - @Override - public T call(T t1, T t2) { - return Functions.execute(accumulator, t1, t2); - } - - }); - } - - /** - * Returns a Observable that applies a closure of your choosing to the first item emitted by a - * source Observable, then feeds the result of that closure along with the second item emitted - * by a Observable into the same closure, and so on until all items have been emitted by the - * source Observable, emitting the final result from the final call to your closure as its sole - * output. - * <p> - * This technique, which is called "reduce" here, is sometimes called "fold," "accumulate," "compress," or "inject" in other programming contexts. Groovy, for instance, has an <code>inject</code> - * method that does a similar operation on lists. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.reduce&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.reduce.png"></a> - * - * @param <T> - * the type item emitted by the source Observable - * @param sequence - * the source Observable - * @param initialValue - * a seed passed into the first execution of the accumulator closure - * @param accumulator - * an accumulator closure to be invoked on each element from the sequence, whose - * result will be used in the next accumulator call (if applicable) - * - * @return a Observable that emits a single element that is the result of accumulating the - * output from applying the accumulator to the sequence of items emitted by the source - * Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> - * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> - */ - public static <T> Observable<T> reduce(Observable<T> sequence, T initialValue, Func2<T, T, T> accumulator) { - return wrap(OperationScan.scan(sequence, initialValue, accumulator).last()); - } - - /** - * Returns a Observable that applies a closure of your choosing to the first item emitted by a - * source Observable, then feeds the result of that closure along with the second item emitted - * by a Observable into the same closure, and so on until all items have been emitted by the - * source Observable, emitting the final result from the final call to your closure as its sole - * output. - * <p> - * This technique, which is called "reduce" here, is sometimes called "fold," "accumulate," "compress," or "inject" in other programming contexts. Groovy, for instance, has an <code>inject</code> - * method that does a similar operation on lists. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.reduce&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.reduce.png"></a> - * - * @param <T> - * the type item emitted by the source Observable - * @param sequence - * the source Observable - * @param initialValue - * a seed passed into the first execution of the accumulator closure - * @param accumulator - * an accumulator closure to be invoked on each element from the sequence, whose - * result will be used in the next accumulator call (if applicable) - * @return a Observable that emits a single element that is the result of accumulating the - * output from applying the accumulator to the sequence of items emitted by the source - * Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> - * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> - */ - public static <T> Observable<T> reduce(final Observable<T> sequence, final T initialValue, final Object accumulator) { - return reduce(sequence, initialValue, new Func2<T, T, T>() { - - @Override - public T call(T t1, T t2) { - return Functions.execute(accumulator, t1, t2); - } - - }); - } - - /** - * Returns a Observable that applies a closure of your choosing to the first item emitted by a - * source Observable, then feeds the result of that closure along with the second item emitted - * by a Observable into the same closure, and so on until all items have been emitted by the - * source Observable, emitting the result of each of these iterations as its own sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.scan.noseed&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.scan.noseed.png"></a> - * - * @param <T> - * the type item emitted by the source Observable - * @param sequence - * the source Observable - * @param accumulator - * an accumulator closure to be invoked on each element from the sequence, whose - * result will be emitted and used in the next accumulator call (if applicable) - * @return a Observable that emits a sequence of items that are the result of accumulating the - * output from the sequence emitted by the source Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> - */ - public static <T> Observable<T> scan(Observable<T> sequence, Func2<T, T, T> accumulator) { - return wrap(OperationScan.scan(sequence, accumulator)); - } - - /** - * Returns a Observable that applies a closure of your choosing to the first item emitted by a - * source Observable, then feeds the result of that closure along with the second item emitted - * by a Observable into the same closure, and so on until all items have been emitted by the - * source Observable, emitting the result of each of these iterations as its own sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.scan.noseed&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.scan.noseed.png"></a> - * - * @param <T> - * the type item emitted by the source Observable - * @param sequence - * the source Observable - * @param accumulator - * an accumulator closure to be invoked on each element from the sequence, whose - * result will be emitted and used in the next accumulator call (if applicable) - * @return a Observable that emits a sequence of items that are the result of accumulating the - * output from the sequence emitted by the source Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> - */ - public static <T> Observable<T> scan(final Observable<T> sequence, final Object accumulator) { - return scan(sequence, new Func2<T, T, T>() { - - @Override - public T call(T t1, T t2) { - return Functions.execute(accumulator, t1, t2); - } - - }); - } - - /** - * Returns a Observable that applies a closure of your choosing to the first item emitted by a - * source Observable, then feeds the result of that closure along with the second item emitted - * by a Observable into the same closure, and so on until all items have been emitted by the - * source Observable, emitting the result of each of these iterations as its own sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.scan&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.scan.png"></a> - * - * @param <T> - * the type item emitted by the source Observable - * @param sequence - * the source Observable - * @param initialValue - * the initial (seed) accumulator value - * @param accumulator - * an accumulator closure to be invoked on each element from the sequence, whose - * result will be emitted and used in the next accumulator call (if applicable) - * @return a Observable that emits a sequence of items that are the result of accumulating the - * output from the sequence emitted by the source Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> - */ - public static <T> Observable<T> scan(Observable<T> sequence, T initialValue, Func2<T, T, T> accumulator) { - return wrap(OperationScan.scan(sequence, initialValue, accumulator)); - } - - /** - * Returns a Observable that applies a closure of your choosing to the first item emitted by a - * source Observable, then feeds the result of that closure along with the second item emitted - * by a Observable into the same closure, and so on until all items have been emitted by the - * source Observable, emitting the result of each of these iterations as its own sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.scan&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.scan.png"></a> - * - * @param <T> - * the type item emitted by the source Observable - * @param sequence - * the source Observable - * @param initialValue - * the initial (seed) accumulator value - * @param accumulator - * an accumulator closure to be invoked on each element from the sequence, whose - * result will be emitted and used in the next accumulator call (if applicable) - * @return a Observable that emits a sequence of items that are the result of accumulating the - * output from the sequence emitted by the source Observable - * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> - */ - public static <T> Observable<T> scan(final Observable<T> sequence, final T initialValue, final Object accumulator) { - return scan(sequence, initialValue, new Func2<T, T, T>() { - - @Override - public T call(T t1, T t2) { - return Functions.execute(accumulator, t1, t2); - } - - }); - } - - /** - * Returns a Observable that skips the first <code>num</code> items emitted by the source - * Observable. You can ignore the first <code>num</code> items emitted by a Observable and attend - * only to those items that come after, by modifying the Observable with the <code>skip</code> method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.skip&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.skip.png"></a> - * - * @param items - * the source Observable - * @param num - * the number of items to skip - * @return a Observable that emits the same sequence of items emitted by the source Observable, - * except for the first <code>num</code> items - * @see <a href="http://msdn.microsoft.com/en-us/library/hh229847(v=vs.103).aspx">MSDN: Observable.Skip Method</a> - */ - public static <T> Observable<T> skip(final Observable<T> items, int num) { - return wrap(OperationSkip.skip(items, num)); - } - - /** - * Accepts a Observable and wraps it in another Observable that ensures that the resulting - * Observable is chronologically well-behaved. - * <p> - * A well-behaved observable ensures <code>onNext</code>, <code>onCompleted</code>, or <code>onError</code> calls to its subscribers are not interleaved, <code>onCompleted</code> and - * <code>onError</code> are only called once respectively, and no - * <code>onNext</code> calls follow <code>onCompleted</code> and <code>onError</code> calls. - * - * @param observable - * the source Observable - * @param <T> - * the type of item emitted by the source Observable - * @return a Observable that is a chronologically well-behaved version of the source Observable - */ - public static <T> Observable<T> synchronize(Observable<T> observable) { - return wrap(new OperationSynchronize<T>(observable)); - } - - /** - * Returns a Observable that emits the first <code>num</code> items emitted by the source - * Observable. - * <p> - * You can choose to pay attention only to the first <code>num</code> values emitted by a Observable by calling its <code>take</code> method. This method returns a Observable that will call a - * subscribing Observer's <code>onNext</code> closure a - * maximum of <code>num</code> times before calling <code>onCompleted</code>. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.take&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.take.png"></a> - * - * @param items - * the source Observable - * @param num - * the number of items from the start of the sequence emitted by the source - * Observable to emit - * @return a Observable that only emits the first <code>num</code> items emitted by the source - * Observable - */ - public static <T> Observable<T> take(final Observable<T> items, final int num) { - return wrap(OperationTake.take(items, num)); - } - - /** - * Returns a Observable that emits a single item, a list composed of all the items emitted by - * the source Observable. - * <p> - * Normally, a Observable that returns multiple items will do so by calling its Observer's <code>onNext</code> closure for each such item. You can change this behavior, instructing the Observable to - * compose a list of all of these multiple items and - * then to call the Observer's <code>onNext</code> closure once, passing it the entire list, by calling the Observable object's <code>toList</code> method prior to calling its <code>subscribe</code> - * method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.tolist&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.tolist.png"></a> - * - * @param that - * the source Observable - * @return a Observable that emits a single item: a <code>List</code> containing all of the - * items emitted by the source Observable - */ - public static <T> Observable<List<T>> toList(final Observable<T> that) { - return wrap(new OperationToObservableList<T>(that)); - } - - /** - * Sort T objects by their natural order (object must implement Comparable). - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.tolistsorted&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.tolistsorted.png"></a> - * - * @param sequence - * @throws ClassCastException - * if T objects do not implement Comparable - * @return - */ - public static <T> Observable<List<T>> toSortedList(Observable<T> sequence) { - return wrap(OperationToObservableSortedList.toSortedList(sequence)); - } - - /** - * Sort T objects using the defined sort function. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.tolistsorted.f&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.tolistsorted.f.png"></a> - * - * @param sequence - * @param sortFunction - * @return - */ - public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, Func2<Integer, T, T> sortFunction) { - return wrap(OperationToObservableSortedList.toSortedList(sequence, sortFunction)); - } - - /** - * Sort T objects using the defined sort function. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.tolistsorted.f&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.tolistsorted.f.png"></a> - * - * @param sequence - * @param sortFunction - * @return - */ - public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, final Object sortFunction) { - return wrap(OperationToObservableSortedList.toSortedList(sequence, new Func2<Integer, T, T>() { - - @Override - public Integer call(T t1, T t2) { - return Functions.execute(sortFunction, t1, t2); - } - - })); - } - - /** - * Converts an Iterable sequence to a Observable sequence. - * - * Any object that supports the Iterable interface can be converted into a Observable that emits - * each iterable item in the object, by passing the object into the <code>toObservable</code> method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.toObservable&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.toObservable.png"></a> - * - * @param iterable - * the source Iterable sequence - * @param <T> - * the type of items in the iterable sequence and the type emitted by the resulting - * Observable - * @return a Observable that emits each item in the source Iterable sequence - */ - public static <T> Observable<T> toObservable(Iterable<T> iterable) { - return wrap(new OperationToObservableIterable<T>(iterable)); - } - - /** - * Converts an Array sequence to a Observable sequence. - * - * An Array can be converted into a Observable that emits each item in the Array, by passing the - * Array into the <code>toObservable</code> method. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.toObservable&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.toObservable.png"></a> - * - * @param iterable - * the source Array - * @param <T> - * the type of items in the Array, and the type of items emitted by the resulting - * Observable - * @return a Observable that emits each item in the source Array - */ - public static <T> Observable<T> toObservable(T... items) { - return toObservable(Arrays.asList(items)); - } - - /** - * Allow wrapping responses with the <code>AbstractObservable</code> so that we have all of - * the utility methods available for subscribing. - * <p> - * This is not expected to benefit Java usage, but is intended for dynamic script which are a primary target of the Observable operations. - * <p> - * Since they are dynamic they can execute the "hidden" methods on <code>AbstractObservable</code> while appearing to only receive an <code>Observable</code> without first casting. - * - * @param o - * @return - */ - private static <T> Observable<T> wrap(final Observable<T> o) { - if (o instanceof Observable) { - // if the Observable is already an AbstractObservable, don't wrap it again. - return (Observable<T>) o; - } - return new Observable<T>() { - - @Override - public Subscription subscribe(Observer<T> observer) { - return o.subscribe(observer); - } - - }; - } - - /** - * Returns a Observable that applies a closure of your choosing to the combination of items - * emitted, in sequence, by two other Observables, with the results of this closure becoming the - * sequence emitted by the returned Observable. - * <p> - * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code> - * and the first item emitted by <code>w1</code>; the - * second item emitted by the new Observable will be the result of the closure applied to the second item emitted by <code>w0</code> and the second item emitted by <code>w1</code>; and so forth. - * <p> - * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the - * shortest sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.png"></a> - * - * @param w0 - * one source Observable - * @param w1 - * another source Observable - * @param reduceFunction - * a closure that, when applied to an item emitted by each of the source Observables, - * results in a value that will be emitted by the resulting Observable - * @return a Observable that emits the zipped results - */ - public static <R, T0, T1> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Func2<R, T0, T1> reduceFunction) { - return wrap(OperationZip.zip(w0, w1, reduceFunction)); - } - - /** - * Returns a Observable that applies a closure of your choosing to the combination of items - * emitted, in sequence, by two other Observables, with the results of this closure becoming the - * sequence emitted by the returned Observable. - * <p> - * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code> - * and the first item emitted by <code>w1</code>; the - * second item emitted by the new Observable will be the result of the closure applied to the second item emitted by <code>w0</code> and the second item emitted by <code>w1</code>; and so forth. - * <p> - * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the - * shortest sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.png"></a> - * - * @param w0 - * one source Observable - * @param w1 - * another source Observable - * @param reduceFunction - * a closure that, when applied to an item emitted by each of the source Observables, - * results in a value that will be emitted by the resulting Observable - * @return a Observable that emits the zipped results - */ - public static <R, T0, T1> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, final Object function) { - return zip(w0, w1, new Func2<R, T0, T1>() { - - @Override - public R call(T0 t0, T1 t1) { - return Functions.execute(function, t0, t1); - } - - }); - } - - /** - * Returns a Observable that applies a closure of your choosing to the combination of items - * emitted, in sequence, by three other Observables, with the results of this closure becoming - * the sequence emitted by the returned Observable. - * <p> - * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code>, - * the first item emitted by <code>w1</code>, and the - * first item emitted by <code>w2</code>; the second item emitted by the new Observable will be the result of the closure applied to the second item emitted by <code>w0</code>, the second item - * emitted by <code>w1</code>, and the second item - * emitted by <code>w2</code>; and so forth. - * <p> - * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the - * shortest sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip.3&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.3.png"></a> - * - * @param w0 - * one source Observable - * @param w1 - * another source Observable - * @param w2 - * a third source Observable - * @param function - * a closure that, when applied to an item emitted by each of the source Observables, - * results in a value that will be emitted by the resulting Observable - * @return a Observable that emits the zipped results - */ - public static <R, T0, T1, T2> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Func3<R, T0, T1, T2> function) { - return wrap(OperationZip.zip(w0, w1, w2, function)); - } - - /** - * Returns a Observable that applies a closure of your choosing to the combination of items - * emitted, in sequence, by three other Observables, with the results of this closure becoming - * the sequence emitted by the returned Observable. - * <p> - * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code>, - * the first item emitted by <code>w1</code>, and the - * first item emitted by <code>w2</code>; the second item emitted by the new Observable will be the result of the closure applied to the second item emitted by <code>w0</code>, the second item - * emitted by <code>w1</code>, and the second item - * emitted by <code>w2</code>; and so forth. - * <p> - * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the - * shortest sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip.3&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.3.png"></a> - * - * @param w0 - * one source Observable - * @param w1 - * another source Observable - * @param w2 - * a third source Observable - * @param function - * a closure that, when applied to an item emitted by each of the source Observables, - * results in a value that will be emitted by the resulting Observable - * @return a Observable that emits the zipped results - */ - public static <R, T0, T1, T2> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, final Object function) { - return zip(w0, w1, w2, new Func3<R, T0, T1, T2>() { - - @Override - public R call(T0 t0, T1 t1, T2 t2) { - return Functions.execute(function, t0, t1, t2); - } - - }); - } - - /** - * Returns a Observable that applies a closure of your choosing to the combination of items - * emitted, in sequence, by four other Observables, with the results of this closure becoming - * the sequence emitted by the returned Observable. - * <p> - * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code>, - * the first item emitted by <code>w1</code>, the - * first item emitted by <code>w2</code>, and the first item emitted by <code>w3</code>; the second item emitted by the new Observable will be the result of the closure applied to the second item - * emitted by each of those Observables; and so forth. - * <p> - * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the - * shortest sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip.4&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.4.png"></a> - * - * @param w0 - * one source Observable - * @param w1 - * another source Observable - * @param w2 - * a third source Observable - * @param w3 - * a fourth source Observable - * @param reduceFunction - * a closure that, when applied to an item emitted by each of the source Observables, - * results in a value that will be emitted by the resulting Observable - * @return a Observable that emits the zipped results - */ - public static <R, T0, T1, T2, T3> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Observable<T3> w3, Func4<R, T0, T1, T2, T3> reduceFunction) { - return wrap(OperationZip.zip(w0, w1, w2, w3, reduceFunction)); - } - - /** - * Returns a Observable that applies a closure of your choosing to the combination of items - * emitted, in sequence, by four other Observables, with the results of this closure becoming - * the sequence emitted by the returned Observable. - * <p> - * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code>, - * the first item emitted by <code>w1</code>, the - * first item emitted by <code>w2</code>, and the first item emitted by <code>w3</code>; the second item emitted by the new Observable will be the result of the closure applied to the second item - * emitted by each of those Observables; and so forth. - * <p> - * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the - * shortest sequence. - * <p> - * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip.4&ceoid=27321465&key=API&pageId=27321465"><img - * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.4.png"></a> - * - * @param w0 - * one source Observable - * @param w1 - * another source Observable - * @param w2 - * a third source Observable - * @param w3 - * a fourth source Observable - * @param function - * a closure that, when applied to an item emitted by each of the source Observables, - * results in a value that will be emitted by the resulting Observable - * @return a Observable that emits the zipped results - */ - public static <R, T0, T1, T2, T3> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Observable<T3> w3, final Object function) { - return zip(w0, w1, w2, w3, new Func4<R, T0, T1, T2, T3>() { - - @Override - public R call(T0 t0, T1 t1, T2 t2, T3 t3) { - return Functions.execute(function, t0, t1, t2, t3); - } - - }); - } - - public static class UnitTest { - @Mock - ScriptAssertion assertion; - - @Mock - Observer<Integer> w; - - @Before - public void before() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testReduce() { - Observable<Integer> Observable = toObservable(1, 2, 3, 4); - reduce(Observable, new Func2<Integer, Integer, Integer>() { - - @Override - public Integer call(Integer t1, Integer t2) { - return t1 + t2; - } - - }).subscribe(w); - // we should be called only once - verify(w, times(1)).onNext(anyInt()); - verify(w).onNext(10); - } - - @Test - public void testReduceWithInitialValue() { - Observable<Integer> Observable = toObservable(1, 2, 3, 4); - reduce(Observable, 50, new Func2<Integer, Integer, Integer>() { - - @Override - public Integer call(Integer t1, Integer t2) { - return t1 + t2; - } - - }).subscribe(w); - // we should be called only once - verify(w, times(1)).onNext(anyInt()); - verify(w).onNext(60); - } - - @Test - public void testCreateViaGroovy() { - runGroovyScript("o.create({it.onNext('hello');it.onCompleted();}).subscribe({ result -> a.received(result)});"); - verify(assertion, times(1)).received("hello"); - } - - @Test - public void testFilterViaGroovy() { - runGroovyScript("o.filter(o.toObservable(1, 2, 3), {it >= 2}).subscribe({ result -> a.received(result)});"); - verify(assertion, times(0)).received(1); - verify(assertion, times(1)).received(2); - verify(assertion, times(1)).received(3); - } - - @Test - public void testMapViaGroovy() { - runGroovyScript("o.map(o.toObservable(1, 2, 3), {'hello_' + it}).subscribe({ result -> a.received(result)});"); - verify(assertion, times(1)).received("hello_" + 1); - verify(assertion, times(1)).received("hello_" + 2); - verify(assertion, times(1)).received("hello_" + 3); - } - - @Test - public void testSkipViaGroovy() { - runGroovyScript("o.skip(o.toObservable(1, 2, 3), 2).subscribe({ result -> a.received(result)});"); - verify(assertion, times(0)).received(1); - verify(assertion, times(0)).received(2); - verify(assertion, times(1)).received(3); - } - - @Test - public void testTakeViaGroovy() { - runGroovyScript("o.take(o.toObservable(1, 2, 3), 2).subscribe({ result -> a.received(result)});"); - verify(assertion, times(1)).received(1); - verify(assertion, times(1)).received(2); - verify(assertion, times(0)).received(3); - } - - @Test - public void testSkipTakeViaGroovy() { - runGroovyScript("o.skip(o.toObservable(1, 2, 3), 1).take(1).subscribe({ result -> a.received(result)});"); - verify(assertion, times(0)).received(1); - verify(assertion, times(1)).received(2); - verify(assertion, times(0)).received(3); - } - - @Test - public void testMergeDelayErrorViaGroovy() { - runGroovyScript("o.mergeDelayError(o.toObservable(1, 2, 3), o.merge(o.toObservable(6), o.error(new NullPointerException()), o.toObservable(7)), o.toObservable(4, 5)).subscribe({ result -> a.received(result)}, { exception -> a.error(exception)});"); - verify(assertion, times(1)).received(1); - verify(assertion, times(1)).received(2); - verify(assertion, times(1)).received(3); - verify(assertion, times(1)).received(4); - verify(assertion, times(1)).received(5); - verify(assertion, times(1)).received(6); - verify(assertion, times(0)).received(7); - verify(assertion, times(1)).error(any(NullPointerException.class)); - } - - @Test - public void testMergeViaGroovy() { - runGroovyScript("o.merge(o.toObservable(1, 2, 3), o.merge(o.toObservable(6), o.error(new NullPointerException()), o.toObservable(7)), o.toObservable(4, 5)).subscribe({ result -> a.received(result)}, { exception -> a.error(exception)});"); - // executing synchronously so we can deterministically know what order things will come - verify(assertion, times(1)).received(1); - verify(assertion, times(1)).received(2); - verify(assertion, times(1)).received(3); - verify(assertion, times(0)).received(4); // the NPE will cause this sequence to be skipped - verify(assertion, times(0)).received(5); // the NPE will cause this sequence to be skipped - verify(assertion, times(1)).received(6); // this comes before the NPE so should exist - verify(assertion, times(0)).received(7);// this comes in the sequence after the NPE - verify(assertion, times(1)).error(any(NullPointerException.class)); - } - - @Test - public void testMaterializeViaGroovy() { - runGroovyScript("o.materialize(o.toObservable(1, 2, 3)).subscribe({ result -> a.received(result)});"); - // we expect 4 onNext calls: 3 for 1, 2, 3 ObservableNotification.OnNext and 1 for ObservableNotification.OnCompleted - verify(assertion, times(4)).received(any(Notification.class)); - verify(assertion, times(0)).error(any(Exception.class)); - } - - @Test - public void testToSortedList() { - runGroovyScript("o.toSortedList(o.toObservable(1, 3, 2, 5, 4)).subscribe({ result -> a.received(result)});"); - verify(assertion, times(1)).received(Arrays.asList(1, 2, 3, 4, 5)); - } - - @Test - public void testToSortedListWithFunction() { - runGroovyScript("o.toSortedList(o.toObservable(1, 3, 2, 5, 4), {a, b -> a - b}).subscribe({ result -> a.received(result)});"); - verify(assertion, times(1)).received(Arrays.asList(1, 2, 3, 4, 5)); - } - - private void runGroovyScript(String script) { - ClassLoader parent = getClass().getClassLoader(); - @SuppressWarnings("resource") - GroovyClassLoader loader = new GroovyClassLoader(parent); - - Binding binding = new Binding(); - binding.setVariable("a", assertion); - binding.setVariable("o", org.rx.operations.ObservableExtensions.class); - - /* parse the script and execute it */ - InvokerHelper.createScript(loader.parseClass(script), binding).run(); - } - - private static interface ScriptAssertion { - public void received(Object o); - - public void error(Exception o); - } - } -} diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationCombineLatest.java b/rxjava-core/src/main/java/org/rx/operations/OperationCombineLatest.java index d198939c0c..dc601e9568 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationCombineLatest.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationCombineLatest.java @@ -22,7 +22,7 @@ import org.rx.reactive.Observer; import org.rx.reactive.Subscription; -class OperationCombineLatest { +public class OperationCombineLatest { public static <R, T0, T1> Observable<R> combineLatest(Observable<T0> w0, Observable<T1> w1, Func2<R, T0, T1> combineLatestFunction) { Aggregator<R> a = new Aggregator<R>(Functions.fromFunc(combineLatestFunction)); @@ -652,7 +652,7 @@ public void testCombineLatest2Types() { /* define a Observer to receive aggregated events */ Observer<String> aObserver = mock(Observer.class); - Observable<String> w = combineLatest(ObservableExtensions.toObservable("one", "two"), ObservableExtensions.toObservable(2, 3, 4), combineLatestFunction); + Observable<String> w = combineLatest(Observable.toObservable("one", "two"), Observable.toObservable(2, 3, 4), combineLatestFunction); w.subscribe(aObserver); verify(aObserver, never()).onError(any(Exception.class)); @@ -671,7 +671,7 @@ public void testCombineLatest3TypesA() { /* define a Observer to receive aggregated events */ Observer<String> aObserver = mock(Observer.class); - Observable<String> w = combineLatest(ObservableExtensions.toObservable("one", "two"), ObservableExtensions.toObservable(2), ObservableExtensions.toObservable(new int[] { 4, 5, 6 }), combineLatestFunction); + Observable<String> w = combineLatest(Observable.toObservable("one", "two"), Observable.toObservable(2), Observable.toObservable(new int[] { 4, 5, 6 }), combineLatestFunction); w.subscribe(aObserver); verify(aObserver, never()).onError(any(Exception.class)); @@ -688,7 +688,7 @@ public void testCombineLatest3TypesB() { /* define a Observer to receive aggregated events */ Observer<String> aObserver = mock(Observer.class); - Observable<String> w = combineLatest(ObservableExtensions.toObservable("one"), ObservableExtensions.toObservable(2), ObservableExtensions.toObservable(new int[] { 4, 5, 6 }, new int[] { 7, 8 }), combineLatestFunction); + Observable<String> w = combineLatest(Observable.toObservable("one"), Observable.toObservable(2), Observable.toObservable(new int[] { 4, 5, 6 }, new int[] { 7, 8 }), combineLatestFunction); w.subscribe(aObserver); verify(aObserver, never()).onError(any(Exception.class)); @@ -781,7 +781,7 @@ private static class TestObservable extends Observable<String> { public Subscription subscribe(Observer<String> Observer) { // just store the variable where it can be accessed so we can manually trigger it this.Observer = Observer; - return ObservableExtensions.noOpSubscription(); + return Observable.noOpSubscription(); } } diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationFilter.java b/rxjava-core/src/main/java/org/rx/operations/OperationFilter.java index f91bccfe27..5421a0a0d4 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationFilter.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationFilter.java @@ -4,54 +4,63 @@ import static org.mockito.Mockito.*; import org.junit.Test; +import org.mockito.Mockito; import org.rx.functions.Func1; import org.rx.reactive.Observable; import org.rx.reactive.Observer; import org.rx.reactive.Subscription; -/* package */final class OperationFilter<T> extends Observable<T> { - private final Observable<T> that; - private final Func1<Boolean, T> predicate; +public final class OperationFilter<T> { - OperationFilter(Observable<T> that, Func1<Boolean, T> predicate) { - this.that = that; - this.predicate = predicate; + public static <T> Observable<T> filter(Observable<T> that, Func1<Boolean, T> predicate) { + return new Filter<T>(that, predicate); } - public Subscription subscribe(Observer<T> Observer) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + private static class Filter<T> extends Observable<T> { - subscription.setActual(that.subscribe(new Observer<T>() { - public void onNext(T value) { - try { - if ((boolean) predicate.call(value)) { - observer.onNext(value); + private final Observable<T> that; + private final Func1<Boolean, T> predicate; + + public Filter(Observable<T> that, Func1<Boolean, T> predicate) { + this.that = that; + this.predicate = predicate; + } + + public Subscription subscribe(Observer<T> Observer) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + + subscription.setActual(that.subscribe(new Observer<T>() { + public void onNext(T value) { + try { + if ((boolean) predicate.call(value)) { + observer.onNext(value); + } + } catch (Exception ex) { + observer.onError(ex); + subscription.unsubscribe(); } - } catch (Exception ex) { - observer.onError(ex); - subscription.unsubscribe(); } - } - public void onError(Exception ex) { - observer.onError(ex); - } + public void onError(Exception ex) { + observer.onError(ex); + } - public void onCompleted() { - observer.onCompleted(); - } - })); + public void onCompleted() { + observer.onCompleted(); + } + })); - return subscription; + return subscription; + } } public static class UnitTest { @Test public void testFilter() { - Observable<String> w = ObservableExtensions.toObservable("one", "two", "three"); - Observable<String> Observable = new OperationFilter<String>(w, new Func1<Boolean, String>() { + Observable<String> w = Observable.toObservable("one", "two", "three"); + Observable<String> Observable = filter(w, new Func1<Boolean, String>() { @Override public Boolean call(String t1) { @@ -65,10 +74,10 @@ public Boolean call(String t1) { @SuppressWarnings("unchecked") Observer<String> aObserver = mock(Observer.class); Observable.subscribe(aObserver); - verify(aObserver, never()).onNext("one"); + verify(aObserver, Mockito.never()).onNext("one"); verify(aObserver, times(1)).onNext("two"); - verify(aObserver, never()).onNext("three"); - verify(aObserver, never()).onError(any(Exception.class)); + verify(aObserver, Mockito.never()).onNext("three"); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); verify(aObserver, times(1)).onCompleted(); } } diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationLast.java b/rxjava-core/src/main/java/org/rx/operations/OperationLast.java index d83179b898..b412c1d76e 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationLast.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationLast.java @@ -7,6 +7,7 @@ import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; +import org.mockito.Mockito; import org.rx.reactive.Observable; import org.rx.reactive.Observer; import org.rx.reactive.Subscription; @@ -16,54 +17,62 @@ * * @param <T> */ -/* package */final class OperationLast<T> extends Observable<T> { - private final AtomicReference<T> lastValue = new AtomicReference<T>(); - private final Observable<T> that; - private final AtomicBoolean onNextCalled = new AtomicBoolean(false); +public final class OperationLast<T> { - OperationLast(Observable<T> that) { - this.that = that; + public static <T> Observable<T> last(Observable<T> observable) { + return new Last<T>(observable); } - public Subscription subscribe(final Observer<T> Observer) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + private static class Last<T> extends Observable<T> { - subscription.setActual(that.subscribe(new Observer<T>() { - public void onNext(T value) { - onNextCalled.set(true); - lastValue.set(value); - } + private final AtomicReference<T> lastValue = new AtomicReference<T>(); + private final Observable<T> that; + private final AtomicBoolean onNextCalled = new AtomicBoolean(false); - public void onError(Exception ex) { - observer.onError(ex); - } + public Last(Observable<T> that) { + this.that = that; + } + + public Subscription subscribe(final Observer<T> Observer) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + + subscription.setActual(that.subscribe(new Observer<T>() { + public void onNext(T value) { + onNextCalled.set(true); + lastValue.set(value); + } - public void onCompleted() { - if (onNextCalled.get()) { - observer.onNext(lastValue.get()); + public void onError(Exception ex) { + observer.onError(ex); } - observer.onCompleted(); - } - })); - return subscription; + public void onCompleted() { + if (onNextCalled.get()) { + observer.onNext(lastValue.get()); + } + observer.onCompleted(); + } + })); + + return subscription; + } } public static class UnitTest { @Test public void testLast() { - Observable<String> w = ObservableExtensions.toObservable("one", "two", "three"); - Observable<String> Observable = new OperationLast<String>(w); + Observable<String> w = Observable.toObservable("one", "two", "three"); + Observable<String> Observable = last(w); @SuppressWarnings("unchecked") Observer<String> aObserver = mock(Observer.class); Observable.subscribe(aObserver); - verify(aObserver, never()).onNext("one"); - verify(aObserver, never()).onNext("two"); + verify(aObserver, Mockito.never()).onNext("one"); + verify(aObserver, Mockito.never()).onNext("two"); verify(aObserver, times(1)).onNext("three"); - verify(aObserver, never()).onError(any(Exception.class)); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); verify(aObserver, times(1)).onCompleted(); } } diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationMap.java b/rxjava-core/src/main/java/org/rx/operations/OperationMap.java index 5834b6d89b..18b17ac762 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationMap.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationMap.java @@ -15,7 +15,7 @@ import org.rx.reactive.Observer; import org.rx.reactive.Subscription; -/* package */class OperationMap { +public final class OperationMap { /** * Accepts a sequence and a transformation function. Returns a sequence that is the result of @@ -130,7 +130,7 @@ public void testMap() { Map<String, String> m1 = getMap("One"); Map<String, String> m2 = getMap("Two"); @SuppressWarnings("unchecked") - Observable<Map<String, String>> observable = ObservableExtensions.toObservable(m1, m2); + Observable<Map<String, String>> observable = Observable.toObservable(m1, m2); Observable<String> m = map(observable, new Func1<String, Map<String, String>>() { @@ -152,7 +152,7 @@ public String call(Map<String, String> map) { @Test public void testMapMany() { /* simulate a top-level async call which returns IDs */ - Observable<Integer> ids = ObservableExtensions.toObservable(1, 2); + Observable<Integer> ids = Observable.toObservable(1, 2); /* now simulate the behavior to take those IDs and perform nested async calls based on them */ Observable<String> m = mapMany(ids, new Func1<Observable<String>, Integer>() { @@ -165,11 +165,11 @@ public Observable<String> call(Integer id) { if (id == 1) { Map<String, String> m1 = getMap("One"); Map<String, String> m2 = getMap("Two"); - subObservable = ObservableExtensions.toObservable(m1, m2); + subObservable = Observable.toObservable(m1, m2); } else { Map<String, String> m3 = getMap("Three"); Map<String, String> m4 = getMap("Four"); - subObservable = ObservableExtensions.toObservable(m3, m4); + subObservable = Observable.toObservable(m3, m4); } /* simulate kicking off the async call and performing a select on it to transform the data */ @@ -197,15 +197,15 @@ public void testMapMany2() { Map<String, String> m1 = getMap("One"); Map<String, String> m2 = getMap("Two"); @SuppressWarnings("unchecked") - Observable<Map<String, String>> observable1 = ObservableExtensions.toObservable(m1, m2); + Observable<Map<String, String>> observable1 = Observable.toObservable(m1, m2); Map<String, String> m3 = getMap("Three"); Map<String, String> m4 = getMap("Four"); @SuppressWarnings("unchecked") - Observable<Map<String, String>> observable2 = ObservableExtensions.toObservable(m3, m4); + Observable<Map<String, String>> observable2 = Observable.toObservable(m3, m4); @SuppressWarnings("unchecked") - Observable<Observable<Map<String, String>>> observable = ObservableExtensions.toObservable(observable1, observable2); + Observable<Observable<Map<String, String>>> observable = Observable.toObservable(observable1, observable2); Observable<String> m = mapMany(observable, new Func1<Observable<String>, Observable<Map<String, String>>>() { diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationMaterialize.java b/rxjava-core/src/main/java/org/rx/operations/OperationMaterialize.java index 85daa7cebe..0964829bf7 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationMaterialize.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationMaterialize.java @@ -18,7 +18,7 @@ * <p> * See http://msdn.microsoft.com/en-us/library/hh229453(v=VS.103).aspx for the Microsoft Rx equivalent. */ -public class OperationMaterialize { +public final class OperationMaterialize { /** * Materializes the implicit notifications of an observable sequence as explicit notification values. diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationMerge.java b/rxjava-core/src/main/java/org/rx/operations/OperationMerge.java index 4293218824..acd3106df6 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationMerge.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationMerge.java @@ -17,7 +17,7 @@ import org.rx.reactive.Observer; import org.rx.reactive.Subscription; -/* package */class OperationMerge { +public final class OperationMerge { /** * Flattens the observable sequences from the list of Observables into one observable sequence without any transformation. diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationMergeDelayError.java b/rxjava-core/src/main/java/org/rx/operations/OperationMergeDelayError.java index f7cb0c24df..da9c145aea 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationMergeDelayError.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationMergeDelayError.java @@ -27,7 +27,7 @@ * <p> * NOTE: If this is used on an infinite stream it will never call onError and effectively will swallow errors. */ -/* package */class OperationMergeDelayError { +public final class OperationMergeDelayError { /** * Flattens the observable sequences from the list of Observables into one observable sequence without any transformation and delays any onError calls until after all sequences have called diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaFunction.java b/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaFunction.java index f38c8737ef..82fff9ca2d 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaFunction.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaFunction.java @@ -8,76 +8,85 @@ import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; +import org.mockito.Mockito; import org.rx.functions.Func1; import org.rx.reactive.CompositeException; import org.rx.reactive.Observable; import org.rx.reactive.Observer; import org.rx.reactive.Subscription; -final class OperationOnErrorResumeNextViaFunction<T> extends Observable<T> { - private final Func1<Observable<T>, Exception> resumeFunction; - private final Observable<T> originalSequence; +public final class OperationOnErrorResumeNextViaFunction<T> { - OperationOnErrorResumeNextViaFunction(Observable<T> originalSequence, Func1<Observable<T>, Exception> resumeFunction) { - this.resumeFunction = resumeFunction; - this.originalSequence = originalSequence; + public static <T> Observable<T> onErrorResumeNextViaFunction(Observable<T> originalSequence, Func1<Observable<T>, Exception> resumeFunction) { + return new OnErrorResumeNextViaFunction<T>(originalSequence, resumeFunction); } - public Subscription subscribe(Observer<T> Observer) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + private static class OnErrorResumeNextViaFunction<T> extends Observable<T> { - // AtomicReference since we'll be accessing/modifying this across threads so we can switch it if needed - final AtomicReference<AtomicObservableSubscription> subscriptionRef = new AtomicReference<AtomicObservableSubscription>(subscription); + private final Func1<Observable<T>, Exception> resumeFunction; + private final Observable<T> originalSequence; - // subscribe to the original Observable and remember the subscription - subscription.setActual(originalSequence.subscribe(new Observer<T>() { - public void onNext(T value) { - // forward the successful calls - observer.onNext(value); - } + public OnErrorResumeNextViaFunction(Observable<T> originalSequence, Func1<Observable<T>, Exception> resumeFunction) { + this.resumeFunction = resumeFunction; + this.originalSequence = originalSequence; + } + + public Subscription subscribe(Observer<T> Observer) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + + // AtomicReference since we'll be accessing/modifying this across threads so we can switch it if needed + final AtomicReference<AtomicObservableSubscription> subscriptionRef = new AtomicReference<AtomicObservableSubscription>(subscription); - /** - * Instead of passing the onError forward, we intercept and "resume" with the resumeSequence. - */ - public void onError(Exception ex) { - /* remember what the current subscription is so we can determine if someone unsubscribes concurrently */ - AtomicObservableSubscription currentSubscription = subscriptionRef.get(); - // check that we have not been unsubscribed before we can process the error - if (currentSubscription != null) { - try { - Observable<T> resumeSequence = resumeFunction.call(ex); - /* error occurred, so switch subscription to the 'resumeSequence' */ - AtomicObservableSubscription innerSubscription = new AtomicObservableSubscription(resumeSequence.subscribe(observer)); - /* we changed the sequence, so also change the subscription to the one of the 'resumeSequence' instead */ - if (!subscriptionRef.compareAndSet(currentSubscription, innerSubscription)) { - // we failed to set which means 'subscriptionRef' was set to NULL via the unsubscribe below - // so we want to immediately unsubscribe from the resumeSequence we just subscribed to - innerSubscription.unsubscribe(); + // subscribe to the original Observable and remember the subscription + subscription.setActual(originalSequence.subscribe(new Observer<T>() { + public void onNext(T value) { + // forward the successful calls + observer.onNext(value); + } + + /** + * Instead of passing the onError forward, we intercept and "resume" with the resumeSequence. + */ + public void onError(Exception ex) { + /* remember what the current subscription is so we can determine if someone unsubscribes concurrently */ + AtomicObservableSubscription currentSubscription = subscriptionRef.get(); + // check that we have not been unsubscribed before we can process the error + if (currentSubscription != null) { + try { + Observable<T> resumeSequence = resumeFunction.call(ex); + /* error occurred, so switch subscription to the 'resumeSequence' */ + AtomicObservableSubscription innerSubscription = new AtomicObservableSubscription(resumeSequence.subscribe(observer)); + /* we changed the sequence, so also change the subscription to the one of the 'resumeSequence' instead */ + if (!subscriptionRef.compareAndSet(currentSubscription, innerSubscription)) { + // we failed to set which means 'subscriptionRef' was set to NULL via the unsubscribe below + // so we want to immediately unsubscribe from the resumeSequence we just subscribed to + innerSubscription.unsubscribe(); + } + } catch (Exception e) { + // the resume function failed so we need to call onError + // I am using CompositeException so that both exceptions can be seen + observer.onError(new CompositeException("OnErrorResume function failed", Arrays.asList(ex, e))); } - } catch (Exception e) { - // the resume function failed so we need to call onError - // I am using CompositeException so that both exceptions can be seen - observer.onError(new CompositeException("OnErrorResume function failed", Arrays.asList(ex, e))); } } - } - public void onCompleted() { - // forward the successful calls - observer.onCompleted(); - } - })); - - return new Subscription() { - public void unsubscribe() { - // this will get either the original, or the resumeSequence one and unsubscribe on it - Subscription s = subscriptionRef.getAndSet(null); - if (s != null) { - s.unsubscribe(); + public void onCompleted() { + // forward the successful calls + observer.onCompleted(); } - } - }; + })); + + return new Subscription() { + public void unsubscribe() { + // this will get either the original, or the resumeSequence one and unsubscribe on it + Subscription s = subscriptionRef.getAndSet(null); + if (s != null) { + s.unsubscribe(); + } + } + }; + } } public static class UnitTest { @@ -92,11 +101,11 @@ public void testResumeNext() { @Override public Observable<String> call(Exception t1) { receivedException.set(t1); - return ObservableExtensions.toObservable("twoResume", "threeResume"); + return Observable.toObservable("twoResume", "threeResume"); } }; - Observable<String> Observable = new OperationOnErrorResumeNextViaFunction<String>(w, resume); + Observable<String> Observable = onErrorResumeNextViaFunction(w, resume); @SuppressWarnings("unchecked") Observer<String> aObserver = mock(Observer.class); @@ -108,11 +117,11 @@ public Observable<String> call(Exception t1) { fail(e.getMessage()); } - verify(aObserver, never()).onError(any(Exception.class)); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); verify(aObserver, times(1)).onCompleted(); verify(aObserver, times(1)).onNext("one"); - verify(aObserver, never()).onNext("two"); - verify(aObserver, never()).onNext("three"); + verify(aObserver, Mockito.never()).onNext("two"); + verify(aObserver, Mockito.never()).onNext("three"); verify(aObserver, times(1)).onNext("twoResume"); verify(aObserver, times(1)).onNext("threeResume"); assertNotNull(receivedException.get()); @@ -133,7 +142,7 @@ public Observable<String> call(Exception t1) { } }; - Observable<String> Observable = new OperationOnErrorResumeNextViaFunction<String>(w, resume); + Observable<String> Observable = onErrorResumeNextViaFunction(w, resume); @SuppressWarnings("unchecked") Observer<String> aObserver = mock(Observer.class); diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaObservable.java b/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaObservable.java new file mode 100644 index 0000000000..9311d5381d --- /dev/null +++ b/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaObservable.java @@ -0,0 +1,150 @@ +package org.rx.operations; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.mockito.Mockito; +import org.rx.reactive.Observable; +import org.rx.reactive.Observer; +import org.rx.reactive.Subscription; + +public final class OperationOnErrorResumeNextViaObservable<T> { + + public static <T> Observable<T> onErrorResumeNextViaObservable(Observable<T> originalSequence, Observable<T> resumeSequence) { + return new OnErrorResumeNextViaObservable<T>(originalSequence, resumeSequence); + } + + private static class OnErrorResumeNextViaObservable<T> extends Observable<T> { + + private final Observable<T> resumeSequence; + private final Observable<T> originalSequence; + + public OnErrorResumeNextViaObservable(Observable<T> originalSequence, Observable<T> resumeSequence) { + this.resumeSequence = resumeSequence; + this.originalSequence = originalSequence; + } + + public Subscription subscribe(Observer<T> Observer) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + + // AtomicReference since we'll be accessing/modifying this across threads so we can switch it if needed + final AtomicReference<AtomicObservableSubscription> subscriptionRef = new AtomicReference<AtomicObservableSubscription>(subscription); + + // subscribe to the original Observable and remember the subscription + subscription.setActual(originalSequence.subscribe(new Observer<T>() { + public void onNext(T value) { + // forward the successful calls + observer.onNext(value); + } + + /** + * Instead of passing the onError forward, we intercept and "resume" with the resumeSequence. + */ + public void onError(Exception ex) { + /* remember what the current subscription is so we can determine if someone unsubscribes concurrently */ + AtomicObservableSubscription currentSubscription = subscriptionRef.get(); + // check that we have not been unsubscribed before we can process the error + if (currentSubscription != null) { + /* error occurred, so switch subscription to the 'resumeSequence' */ + AtomicObservableSubscription innerSubscription = new AtomicObservableSubscription(resumeSequence.subscribe(observer)); + /* we changed the sequence, so also change the subscription to the one of the 'resumeSequence' instead */ + if (!subscriptionRef.compareAndSet(currentSubscription, innerSubscription)) { + // we failed to set which means 'subscriptionRef' was set to NULL via the unsubscribe below + // so we want to immediately unsubscribe from the resumeSequence we just subscribed to + innerSubscription.unsubscribe(); + } + } + } + + public void onCompleted() { + // forward the successful calls + observer.onCompleted(); + } + })); + + return new Subscription() { + public void unsubscribe() { + // this will get either the original, or the resumeSequence one and unsubscribe on it + Subscription s = subscriptionRef.getAndSet(null); + if (s != null) { + s.unsubscribe(); + } + } + }; + } + } + + public static class UnitTest { + + @Test + public void testResumeNext() { + Subscription s = mock(Subscription.class); + TestObservable w = new TestObservable(s, "one"); + Observable<String> resume = Observable.toObservable("twoResume", "threeResume"); + Observable<String> Observable = onErrorResumeNextViaObservable(w, resume); + + @SuppressWarnings("unchecked") + Observer<String> aObserver = mock(Observer.class); + Observable.subscribe(aObserver); + + try { + w.t.join(); + } catch (InterruptedException e) { + fail(e.getMessage()); + } + + verify(aObserver, Mockito.never()).onError(any(Exception.class)); + verify(aObserver, times(1)).onCompleted(); + verify(aObserver, times(1)).onNext("one"); + verify(aObserver, Mockito.never()).onNext("two"); + verify(aObserver, Mockito.never()).onNext("three"); + verify(aObserver, times(1)).onNext("twoResume"); + verify(aObserver, times(1)).onNext("threeResume"); + + } + + private static class TestObservable extends Observable<String> { + + final Subscription s; + final String[] values; + Thread t = null; + + public TestObservable(Subscription s, String... values) { + this.s = s; + this.values = values; + } + + @Override + public Subscription subscribe(final Observer<String> observer) { + System.out.println("TestObservable subscribed to ..."); + t = new Thread(new Runnable() { + + @Override + public void run() { + try { + System.out.println("running TestObservable thread"); + for (String s : values) { + System.out.println("TestObservable onNext: " + s); + observer.onNext(s); + } + throw new RuntimeException("Forced Failure"); + } catch (Exception e) { + observer.onError(e); + } + } + + }); + System.out.println("starting TestObservable thread"); + t.start(); + System.out.println("done starting TestObservable thread"); + return s; + } + + } + } +} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaWatchable.java b/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaWatchable.java deleted file mode 100644 index dd2e5e3771..0000000000 --- a/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorResumeNextViaWatchable.java +++ /dev/null @@ -1,141 +0,0 @@ -package org.rx.operations; - -import static org.junit.Assert.*; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; - -import java.util.concurrent.atomic.AtomicReference; - -import org.junit.Test; -import org.rx.reactive.Observable; -import org.rx.reactive.Observer; -import org.rx.reactive.Subscription; - -final class OperationOnErrorResumeNextViaObservable<T> extends Observable<T> { - private final Observable<T> resumeSequence; - private final Observable<T> originalSequence; - - OperationOnErrorResumeNextViaObservable(Observable<T> originalSequence, Observable<T> resumeSequence) { - this.resumeSequence = resumeSequence; - this.originalSequence = originalSequence; - } - - public Subscription subscribe(Observer<T> Observer) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); - - // AtomicReference since we'll be accessing/modifying this across threads so we can switch it if needed - final AtomicReference<AtomicObservableSubscription> subscriptionRef = new AtomicReference<AtomicObservableSubscription>(subscription); - - // subscribe to the original Observable and remember the subscription - subscription.setActual(originalSequence.subscribe(new Observer<T>() { - public void onNext(T value) { - // forward the successful calls - observer.onNext(value); - } - - /** - * Instead of passing the onError forward, we intercept and "resume" with the resumeSequence. - */ - public void onError(Exception ex) { - /* remember what the current subscription is so we can determine if someone unsubscribes concurrently */ - AtomicObservableSubscription currentSubscription = subscriptionRef.get(); - // check that we have not been unsubscribed before we can process the error - if (currentSubscription != null) { - /* error occurred, so switch subscription to the 'resumeSequence' */ - AtomicObservableSubscription innerSubscription = new AtomicObservableSubscription(resumeSequence.subscribe(observer)); - /* we changed the sequence, so also change the subscription to the one of the 'resumeSequence' instead */ - if (!subscriptionRef.compareAndSet(currentSubscription, innerSubscription)) { - // we failed to set which means 'subscriptionRef' was set to NULL via the unsubscribe below - // so we want to immediately unsubscribe from the resumeSequence we just subscribed to - innerSubscription.unsubscribe(); - } - } - } - - public void onCompleted() { - // forward the successful calls - observer.onCompleted(); - } - })); - - return new Subscription() { - public void unsubscribe() { - // this will get either the original, or the resumeSequence one and unsubscribe on it - Subscription s = subscriptionRef.getAndSet(null); - if (s != null) { - s.unsubscribe(); - } - } - }; - } - - public static class UnitTest { - - @Test - public void testResumeNext() { - Subscription s = mock(Subscription.class); - TestObservable w = new TestObservable(s, "one"); - Observable<String> resume = ObservableExtensions.toObservable("twoResume", "threeResume"); - Observable<String> Observable = new OperationOnErrorResumeNextViaObservable<String>(w, resume); - - @SuppressWarnings("unchecked") - Observer<String> aObserver = mock(Observer.class); - Observable.subscribe(aObserver); - - try { - w.t.join(); - } catch (InterruptedException e) { - fail(e.getMessage()); - } - - verify(aObserver, never()).onError(any(Exception.class)); - verify(aObserver, times(1)).onCompleted(); - verify(aObserver, times(1)).onNext("one"); - verify(aObserver, never()).onNext("two"); - verify(aObserver, never()).onNext("three"); - verify(aObserver, times(1)).onNext("twoResume"); - verify(aObserver, times(1)).onNext("threeResume"); - - } - - private static class TestObservable extends Observable<String> { - - final Subscription s; - final String[] values; - Thread t = null; - - public TestObservable(Subscription s, String... values) { - this.s = s; - this.values = values; - } - - @Override - public Subscription subscribe(final Observer<String> observer) { - System.out.println("TestObservable subscribed to ..."); - t = new Thread(new Runnable() { - - @Override - public void run() { - try { - System.out.println("running TestObservable thread"); - for (String s : values) { - System.out.println("TestObservable onNext: " + s); - observer.onNext(s); - } - throw new RuntimeException("Forced Failure"); - } catch (Exception e) { - observer.onError(e); - } - } - - }); - System.out.println("starting TestObservable thread"); - t.start(); - System.out.println("done starting TestObservable thread"); - return s; - } - - } - } -} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorReturn.java b/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorReturn.java index 7eb7d5b222..6ab27e6aa1 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorReturn.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationOnErrorReturn.java @@ -8,6 +8,7 @@ import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; +import org.mockito.Mockito; import org.rx.functions.Func1; import org.rx.reactive.CompositeException; import org.rx.reactive.Observable; @@ -17,75 +18,82 @@ /** * When an onError occurs the resumeFunction will be executed and it's response passed to onNext instead of calling onError. */ -final class OperationOnErrorReturn<T> extends Observable<T> { - private final Func1<T, Exception> resumeFunction; - private final Observable<T> originalSequence; +public final class OperationOnErrorReturn<T> { - OperationOnErrorReturn(Observable<T> originalSequence, Func1<T, Exception> resumeFunction) { - this.resumeFunction = resumeFunction; - this.originalSequence = originalSequence; + public static <T> Observable<T> onErrorReturn(Observable<T> originalSequence, Func1<T, Exception> resumeFunction) { + return new OnErrorReturn<T>(originalSequence, resumeFunction); } - public Subscription subscribe(Observer<T> Observer) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + private static class OnErrorReturn<T> extends Observable<T> { + private final Func1<T, Exception> resumeFunction; + private final Observable<T> originalSequence; - // AtomicReference since we'll be accessing/modifying this across threads so we can switch it if needed - final AtomicReference<AtomicObservableSubscription> subscriptionRef = new AtomicReference<AtomicObservableSubscription>(subscription); + public OnErrorReturn(Observable<T> originalSequence, Func1<T, Exception> resumeFunction) { + this.resumeFunction = resumeFunction; + this.originalSequence = originalSequence; + } - // subscribe to the original Observable and remember the subscription - subscription.setActual(originalSequence.subscribe(new Observer<T>() { - public void onNext(T value) { - // forward the successful calls - observer.onNext(value); - } + public Subscription subscribe(Observer<T> Observer) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); - /** - * Instead of passing the onError forward, we intercept and "resume" with the resumeSequence. - */ - public void onError(Exception ex) { - /* remember what the current subscription is so we can determine if someone unsubscribes concurrently */ - AtomicObservableSubscription currentSubscription = subscriptionRef.get(); - // check that we have not been unsubscribed before we can process the error - if (currentSubscription != null) { - try { - /* error occurred, so execute the function, give it the exception and call onNext with the response */ - onNext(resumeFunction.call(ex)); - /* - * we are not handling an exception thrown from this function ... should we do something? - * error handling within an error handler is a weird one to determine what we should do - * right now I'm going to just let it throw whatever exceptions occur (such as NPE) - * but I'm considering calling the original Observer.onError to act as if this OnErrorReturn operator didn't happen - */ - - /* we are now completed */ - onCompleted(); - - /* unsubscribe since it blew up */ - currentSubscription.unsubscribe(); - } catch (Exception e) { - // the return function failed so we need to call onError - // I am using CompositeException so that both exceptions can be seen - observer.onError(new CompositeException("OnErrorReturn function failed", Arrays.asList(ex, e))); + // AtomicReference since we'll be accessing/modifying this across threads so we can switch it if needed + final AtomicReference<AtomicObservableSubscription> subscriptionRef = new AtomicReference<AtomicObservableSubscription>(subscription); + + // subscribe to the original Observable and remember the subscription + subscription.setActual(originalSequence.subscribe(new Observer<T>() { + public void onNext(T value) { + // forward the successful calls + observer.onNext(value); + } + + /** + * Instead of passing the onError forward, we intercept and "resume" with the resumeSequence. + */ + public void onError(Exception ex) { + /* remember what the current subscription is so we can determine if someone unsubscribes concurrently */ + AtomicObservableSubscription currentSubscription = subscriptionRef.get(); + // check that we have not been unsubscribed before we can process the error + if (currentSubscription != null) { + try { + /* error occurred, so execute the function, give it the exception and call onNext with the response */ + onNext(resumeFunction.call(ex)); + /* + * we are not handling an exception thrown from this function ... should we do something? + * error handling within an error handler is a weird one to determine what we should do + * right now I'm going to just let it throw whatever exceptions occur (such as NPE) + * but I'm considering calling the original Observer.onError to act as if this OnErrorReturn operator didn't happen + */ + + /* we are now completed */ + onCompleted(); + + /* unsubscribe since it blew up */ + currentSubscription.unsubscribe(); + } catch (Exception e) { + // the return function failed so we need to call onError + // I am using CompositeException so that both exceptions can be seen + observer.onError(new CompositeException("OnErrorReturn function failed", Arrays.asList(ex, e))); + } } } - } - public void onCompleted() { - // forward the successful calls - observer.onCompleted(); - } - })); - - return new Subscription() { - public void unsubscribe() { - // this will get either the original, or the resumeSequence one and unsubscribe on it - Subscription s = subscriptionRef.getAndSet(null); - if (s != null) { - s.unsubscribe(); + public void onCompleted() { + // forward the successful calls + observer.onCompleted(); } - } - }; + })); + + return new Subscription() { + public void unsubscribe() { + // this will get either the original, or the resumeSequence one and unsubscribe on it + Subscription s = subscriptionRef.getAndSet(null); + if (s != null) { + s.unsubscribe(); + } + } + }; + } } public static class UnitTest { @@ -96,7 +104,7 @@ public void testResumeNext() { TestObservable w = new TestObservable(s, "one"); final AtomicReference<Exception> capturedException = new AtomicReference<Exception>(); - Observable<String> Observable = new OperationOnErrorReturn<String>(w, new Func1<String, Exception>() { + Observable<String> Observable = onErrorReturn(w, new Func1<String, Exception>() { @Override public String call(Exception e) { @@ -116,7 +124,7 @@ public String call(Exception e) { fail(e.getMessage()); } - verify(aObserver, never()).onError(any(Exception.class)); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); verify(aObserver, times(1)).onCompleted(); verify(aObserver, times(1)).onNext("one"); verify(aObserver, times(1)).onNext("failure"); @@ -132,7 +140,7 @@ public void testFunctionThrowsError() { TestObservable w = new TestObservable(s, "one"); final AtomicReference<Exception> capturedException = new AtomicReference<Exception>(); - Observable<String> Observable = new OperationOnErrorReturn<String>(w, new Func1<String, Exception>() { + Observable<String> Observable = onErrorReturn(w, new Func1<String, Exception>() { @Override public String call(Exception e) { diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationScan.java b/rxjava-core/src/main/java/org/rx/operations/OperationScan.java index 6aa1934a87..2fc34b6dc3 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationScan.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationScan.java @@ -11,7 +11,7 @@ import org.rx.reactive.Observer; import org.rx.reactive.Subscription; -/* package */class OperationScan { +public final class OperationScan { /** * Applies an accumulator function over an observable sequence and returns each intermediate result with the specified source and accumulator. * @@ -129,7 +129,7 @@ public void testScanIntegersWithInitialValue() { @SuppressWarnings("unchecked") Observer<Integer> Observer = mock(Observer.class); - Observable<Integer> observable = ObservableExtensions.toObservable(1, 2, 3); + Observable<Integer> observable = Observable.toObservable(1, 2, 3); Observable<Integer> m = scan(observable, 0, new Func2<Integer, Integer, Integer>() { @@ -156,7 +156,7 @@ public void testScanIntegersWithoutInitialValue() { @SuppressWarnings("unchecked") Observer<Integer> Observer = mock(Observer.class); - Observable<Integer> observable = ObservableExtensions.toObservable(1, 2, 3); + Observable<Integer> observable = Observable.toObservable(1, 2, 3); Observable<Integer> m = scan(observable, new Func2<Integer, Integer, Integer>() { @@ -183,7 +183,7 @@ public void testScanIntegersWithoutInitialValueAndOnlyOneValue() { @SuppressWarnings("unchecked") Observer<Integer> Observer = mock(Observer.class); - Observable<Integer> observable = ObservableExtensions.toObservable(1); + Observable<Integer> observable = Observable.toObservable(1); Observable<Integer> m = scan(observable, new Func2<Integer, Integer, Integer>() { diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationSkip.java b/rxjava-core/src/main/java/org/rx/operations/OperationSkip.java index 419ae53ca6..45394989fa 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationSkip.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationSkip.java @@ -15,7 +15,7 @@ * * @param <T> */ -/* package */final class OperationSkip { +public final class OperationSkip { /** * Skips a specified number of contiguous values from the start of a Observable sequence and then returns the remaining values. @@ -102,7 +102,7 @@ public static class UnitTest { @Test public void testSkip1() { - Observable<String> w = ObservableExtensions.toObservable("one", "two", "three"); + Observable<String> w = Observable.toObservable("one", "two", "three"); Observable<String> skip = skip(w, 2); @SuppressWarnings("unchecked") @@ -117,7 +117,7 @@ public void testSkip1() { @Test public void testSkip2() { - Observable<String> w = ObservableExtensions.toObservable("one", "two", "three"); + Observable<String> w = Observable.toObservable("one", "two", "three"); Observable<String> skip = skip(w, 1); @SuppressWarnings("unchecked") diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationSynchronize.java b/rxjava-core/src/main/java/org/rx/operations/OperationSynchronize.java index 439f59f09c..a96d02ddbc 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationSynchronize.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationSynchronize.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.*; import org.junit.Test; +import org.mockito.Mockito; import org.rx.reactive.Observable; import org.rx.reactive.Observer; import org.rx.reactive.Subscription; @@ -19,7 +20,7 @@ * @param <T> * The type of the observable sequence. */ -/* package */class OperationSynchronize<T> extends Observable<T> { +public final class OperationSynchronize<T> { /** * Accepts an observable and wraps it in another observable which ensures that the resulting observable is well-behaved. @@ -33,21 +34,25 @@ * @return */ public static <T> Observable<T> synchronize(Observable<T> observable) { - return new OperationSynchronize<T>(observable); + return new Synchronize<T>(observable); } - public OperationSynchronize(Observable<T> innerObservable) { - this.innerObservable = innerObservable; - } + private static class Synchronize<T> extends Observable<T> { + + public Synchronize(Observable<T> innerObservable) { + this.innerObservable = innerObservable; + } - private Observable<T> innerObservable; - private AtomicObserver<T> atomicObserver; + private Observable<T> innerObservable; + private AtomicObserverSingleThreaded<T> atomicObserver; + + public Subscription subscribe(Observer<T> observer) { + AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + atomicObserver = new AtomicObserverSingleThreaded<T>(observer, subscription); + subscription.setActual(innerObservable.subscribe(atomicObserver)); + return subscription; + } - public Subscription subscribe(Observer<T> Observer) { - AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - atomicObserver = new AtomicObserver<T>(Observer, subscription); - subscription.setActual(innerObservable.subscribe(atomicObserver)); - return subscription; } public static class UnitTest { @@ -69,7 +74,7 @@ public void testOnCompletedAfterUnSubscribe() { t.sendOnCompleted(); verify(w, times(1)).onNext("one"); - verify(w, never()).onCompleted(); + verify(w, Mockito.never()).onCompleted(); } /** @@ -89,7 +94,7 @@ public void testOnNextAfterUnSubscribe() { t.sendOnNext("two"); verify(w, times(1)).onNext("one"); - verify(w, never()).onNext("two"); + verify(w, Mockito.never()).onNext("two"); } /** @@ -109,7 +114,7 @@ public void testOnErrorAfterUnSubscribe() { t.sendOnError(new RuntimeException("bad")); verify(w, times(1)).onNext("one"); - verify(w, never()).onError(any(Exception.class)); + verify(w, Mockito.never()).onError(any(Exception.class)); } /** @@ -131,7 +136,7 @@ public void testOnNextAfterOnError() { verify(w, times(1)).onNext("one"); verify(w, times(1)).onError(any(Exception.class)); - verify(w, never()).onNext("two"); + verify(w, Mockito.never()).onNext("two"); } /** @@ -153,7 +158,7 @@ public void testOnCompletedAfterOnError() { verify(w, times(1)).onNext("one"); verify(w, times(1)).onError(any(Exception.class)); - verify(w, never()).onCompleted(); + verify(w, Mockito.never()).onCompleted(); } /** @@ -174,9 +179,9 @@ public void testOnNextAfterOnCompleted() { t.sendOnNext("two"); verify(w, times(1)).onNext("one"); - verify(w, never()).onNext("two"); + verify(w, Mockito.never()).onNext("two"); verify(w, times(1)).onCompleted(); - verify(w, never()).onError(any(Exception.class)); + verify(w, Mockito.never()).onError(any(Exception.class)); } /** @@ -198,7 +203,7 @@ public void testOnErrorAfterOnCompleted() { verify(w, times(1)).onNext("one"); verify(w, times(1)).onCompleted(); - verify(w, never()).onError(any(Exception.class)); + verify(w, Mockito.never()).onError(any(Exception.class)); } /** diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationTake.java b/rxjava-core/src/main/java/org/rx/operations/OperationTake.java index 583cb7fb77..13aed147ad 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationTake.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationTake.java @@ -16,7 +16,7 @@ * * @param <T> */ -/* package */final class OperationTake { +public final class OperationTake { /** * Returns a specified number of contiguous values from the start of an observable sequence. @@ -108,7 +108,7 @@ public static class UnitTest { @Test public void testTake1() { - Observable<String> w = ObservableExtensions.toObservable("one", "two", "three"); + Observable<String> w = Observable.toObservable("one", "two", "three"); Observable<String> take = take(w, 2); @SuppressWarnings("unchecked") @@ -123,7 +123,7 @@ public void testTake1() { @Test public void testTake2() { - Observable<String> w = ObservableExtensions.toObservable("one", "two", "three"); + Observable<String> w = Observable.toObservable("one", "two", "three"); Observable<String> take = take(w, 1); @SuppressWarnings("unchecked") diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationToObservableFunction.java b/rxjava-core/src/main/java/org/rx/operations/OperationToObservableFunction.java new file mode 100644 index 0000000000..cfa2501caa --- /dev/null +++ b/rxjava-core/src/main/java/org/rx/operations/OperationToObservableFunction.java @@ -0,0 +1,77 @@ +package org.rx.operations; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + +import org.junit.Test; +import org.mockito.Mockito; +import org.rx.functions.Func1; +import org.rx.reactive.Observable; +import org.rx.reactive.Observer; +import org.rx.reactive.Subscription; + +/** + * Accepts a Function and makes it into a Observable. + * <p> + * This is equivalent to Rx Observable.Create + * + * @see http://msdn.microsoft.com/en-us/library/hh229114(v=vs.103).aspx + * @see Observable.toObservable + * @see Observable.create + */ +public final class OperationToObservableFunction<T> { + + public static <T> Observable<T> toObservableFunction(Func1<Subscription, Observer<T>> func) { + return new ToObservableFunction<T>(func); + } + + private static class ToObservableFunction<T> extends Observable<T> { + private final Func1<Subscription, Observer<T>> func; + + public ToObservableFunction(Func1<Subscription, Observer<T>> func) { + this.func = func; + } + + @Override + public Subscription subscribe(Observer<T> Observer) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + // We specifically use the SingleThreaded AtomicObserver since we can't ensure the implementation is thread-safe + // so will not allow it to use the MultiThreaded version even when other operators are doing so + final Observer<T> atomicObserver = new AtomicObserverSingleThreaded<T>(Observer, subscription); + // if func.call is synchronous, then the subscription won't matter as it can't ever be called + // if func.call is asynchronous, then the subscription will get set and can be unsubscribed from + subscription.setActual(func.call(atomicObserver)); + + return subscription; + } + } + + public static class UnitTest { + + @Test + public void testCreate() { + + Observable<String> observable = toObservableFunction(new Func1<Subscription, Observer<String>>() { + + @Override + public Subscription call(Observer<String> Observer) { + Observer.onNext("one"); + Observer.onNext("two"); + Observer.onNext("three"); + Observer.onCompleted(); + return Observable.noOpSubscription(); + } + + }); + + @SuppressWarnings("unchecked") + Observer<String> aObserver = mock(Observer.class); + observable.subscribe(aObserver); + verify(aObserver, times(1)).onNext("one"); + verify(aObserver, times(1)).onNext("two"); + verify(aObserver, times(1)).onNext("three"); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); + verify(aObserver, times(1)).onCompleted(); + } + } +} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationToObservableIterable.java b/rxjava-core/src/main/java/org/rx/operations/OperationToObservableIterable.java new file mode 100644 index 0000000000..a462b5ee95 --- /dev/null +++ b/rxjava-core/src/main/java/org/rx/operations/OperationToObservableIterable.java @@ -0,0 +1,62 @@ +package org.rx.operations; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + +import java.util.Arrays; + +import org.junit.Test; +import org.mockito.Mockito; +import org.rx.reactive.Observable; +import org.rx.reactive.Observer; +import org.rx.reactive.Subscription; + +/** + * Accepts an Iterable object and exposes it as an Observable. + * + * @param <T> + * The type of the Iterable sequence. + */ +public final class OperationToObservableIterable<T> { + + public static <T> Observable<T> toObservableIterable(Iterable<T> list) { + return new ToObservableIterable<T>(list); + } + + private static class ToObservableIterable<T> extends Observable<T> { + public ToObservableIterable(Iterable<T> list) { + this.iterable = list; + } + + public Iterable<T> iterable; + + public Subscription subscribe(Observer<T> Observer) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(Observable.noOpSubscription()); + final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); + + for (T item : iterable) { + observer.onNext(item); + } + observer.onCompleted(); + + return subscription; + } + } + + public static class UnitTest { + + @Test + public void testIterable() { + Observable<String> Observable = toObservableIterable(Arrays.<String> asList("one", "two", "three")); + + @SuppressWarnings("unchecked") + Observer<String> aObserver = mock(Observer.class); + Observable.subscribe(aObserver); + verify(aObserver, times(1)).onNext("one"); + verify(aObserver, times(1)).onNext("two"); + verify(aObserver, times(1)).onNext("three"); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); + verify(aObserver, times(1)).onCompleted(); + } + } +} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationToObservableList.java b/rxjava-core/src/main/java/org/rx/operations/OperationToObservableList.java new file mode 100644 index 0000000000..e8ac558d92 --- /dev/null +++ b/rxjava-core/src/main/java/org/rx/operations/OperationToObservableList.java @@ -0,0 +1,84 @@ +package org.rx.operations; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.junit.Test; +import org.mockito.Mockito; +import org.rx.reactive.Observable; +import org.rx.reactive.Observer; +import org.rx.reactive.Subscription; + +public final class OperationToObservableList<T> { + + public static <T> Observable<List<T>> toObservableList(Observable<T> that) { + return new ToObservableList<T>(that); + } + + private static class ToObservableList<T> extends Observable<List<T>> { + + private final Observable<T> that; + final ConcurrentLinkedQueue<T> list = new ConcurrentLinkedQueue<T>(); + + public ToObservableList(Observable<T> that) { + this.that = that; + } + + public Subscription subscribe(Observer<List<T>> listObserver) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + final Observer<List<T>> Observer = new AtomicObserver<List<T>>(listObserver, subscription); + + subscription.setActual(that.subscribe(new Observer<T>() { + public void onNext(T value) { + // onNext can be concurrently executed so list must be thread-safe + list.add(value); + } + + public void onError(Exception ex) { + Observer.onError(ex); + } + + public void onCompleted() { + try { + // copy from LinkedQueue to List since ConcurrentLinkedQueue does not implement the List interface + ArrayList<T> l = new ArrayList<T>(list.size()); + for (T t : list) { + l.add(t); + } + + // benjchristensen => I want to make this immutable but some clients are sorting this + // instead of using toSortedList() and this change breaks them until we migrate their code. + // Observer.onNext(Collections.unmodifiableList(l)); + Observer.onNext(l); + Observer.onCompleted(); + } catch (Exception e) { + onError(e); + } + + } + })); + return subscription; + } + } + + public static class UnitTest { + + @Test + public void testList() { + Observable<String> w = Observable.toObservable("one", "two", "three"); + Observable<List<String>> Observable = toObservableList(w); + + @SuppressWarnings("unchecked") + Observer<List<String>> aObserver = mock(Observer.class); + Observable.subscribe(aObserver); + verify(aObserver, times(1)).onNext(Arrays.asList("one", "two", "three")); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); + verify(aObserver, times(1)).onCompleted(); + } + } +} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationToObservableSortedList.java b/rxjava-core/src/main/java/org/rx/operations/OperationToObservableSortedList.java new file mode 100644 index 0000000000..29e5f4ed67 --- /dev/null +++ b/rxjava-core/src/main/java/org/rx/operations/OperationToObservableSortedList.java @@ -0,0 +1,166 @@ +package org.rx.operations; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.junit.Test; +import org.mockito.Mockito; +import org.rx.functions.Func2; +import org.rx.reactive.Observable; +import org.rx.reactive.Observer; +import org.rx.reactive.Subscription; + +/** + * Similar to toList in that it converts a sequence<T> into a List<T> except that it accepts a Function that will provide an implementation of Comparator. + * + * @param <T> + */ +public final class OperationToObservableSortedList<T> { + + /** + * Sort T objects by their natural order (object must implement Comparable). + * + * @param sequence + * @throws ClassCastException + * if T objects do not implement Comparable + * @return + */ + public static <T> Observable<List<T>> toSortedList(Observable<T> sequence) { + return new ToObservableSortedList<T>(sequence); + } + + /** + * Sort T objects using the defined sort function. + * + * @param sequence + * @param sortFunction + * @return + */ + public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, Func2<Integer, T, T> sortFunction) { + return new ToObservableSortedList<T>(sequence, sortFunction); + } + + private static class ToObservableSortedList<T> extends Observable<List<T>> { + + private final Observable<T> that; + private final ConcurrentLinkedQueue<T> list = new ConcurrentLinkedQueue<T>(); + private final Func2<Integer, T, T> sortFunction; + + // unchecked as we're support Object for the default + @SuppressWarnings("unchecked") + private ToObservableSortedList(Observable<T> that) { + this(that, defaultSortFunction); + } + + private ToObservableSortedList(Observable<T> that, Func2<Integer, T, T> sortFunction) { + this.that = that; + this.sortFunction = sortFunction; + } + + public Subscription subscribe(Observer<List<T>> listObserver) { + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + final Observer<List<T>> Observer = new AtomicObserver<List<T>>(listObserver, subscription); + + subscription.setActual(that.subscribe(new Observer<T>() { + public void onNext(T value) { + // onNext can be concurrently executed so list must be thread-safe + list.add(value); + } + + public void onError(Exception ex) { + Observer.onError(ex); + } + + public void onCompleted() { + try { + // copy from LinkedQueue to List since ConcurrentLinkedQueue does not implement the List interface + ArrayList<T> l = new ArrayList<T>(list.size()); + for (T t : list) { + l.add(t); + } + + // sort the list before delivery + Collections.sort(l, new Comparator<T>() { + + @Override + public int compare(T o1, T o2) { + return sortFunction.call(o1, o2); + } + + }); + + Observer.onNext(Collections.unmodifiableList(l)); + Observer.onCompleted(); + } catch (Exception e) { + onError(e); + } + + } + })); + return subscription; + } + + // raw because we want to support Object for this default + @SuppressWarnings("rawtypes") + private static Func2 defaultSortFunction = new DefaultComparableFunction(); + + private static class DefaultComparableFunction implements Func2<Integer, Object, Object> { + + // unchecked because we want to support Object for this default + @SuppressWarnings("unchecked") + @Override + public Integer call(Object t1, Object t2) { + Comparable<Object> c1 = (Comparable<Object>) t1; + Comparable<Object> c2 = (Comparable<Object>) t2; + return c1.compareTo(c2); + } + + } + + } + + public static class UnitTest { + + @Test + public void testSortedList() { + Observable<Integer> w = Observable.toObservable(1, 3, 2, 5, 4); + Observable<List<Integer>> Observable = toSortedList(w); + + @SuppressWarnings("unchecked") + Observer<List<Integer>> aObserver = mock(Observer.class); + Observable.subscribe(aObserver); + verify(aObserver, times(1)).onNext(Arrays.asList(1, 2, 3, 4, 5)); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); + verify(aObserver, times(1)).onCompleted(); + } + + @Test + public void testSortedListWithCustomFunction() { + Observable<Integer> w = Observable.toObservable(1, 3, 2, 5, 4); + Observable<List<Integer>> Observable = toSortedList(w, new Func2<Integer, Integer, Integer>() { + + @Override + public Integer call(Integer t1, Integer t2) { + return t2 - t1; + } + + }); + ; + + @SuppressWarnings("unchecked") + Observer<List<Integer>> aObserver = mock(Observer.class); + Observable.subscribe(aObserver); + verify(aObserver, times(1)).onNext(Arrays.asList(5, 4, 3, 2, 1)); + verify(aObserver, Mockito.never()).onError(any(Exception.class)); + verify(aObserver, times(1)).onCompleted(); + } + + } +} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableFunction.java b/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableFunction.java deleted file mode 100644 index 4a12799d3b..0000000000 --- a/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableFunction.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.rx.operations; - -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; - -import org.junit.Test; -import org.rx.functions.Func1; -import org.rx.reactive.Observable; -import org.rx.reactive.Observer; -import org.rx.reactive.Subscription; - -/** - * Accepts a Function and makes it into a Observable. - * <p> - * This is equivalent to Rx Observable.Create - * - * @see http://msdn.microsoft.com/en-us/library/hh229114(v=vs.103).aspx - * @see ObservableExtensions.toObservable - * @see ObservableExtensions.create - */ -/* package */class OperationToObservableFunction<T> extends Observable<T> { - private final Func1<Subscription, Observer<T>> func; - - OperationToObservableFunction(Func1<Subscription, Observer<T>> func) { - this.func = func; - } - - @Override - public Subscription subscribe(Observer<T> Observer) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - // We specifically use the SingleThreaded AtomicObserver since we can't ensure the implementation is thread-safe - // so will not allow it to use the MultiThreaded version even when other operators are doing so - final Observer<T> atomicObserver = new AtomicObserverSingleThreaded<T>(Observer, subscription); - // if func.call is synchronous, then the subscription won't matter as it can't ever be called - // if func.call is asynchronous, then the subscription will get set and can be unsubscribed from - subscription.setActual(func.call(atomicObserver)); - - return subscription; - } - - public static class UnitTest { - - @Test - public void testCreate() { - - Observable<String> Observable = new OperationToObservableFunction<String>(new Func1<Subscription, Observer<String>>() { - - @Override - public Subscription call(Observer<String> Observer) { - Observer.onNext("one"); - Observer.onNext("two"); - Observer.onNext("three"); - Observer.onCompleted(); - return ObservableExtensions.noOpSubscription(); - } - - }); - - @SuppressWarnings("unchecked") - Observer<String> aObserver = mock(Observer.class); - Observable.subscribe(aObserver); - verify(aObserver, times(1)).onNext("one"); - verify(aObserver, times(1)).onNext("two"); - verify(aObserver, times(1)).onNext("three"); - verify(aObserver, never()).onError(any(Exception.class)); - verify(aObserver, times(1)).onCompleted(); - } - } -} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableIterable.java b/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableIterable.java deleted file mode 100644 index c1fbc8dafe..0000000000 --- a/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableIterable.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.rx.operations; - -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; - -import java.util.Arrays; - -import org.junit.Test; -import org.rx.reactive.Observable; -import org.rx.reactive.Observer; -import org.rx.reactive.Subscription; - -/** - * Accepts an Iterable object and exposes it as an Observable. - * - * @param <T> - * The type of the Iterable sequence. - */ -/* package */class OperationToObservableIterable<T> extends Observable<T> { - public OperationToObservableIterable(Iterable<T> list) { - this.iterable = list; - } - - public Iterable<T> iterable; - - public Subscription subscribe(Observer<T> Observer) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(ObservableExtensions.noOpSubscription()); - final Observer<T> observer = new AtomicObserver<T>(Observer, subscription); - - for (T item : iterable) { - observer.onNext(item); - } - observer.onCompleted(); - - return subscription; - } - - public static class UnitTest { - - @Test - public void testIterable() { - Observable<String> Observable = new OperationToObservableIterable<String>(Arrays.<String> asList("one", "two", "three")); - - @SuppressWarnings("unchecked") - Observer<String> aObserver = mock(Observer.class); - Observable.subscribe(aObserver); - verify(aObserver, times(1)).onNext("one"); - verify(aObserver, times(1)).onNext("two"); - verify(aObserver, times(1)).onNext("three"); - verify(aObserver, never()).onError(any(Exception.class)); - verify(aObserver, times(1)).onCompleted(); - } - } -} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableList.java b/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableList.java deleted file mode 100644 index 597bd99530..0000000000 --- a/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableList.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.rx.operations; - -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.ConcurrentLinkedQueue; - -import org.junit.Test; -import org.rx.reactive.Observable; -import org.rx.reactive.Observer; -import org.rx.reactive.Subscription; - -final class OperationToObservableList<T> extends Observable<List<T>> { - private final Observable<T> that; - final ConcurrentLinkedQueue<T> list = new ConcurrentLinkedQueue<T>(); - - OperationToObservableList(Observable<T> that) { - this.that = that; - } - - public Subscription subscribe(Observer<List<T>> listObserver) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - final Observer<List<T>> Observer = new AtomicObserver<List<T>>(listObserver, subscription); - - subscription.setActual(that.subscribe(new Observer<T>() { - public void onNext(T value) { - // onNext can be concurrently executed so list must be thread-safe - list.add(value); - } - - public void onError(Exception ex) { - Observer.onError(ex); - } - - public void onCompleted() { - try { - // copy from LinkedQueue to List since ConcurrentLinkedQueue does not implement the List interface - ArrayList<T> l = new ArrayList<T>(list.size()); - for (T t : list) { - l.add(t); - } - - // benjchristensen => I want to make this immutable but some clients are sorting this - // instead of using toSortedList() and this change breaks them until we migrate their code. - // Observer.onNext(Collections.unmodifiableList(l)); - Observer.onNext(l); - Observer.onCompleted(); - } catch (Exception e) { - onError(e); - } - - } - })); - return subscription; - } - - public static class UnitTest { - - @Test - public void testList() { - Observable<String> w = ObservableExtensions.toObservable("one", "two", "three"); - Observable<List<String>> Observable = new OperationToObservableList<String>(w); - - @SuppressWarnings("unchecked") - Observer<List<String>> aObserver = mock(Observer.class); - Observable.subscribe(aObserver); - verify(aObserver, times(1)).onNext(Arrays.asList("one", "two", "three")); - verify(aObserver, never()).onError(any(Exception.class)); - verify(aObserver, times(1)).onCompleted(); - } - } -} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableSortedList.java b/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableSortedList.java deleted file mode 100644 index f6a960bf6c..0000000000 --- a/rxjava-core/src/main/java/org/rx/operations/OperationToWatchableSortedList.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.rx.operations; - -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.ConcurrentLinkedQueue; - -import org.junit.Test; -import org.rx.functions.Func2; -import org.rx.reactive.Observable; -import org.rx.reactive.Observer; -import org.rx.reactive.Subscription; - -/** - * Similar to toList in that it converts a sequence<T> into a List<T> except that it accepts a Function that will provide an implementation of Comparator. - * - * @param <T> - */ -final class OperationToObservableSortedList<T> extends Observable<List<T>> { - - /** - * Sort T objects by their natural order (object must implement Comparable). - * - * @param sequence - * @throws ClassCastException - * if T objects do not implement Comparable - * @return - */ - public static <T> Observable<List<T>> toSortedList(Observable<T> sequence) { - return new OperationToObservableSortedList<T>(sequence); - } - - /** - * Sort T objects using the defined sort function. - * - * @param sequence - * @param sortFunction - * @return - */ - public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, Func2<Integer, T, T> sortFunction) { - return new OperationToObservableSortedList<T>(sequence, sortFunction); - } - - private final Observable<T> that; - private final ConcurrentLinkedQueue<T> list = new ConcurrentLinkedQueue<T>(); - private final Func2<Integer, T, T> sortFunction; - - // unchecked as we're support Object for the default - @SuppressWarnings("unchecked") - private OperationToObservableSortedList(Observable<T> that) { - this(that, defaultSortFunction); - } - - private OperationToObservableSortedList(Observable<T> that, Func2<Integer, T, T> sortFunction) { - this.that = that; - this.sortFunction = sortFunction; - } - - public Subscription subscribe(Observer<List<T>> listObserver) { - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - final Observer<List<T>> Observer = new AtomicObserver<List<T>>(listObserver, subscription); - - subscription.setActual(that.subscribe(new Observer<T>() { - public void onNext(T value) { - // onNext can be concurrently executed so list must be thread-safe - list.add(value); - } - - public void onError(Exception ex) { - Observer.onError(ex); - } - - public void onCompleted() { - try { - // copy from LinkedQueue to List since ConcurrentLinkedQueue does not implement the List interface - ArrayList<T> l = new ArrayList<T>(list.size()); - for (T t : list) { - l.add(t); - } - - // sort the list before delivery - Collections.sort(l, new Comparator<T>() { - - @Override - public int compare(T o1, T o2) { - return sortFunction.call(o1, o2); - } - - }); - - Observer.onNext(Collections.unmodifiableList(l)); - Observer.onCompleted(); - } catch (Exception e) { - onError(e); - } - - } - })); - return subscription; - } - - // raw because we want to support Object for this default - @SuppressWarnings("rawtypes") - private static Func2 defaultSortFunction = new DefaultComparableFunction(); - - private static class DefaultComparableFunction implements Func2<Integer, Object, Object> { - - // unchecked because we want to support Object for this default - @SuppressWarnings("unchecked") - @Override - public Integer call(Object t1, Object t2) { - Comparable<Object> c1 = (Comparable<Object>) t1; - Comparable<Object> c2 = (Comparable<Object>) t2; - return c1.compareTo(c2); - } - - } - - public static class UnitTest { - - @Test - public void testSortedList() { - Observable<Integer> w = ObservableExtensions.toObservable(1, 3, 2, 5, 4); - Observable<List<Integer>> Observable = toSortedList(w); - - @SuppressWarnings("unchecked") - Observer<List<Integer>> aObserver = mock(Observer.class); - Observable.subscribe(aObserver); - verify(aObserver, times(1)).onNext(Arrays.asList(1, 2, 3, 4, 5)); - verify(aObserver, never()).onError(any(Exception.class)); - verify(aObserver, times(1)).onCompleted(); - } - - @Test - public void testSortedListWithCustomFunction() { - Observable<Integer> w = ObservableExtensions.toObservable(1, 3, 2, 5, 4); - Observable<List<Integer>> Observable = toSortedList(w, new Func2<Integer, Integer, Integer>() { - - @Override - public Integer call(Integer t1, Integer t2) { - return t2 - t1; - } - - }); - ; - - @SuppressWarnings("unchecked") - Observer<List<Integer>> aObserver = mock(Observer.class); - Observable.subscribe(aObserver); - verify(aObserver, times(1)).onNext(Arrays.asList(5, 4, 3, 2, 1)); - verify(aObserver, never()).onError(any(Exception.class)); - verify(aObserver, times(1)).onCompleted(); - } - - } -} \ No newline at end of file diff --git a/rxjava-core/src/main/java/org/rx/operations/OperationZip.java b/rxjava-core/src/main/java/org/rx/operations/OperationZip.java index e246f74f72..f453ba9abd 100644 --- a/rxjava-core/src/main/java/org/rx/operations/OperationZip.java +++ b/rxjava-core/src/main/java/org/rx/operations/OperationZip.java @@ -22,7 +22,7 @@ import org.rx.reactive.Observer; import org.rx.reactive.Subscription; -class OperationZip { +public final class OperationZip { public static <R, T0, T1> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Func2<R, T0, T1> zipFunction) { Aggregator<R> a = new Aggregator<R>(Functions.fromFunc(zipFunction)); @@ -649,7 +649,7 @@ public void testZip2Types() { /* define a Observer to receive aggregated events */ Observer<String> aObserver = mock(Observer.class); - Observable<String> w = zip(ObservableExtensions.toObservable("one", "two"), ObservableExtensions.toObservable(2, 3, 4), zipr); + Observable<String> w = zip(Observable.toObservable("one", "two"), Observable.toObservable(2, 3, 4), zipr); w.subscribe(aObserver); verify(aObserver, never()).onError(any(Exception.class)); @@ -668,7 +668,7 @@ public void testZip3Types() { /* define a Observer to receive aggregated events */ Observer<String> aObserver = mock(Observer.class); - Observable<String> w = zip(ObservableExtensions.toObservable("one", "two"), ObservableExtensions.toObservable(2), ObservableExtensions.toObservable(new int[] { 4, 5, 6 }), zipr); + Observable<String> w = zip(Observable.toObservable("one", "two"), Observable.toObservable(2), Observable.toObservable(new int[] { 4, 5, 6 }), zipr); w.subscribe(aObserver); verify(aObserver, never()).onError(any(Exception.class)); @@ -684,7 +684,7 @@ public void testOnNextExceptionInvokesOnError() { @SuppressWarnings("unchecked") Observer<Integer> aObserver = mock(Observer.class); - Observable<Integer> w = zip(ObservableExtensions.toObservable(10, 20, 30), ObservableExtensions.toObservable(0, 1, 2), zipr); + Observable<Integer> w = zip(Observable.toObservable(10, 20, 30), Observable.toObservable(0, 1, 2), zipr); w.subscribe(aObserver); verify(aObserver, times(1)).onError(any(Exception.class)); @@ -786,7 +786,7 @@ private static class TestObservable extends Observable<String> { public Subscription subscribe(Observer<String> Observer) { // just store the variable where it can be accessed so we can manually trigger it this.Observer = Observer; - return ObservableExtensions.noOpSubscription(); + return Observable.noOpSubscription(); } } diff --git a/rxjava-core/src/main/java/org/rx/reactive/Observable.java b/rxjava-core/src/main/java/org/rx/reactive/Observable.java index 1450fbabb5..dc36981e29 100644 --- a/rxjava-core/src/main/java/org/rx/reactive/Observable.java +++ b/rxjava-core/src/main/java/org/rx/reactive/Observable.java @@ -5,6 +5,7 @@ import groovy.lang.Binding; import groovy.lang.GroovyClassLoader; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -16,9 +17,27 @@ import org.mockito.MockitoAnnotations; import org.rx.functions.Func1; import org.rx.functions.Func2; +import org.rx.functions.Func3; +import org.rx.functions.Func4; import org.rx.functions.Functions; -import org.rx.operations.ObservableExtensions; +import org.rx.operations.OperationFilter; +import org.rx.operations.OperationLast; +import org.rx.operations.OperationMap; import org.rx.operations.OperationMaterialize; +import org.rx.operations.OperationMerge; +import org.rx.operations.OperationMergeDelayError; +import org.rx.operations.OperationOnErrorResumeNextViaFunction; +import org.rx.operations.OperationOnErrorResumeNextViaObservable; +import org.rx.operations.OperationOnErrorReturn; +import org.rx.operations.OperationScan; +import org.rx.operations.OperationSkip; +import org.rx.operations.OperationSynchronize; +import org.rx.operations.OperationTake; +import org.rx.operations.OperationToObservableFunction; +import org.rx.operations.OperationToObservableIterable; +import org.rx.operations.OperationToObservableList; +import org.rx.operations.OperationToObservableSortedList; +import org.rx.operations.OperationZip; /** * The Observable interface that implements the Reactive Pattern. @@ -29,12 +48,24 @@ * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.legend&ceoid=27321465&key=API&pageId=27321465"><img * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.legend.png"></a> * <p> - * It provides overloaded methods for subscribing as well as delegate methods to the ObservableExtensions. + * It provides overloaded methods for subscribing as well as delegate methods to the * * @param <T> */ public abstract class Observable<T> { + public Observable() { + } + + public static <T> Observable<T> create(final Func1<Subscription, Observer<T>> f, Observer<T> observer) { + return new Observable<T>() { + @Override + public Subscription subscribe(Observer<T> observer) { + return f.call(observer); + } + }; + } + /** * A Observer must call a Observable's <code>subscribe</code> method in order to register itself * to receive push-based notifications from the Observable. A typical implementation of the @@ -143,53 +174,1321 @@ public void onNext(Object args) { }); } - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Subscription subscribe(final Object onNext, final Object onError, final Object onComplete) { - return subscribe(new Observer() { - - public void onCompleted() { - if (onComplete != null) { - executeCallback(onComplete); - } - } + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Subscription subscribe(final Object onNext, final Object onError, final Object onComplete) { + return subscribe(new Observer() { + + public void onCompleted() { + if (onComplete != null) { + executeCallback(onComplete); + } + } + + public void onError(Exception e) { + handleError(e); + if (onError != null) { + executeCallback(onError, e); + } + } + + public void onNext(Object args) { + if (onNext == null) { + throw new RuntimeException("onNext must be implemented"); + } + executeCallback(onNext, args); + } + + }); + } + + /** + * When an error occurs in any Observer we will invoke this to allow it to be handled by the global APIObservableErrorHandler + * + * @param e + */ + private static void handleError(Exception e) { + // plugins have been removed during opensourcing but the intention is to provide these hooks again + } + + /** + * Execute the callback with the given arguments. + * <p> + * The callbacks align with the onCompleted, onError and onNext methods an an IObserver. + * + * @param callback + * Object to be invoked. It is left to the implementing class to determine the type, such as a Groovy Closure or JRuby closure conversion. + * @param args + */ + private void executeCallback(final Object callback, Object... args) { + Functions.execute(callback, args); + } + + /** + * A Observable that never sends any information to a Observer. + * + * This Observable is useful primarily for testing purposes. + * + * @param <T> + * the type of item emitted by the Observable + */ + private static class NeverObservable<T> extends Observable<T> { + public Subscription subscribe(Observer<T> observer) { + return new NullObservableSubscription(); + } + } + + /** + * A disposable object that does nothing when its unsubscribe method is called. + */ + private static class NullObservableSubscription implements Subscription { + public void unsubscribe() { + } + } + + /** + * A Observable that calls a Observer's <code>onError</code> closure when the Observer subscribes. + * + * @param <T> + * the type of object returned by the Observable + */ + private static class ThrowObservable<T> extends Observable<T> { + private Exception exception; + + public ThrowObservable(Exception exception) { + this.exception = exception; + } + + /** + * Accepts a Observer and calls its <code>onError</code> method. + * + * @param observer + * a Observer of this Observable + * @return a reference to the subscription + */ + public Subscription subscribe(Observer<T> observer) { + observer.onError(this.exception); + return new NullObservableSubscription(); + } + } + + /** + * Creates a Observable that will execute the given function when a Observer subscribes to it. + * <p> + * You can create a simple Observable from scratch by using the <code>create</code> method. You pass this method a closure that accepts as a parameter the map of closures that a Observer passes to + * a + * Observable's <code>subscribe</code> method. Write + * the closure you pass to <code>create</code> so that it behaves as a Observable - calling the passed-in <code>onNext</code>, <code>onError</code>, and <code>onCompleted</code> methods + * appropriately. + * <p> + * A well-formed Observable must call either the Observer's <code>onCompleted</code> method exactly once or its <code>onError</code> method exactly once. + * + * @param <T> + * the type emitted by the Observable sequence + * @param func + * a closure that accepts a <code>Observer<T></code> and calls its <code>onNext</code>, <code>onError</code>, and <code>onCompleted</code> methods + * as appropriate, and returns a <code>ObservableSubscription</code> to allow + * cancelling the subscription (if applicable) + * @return a Observable that, when a Observer subscribes to it, will execute the given function + */ + public static <T> Observable<T> create(Func1<Subscription, Observer<T>> func) { + return wrap(OperationToObservableFunction.toObservableFunction(func)); + } + + /** + * Creates a Observable that will execute the given function when a Observer subscribes to it. + * <p> + * You can create a simple Observable from scratch by using the <code>create</code> method. You pass this method a closure that accepts as a parameter the map of closures that a Observer passes to + * a + * Observable's <code>subscribe</code> method. Write + * the closure you pass to <code>create</code> so that it behaves as a Observable - calling the passed-in <code>onNext</code>, <code>onError</code>, and <code>onCompleted</code> methods + * appropriately. + * <p> + * A well-formed Observable must call either the Observer's <code>onCompleted</code> method exactly once or its <code>onError</code> method exactly once. + * + * @param <T> + * the type of the observable sequence + * @param func + * a closure that accepts a <code>Observer<T></code> and calls its <code>onNext</code>, <code>onError</code>, and <code>onCompleted</code> methods + * as appropriate, and returns a <code>ObservableSubscription</code> to allow + * cancelling the subscription (if applicable) + * @return a Observable that, when a Observer subscribes to it, will execute the given function + */ + public static <T> Observable<T> create(final Object callback) { + return create(new Func1<Subscription, Observer<T>>() { + + @Override + public Subscription call(Observer<T> t1) { + return Functions.execute(callback, t1); + } + + }); + } + + /** + * Returns a Observable that returns no data to the Observer and immediately invokes its <code>onCompleted</code> method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.empty&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.empty.png"></a> + * + * @param <T> + * the type of item emitted by the Observable + * @return a Observable that returns no data to the Observer and immediately invokes the + * Observer's <code>onCompleted</code> method + */ + public static <T> Observable<T> empty() { + return toObservable(new ArrayList<T>()); + } + + /** + * Returns a Observable that calls <code>onError</code> when a Observer subscribes to it. + * <p> + * Note: Maps to <code>Observable.Throw</code> in Rx - throw is a reserved word in Java. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.error&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.error.png"></a> + * + * @param exception + * the error to throw + * @param <T> + * the type of object returned by the Observable + * @return a Observable object that calls <code>onError</code> when a Observer subscribes + */ + public static <T> Observable<T> error(Exception exception) { + return wrap(new ThrowObservable<T>(exception)); + } + + /** + * Filters a Observable by discarding any of its emissions that do not meet some test. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.filter&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.filter.png"></a> + * + * @param that + * the Observable to filter + * @param predicate + * a closure that evaluates the items emitted by the source Observable, returning <code>true</code> if they pass the filter + * @return a Observable that emits only those items in the original Observable that the filter + * evaluates as true + */ + public static <T> Observable<T> filter(Observable<T> that, Func1<Boolean, T> predicate) { + return OperationFilter.filter(that, predicate); + } + + /** + * Filters a Observable by discarding any of its emissions that do not meet some test. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.filter&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.filter.png"></a> + * + * @param that + * the Observable to filter + * @param predicate + * a closure that evaluates the items emitted by the source Observable, returning <code>true</code> if they pass the filter + * @return a Observable that emits only those items in the original Observable that the filter + * evaluates as true + */ + public static <T> Observable<T> filter(Observable<T> that, final Object function) { + return filter(that, new Func1<Boolean, T>() { + + @Override + public Boolean call(T t1) { + return Functions.execute(function, t1); + + } + + }); + } + + /** + * Returns a Observable that notifies an observer of a single value and then completes. + * <p> + * To convert any object into a Observable that emits that object, pass that object into the <code>just</code> method. + * <p> + * This is similar to the {@link toObservable} method, except that <code>toObservable</code> will convert an iterable object into a Observable that emits each of the items in the iterable, one at + * a + * time, while the <code>just</code> method would + * convert the iterable into a Observable that emits the entire iterable as a single item. + * <p> + * This value is the equivalent of <code>Observable.Return</code> in the Reactive Extensions library. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.just&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.just.png"></a> + * + * @param value + * the value to pass to the Observer's <code>onNext</code> method + * @param <T> + * the type of the value + * @return a Observable that notifies a Observer of a single value and then completes + */ + public static <T> Observable<T> just(T value) { + List<T> list = new ArrayList<T>(); + list.add(value); + + return toObservable(list); + } + + /** + * Takes the last item emitted by a source Observable and returns a Observable that emits only + * that item as its sole emission. + * <p> + * To convert a Observable that emits a sequence of objects into one that only emits the last object in this sequence before completing, use the <code>last</code> method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.last&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.last.png"></a> + * + * @param that + * the source Observable + * @return a Observable that emits a single item, which is identical to the last item emitted + * by the source Observable + */ + public static <T> Observable<T> last(final Observable<T> that) { + return wrap(OperationLast.last(that)); + } + + /** + * Applies a closure of your choosing to every notification emitted by a Observable, and returns + * this transformation as a new Observable sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.map&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.map.png"></a> + * + * @param sequence + * the source Observable + * @param func + * a closure to apply to each item in the sequence emitted by the source Observable + * @param <T> + * the type of items emitted by the the source Observable + * @param <R> + * the type of items returned by map closure <code>func</code> + * @return a Observable that is the result of applying the transformation function to each item + * in the sequence emitted by the source Observable + */ + public static <T, R> Observable<R> map(Observable<T> sequence, Func1<R, T> func) { + return wrap(OperationMap.map(sequence, func)); + } + + /** + * Applies a closure of your choosing to every notification emitted by a Observable, and returns + * this transformation as a new Observable sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.map&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.map.png"></a> + * + * @param sequence + * the source Observable + * @param function + * a closure to apply to each item in the sequence emitted by the source Observable + * @param <T> + * the type of items emitted by the the source Observable + * @param <R> + * the type of items returned by map closure <code>function</code> + * @return a Observable that is the result of applying the transformation function to each item + * in the sequence emitted by the source Observable + */ + public static <T, R> Observable<R> map(Observable<T> sequence, final Object function) { + return map(sequence, new Func1<R, T>() { + + @Override + public R call(T t1) { + return Functions.execute(function, t1); + } + + }); + } + + /** + * Creates a new Observable sequence by applying a closure that you supply to each object in the + * original Observable sequence, where that closure is itself a Observable that emits objects, + * and then merges the results of that closure applied to every item emitted by the original + * Observable, emitting these merged results as its own sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mapmany&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mapMany.png"></a> + * + * @param sequence + * the source Observable + * @param func + * a closure to apply to each item emitted by the source Observable, generating a + * Observable + * @param <T> + * the type emitted by the source Observable + * @param <R> + * the type emitted by the Observables emitted by <code>func</code> + * @return a Observable that emits a sequence that is the result of applying the transformation + * function to each item emitted by the source Observable and merging the results of + * the Observables obtained from this transformation + */ + public static <T, R> Observable<R> mapMany(Observable<T> sequence, Func1<Observable<R>, T> func) { + return wrap(OperationMap.mapMany(sequence, func)); + } + + /** + * Creates a new Observable sequence by applying a closure that you supply to each object in the + * original Observable sequence, where that closure is itself a Observable that emits objects, + * and then merges the results of that closure applied to every item emitted by the original + * Observable, emitting these merged results as its own sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mapmany&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mapMany.png"></a> + * + * @param sequence + * the source Observable + * @param function + * a closure to apply to each item emitted by the source Observable, generating a + * Observable + * @param <T> + * the type emitted by the source Observable + * @param <R> + * the type emitted by the Observables emitted by <code>function</code> + * @return a Observable that emits a sequence that is the result of applying the transformation + * function to each item emitted by the source Observable and merging the results of the + * Observables obtained from this transformation + */ + public static <T, R> Observable<R> mapMany(Observable<T> sequence, final Object function) { + return mapMany(sequence, new Func1<R, T>() { + + @Override + public R call(T t1) { + return Functions.execute(function, t1); + } + + }); + } + + /** + * Materializes the implicit notifications of an observable sequence as explicit notification values. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.materialize&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.materialize.png"></a> + * + * @param source + * An observable sequence of elements to project. + * @return An observable sequence whose elements are the result of materializing the notifications of the given sequence. + * @see http://msdn.microsoft.com/en-us/library/hh229453(v=VS.103).aspx + */ + public static <T> Observable<Notification<T>> materialize(final Observable<T> sequence) { + return OperationMaterialize.materialize(sequence); + } + + /** + * Flattens the Observable sequences from a list of Observables into one Observable sequence + * without any transformation. You can combine the output of multiple Observables so that they + * act like a single Observable, by using the <code>merge</code> method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.merge&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.merge.png"></a> + * + * @param source + * a list of Observables that emit sequences of items + * @return a Observable that emits a sequence of elements that are the result of flattening the + * output from the <code>source</code> list of Observables + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> + */ + public static <T> Observable<T> merge(List<Observable<T>> source) { + return wrap(OperationMerge.merge(source)); + } + + /** + * Flattens the Observable sequences emitted by a sequence of Observables that are emitted by a + * Observable into one Observable sequence without any transformation. You can combine the output + * of multiple Observables so that they act like a single Observable, by using the <code>merge</code> method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.merge.W&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.merge.W.png"></a> + * + * @param source + * a Observable that emits Observables + * @return a Observable that emits a sequence of elements that are the result of flattening the + * output from the Observables emitted by the <code>source</code> Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> + */ + public static <T> Observable<T> merge(Observable<Observable<T>> source) { + return wrap(OperationMerge.merge(source)); + } + + /** + * Flattens the Observable sequences from a series of Observables into one Observable sequence + * without any transformation. You can combine the output of multiple Observables so that they + * act like a single Observable, by using the <code>merge</code> method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.merge&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.merge.png"></a> + * + * @param source + * a series of Observables that emit sequences of items + * @return a Observable that emits a sequence of elements that are the result of flattening the + * output from the <code>source</code> Observables + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> + */ + public static <T> Observable<T> merge(Observable<T>... source) { + return wrap(OperationMerge.merge(source)); + } + + /** + * Same functionality as <code>merge</code> except that errors received to onError will be held until all sequences have finished (onComplete/onError) before sending the error. + * <p> + * Only the first onError received will be sent. + * <p> + * This enables receiving all successes from merged sequences without one onError from one sequence causing all onNext calls to be prevented. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mergeDelayError&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mergeDelayError.png"></a> + * + * @param source + * a list of Observables that emit sequences of items + * @return a Observable that emits a sequence of elements that are the result of flattening the + * output from the <code>source</code> list of Observables + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> + */ + public static <T> Observable<T> mergeDelayError(List<Observable<T>> source) { + return wrap(OperationMergeDelayError.mergeDelayError(source)); + } + + /** + * Same functionality as <code>merge</code> except that errors received to onError will be held until all sequences have finished (onComplete/onError) before sending the error. + * <p> + * Only the first onError received will be sent. + * <p> + * This enables receiving all successes from merged sequences without one onError from one sequence causing all onNext calls to be prevented. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mergeDelayError.W&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mergeDelayError.W.png"></a> + * + * @param source + * a Observable that emits Observables + * @return a Observable that emits a sequence of elements that are the result of flattening the + * output from the Observables emitted by the <code>source</code> Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> + */ + public static <T> Observable<T> mergeDelayError(Observable<Observable<T>> source) { + return wrap(OperationMergeDelayError.mergeDelayError(source)); + } + + /** + * Same functionality as <code>merge</code> except that errors received to onError will be held until all sequences have finished (onComplete/onError) before sending the error. + * <p> + * Only the first onError received will be sent. + * <p> + * This enables receiving all successes from merged sequences without one onError from one sequence causing all onNext calls to be prevented. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.mergeDelayError&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.mergeDelayError.png"></a> + * + * @param source + * a series of Observables that emit sequences of items + * @return a Observable that emits a sequence of elements that are the result of flattening the + * output from the <code>source</code> Observables + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> + */ + public static <T> Observable<T> mergeDelayError(Observable<T>... source) { + return wrap(OperationMergeDelayError.mergeDelayError(source)); + } + + /** + * Returns a Observable that never sends any information to a Observer. + * + * This observable is useful primarily for testing purposes. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.never&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.never.png"></a> + * + * @param <T> + * the type of item (not) emitted by the Observable + * @return a Observable that never sends any information to a Observer + */ + public static <T> Observable<T> never() { + return wrap(new NeverObservable<T>()); + } + + /** + * A ObservableSubscription that does nothing. + * + * @return + */ + public static Subscription noOpSubscription() { + return new NullObservableSubscription(); + } + + /** + * Instruct a Observable to pass control to another Observable (the return value of a function) + * rather than calling <code>onError</code> if it encounters an error. + * <p> + * By default, when a Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and then + * quits + * without calling any more of its Observer's + * closures. The <code>onErrorResumeNext</code> method changes this behavior. If you pass a closure that emits a Observable (<code>resumeFunction</code>) to a Observable's + * <code>onErrorResumeNext</code> method, if the original Observable encounters + * an error, instead of calling its Observer's <code>onError</code> closure, it will instead relinquish control to this new Observable, which will call the Observer's <code>onNext</code> method if + * it + * is able to do so. In such a case, because no + * Observable necessarily invokes <code>onError</code>, the Observer may never know that an error happened. + * <p> + * You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorresumenext&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorresumenext.png"></a> + * + * @param that + * the source Observable + * @param resumeFunction + * a closure that returns a Observable that will take over if the source Observable + * encounters an error + * @return the source Observable, with its behavior modified as described + */ + public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, final Func1<Observable<T>, Exception> resumeFunction) { + return wrap(OperationOnErrorResumeNextViaFunction.onErrorResumeNextViaFunction(that, resumeFunction)); + } + + /** + * Instruct a Observable to emit a particular object (as returned by a closure) to its Observer + * rather than calling <code>onError</code> if it encounters an error. + * <p> + * By default, when a Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and then + * quits + * without calling any more of its Observer's + * closures. The <code>onErrorResumeNext</code> method changes this behavior. If you pass a function that returns another Observable (<code>resumeFunction</code>) to a Observable's + * <code>onErrorResumeNext</code> method, if the original Observable + * encounters an error, instead of calling its Observer's <code>onError</code> closure, it will instead relinquish control to this new Observable which will call the Observer's <code>onNext</code> + * method if it is able to do so. In such a case, + * because no Observable necessarily invokes <code>onError</code>, the Observer may never know that an error happened. + * <p> + * You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorresumenext&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorresumenext.png"></a> + * + * @param that + * the source Observable + * @param resumeFunction + * a closure that returns a Observable that will take over if the source Observable + * encounters an error + * @return the source Observable, with its behavior modified as described + */ + public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, final Object resumeFunction) { + return onErrorResumeNext(that, new Func1<Observable<T>, Exception>() { + + @Override + public Observable<T> call(Exception e) { + return Functions.execute(resumeFunction, e); + } + }); + } + + /** + * Instruct a Observable to pass control to another Observable rather than calling <code>onError</code> if it encounters an error. + * <p> + * By default, when a Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and then + * quits + * without calling any more of its Observer's + * closures. The <code>onErrorResumeNext</code> method changes this behavior. If you pass another Observable (<code>resumeSequence</code>) to a Observable's <code>onErrorResumeNext</code> method, + * if + * the original Observable encounters an error, + * instead of calling its Observer's <code>onError</code> closure, it will instead relinquish control to <code>resumeSequence</code> which will call the Observer's <code>onNext</code> method if it + * is able to do so. In such a case, because no + * Observable necessarily invokes <code>onError</code>, the Observer may never know that an error happened. + * <p> + * You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorresumenext&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorresumenext.png"></a> + * + * @param that + * the source Observable + * @param resumeSequence + * the Observable that will take over if the source Observable encounters an error + * @return the source Observable, with its behavior modified as described + */ + public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, final Observable<T> resumeSequence) { + return wrap(OperationOnErrorResumeNextViaObservable.onErrorResumeNextViaObservable(that, resumeSequence)); + } + + /** + * Instruct a Observable to emit a particular item to its Observer's <code>onNext</code> closure + * rather than calling <code>onError</code> if it encounters an error. + * <p> + * By default, when a Observable encounters an error that prevents it from emitting the expected item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and then + * quits + * without calling any more of its Observer's + * closures. The <code>onErrorReturn</code> method changes this behavior. If you pass a closure (<code>resumeFunction</code>) to a Observable's <code>onErrorReturn</code> method, if the original + * Observable encounters an error, instead of calling + * its Observer's <code>onError</code> closure, it will instead pass the return value of <code>resumeFunction</code> to the Observer's <code>onNext</code> method. + * <p> + * You can use this to prevent errors from propagating or to supply fallback data should errors be encountered. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorreturn&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorreturn.png"></a> + * + * @param that + * the source Observable + * @param resumeFunction + * a closure that returns a value that will be passed into a Observer's <code>onNext</code> closure if the Observable encounters an error that would + * otherwise cause it to call <code>onError</code> + * @return the source Observable, with its behavior modified as described + */ + public static <T> Observable<T> onErrorReturn(final Observable<T> that, Func1<T, Exception> resumeFunction) { + return wrap(OperationOnErrorReturn.onErrorReturn(that, resumeFunction)); + } + + /** + * Returns a Observable that applies a closure of your choosing to the first item emitted by a + * source Observable, then feeds the result of that closure along with the second item emitted + * by a Observable into the same closure, and so on until all items have been emitted by the + * source Observable, emitting the final result from the final call to your closure as its sole + * output. + * <p> + * This technique, which is called "reduce" here, is sometimes called "fold," "accumulate," "compress," or "inject" in other programming contexts. Groovy, for instance, has an <code>inject</code> + * method that does a similar operation on lists. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.reduce.noseed&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.reduce.noseed.png"></a> + * + * @param <T> + * the type item emitted by the source Observable + * @param sequence + * the source Observable + * @param accumulator + * an accumulator closure to be invoked on each element from the sequence, whose + * result will be used in the next accumulator call (if applicable) + * + * @return a Observable that emits a single element that is the result of accumulating the + * output from applying the accumulator to the sequence of items emitted by the source + * Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> + * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> + */ + public static <T> Observable<T> reduce(Observable<T> sequence, Func2<T, T, T> accumulator) { + return wrap(OperationScan.scan(sequence, accumulator).last()); + } + + /** + * Returns a Observable that applies a closure of your choosing to the first item emitted by a + * source Observable, then feeds the result of that closure along with the second item emitted + * by a Observable into the same closure, and so on until all items have been emitted by the + * source Observable, emitting the final result from the final call to your closure as its sole + * output. + * <p> + * This technique, which is called "reduce" here, is sometimes called "fold," "accumulate," "compress," or "inject" in other programming contexts. Groovy, for instance, has an <code>inject</code> + * method that does a similar operation on lists. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.reduce.noseed&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.reduce.noseed.png"></a> + * + * @param <T> + * the type item emitted by the source Observable + * @param sequence + * the source Observable + * @param accumulator + * an accumulator closure to be invoked on each element from the sequence, whose + * result will be used in the next accumulator call (if applicable) + * + * @return a Observable that emits a single element that is the result of accumulating the + * output from applying the accumulator to the sequence of items emitted by the source + * Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> + * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> + */ + public static <T> Observable<T> reduce(final Observable<T> sequence, final Object accumulator) { + return reduce(sequence, new Func2<T, T, T>() { + + @Override + public T call(T t1, T t2) { + return Functions.execute(accumulator, t1, t2); + } + + }); + } + + /** + * Returns a Observable that applies a closure of your choosing to the first item emitted by a + * source Observable, then feeds the result of that closure along with the second item emitted + * by a Observable into the same closure, and so on until all items have been emitted by the + * source Observable, emitting the final result from the final call to your closure as its sole + * output. + * <p> + * This technique, which is called "reduce" here, is sometimes called "fold," "accumulate," "compress," or "inject" in other programming contexts. Groovy, for instance, has an <code>inject</code> + * method that does a similar operation on lists. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.reduce&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.reduce.png"></a> + * + * @param <T> + * the type item emitted by the source Observable + * @param sequence + * the source Observable + * @param initialValue + * a seed passed into the first execution of the accumulator closure + * @param accumulator + * an accumulator closure to be invoked on each element from the sequence, whose + * result will be used in the next accumulator call (if applicable) + * + * @return a Observable that emits a single element that is the result of accumulating the + * output from applying the accumulator to the sequence of items emitted by the source + * Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> + * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> + */ + public static <T> Observable<T> reduce(Observable<T> sequence, T initialValue, Func2<T, T, T> accumulator) { + return wrap(OperationScan.scan(sequence, initialValue, accumulator).last()); + } + + /** + * Returns a Observable that applies a closure of your choosing to the first item emitted by a + * source Observable, then feeds the result of that closure along with the second item emitted + * by a Observable into the same closure, and so on until all items have been emitted by the + * source Observable, emitting the final result from the final call to your closure as its sole + * output. + * <p> + * This technique, which is called "reduce" here, is sometimes called "fold," "accumulate," "compress," or "inject" in other programming contexts. Groovy, for instance, has an <code>inject</code> + * method that does a similar operation on lists. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.reduce&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.reduce.png"></a> + * + * @param <T> + * the type item emitted by the source Observable + * @param sequence + * the source Observable + * @param initialValue + * a seed passed into the first execution of the accumulator closure + * @param accumulator + * an accumulator closure to be invoked on each element from the sequence, whose + * result will be used in the next accumulator call (if applicable) + * @return a Observable that emits a single element that is the result of accumulating the + * output from applying the accumulator to the sequence of items emitted by the source + * Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229154(v%3Dvs.103).aspx">MSDN: Observable.Aggregate</a> + * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> + */ + public static <T> Observable<T> reduce(final Observable<T> sequence, final T initialValue, final Object accumulator) { + return reduce(sequence, initialValue, new Func2<T, T, T>() { + + @Override + public T call(T t1, T t2) { + return Functions.execute(accumulator, t1, t2); + } + + }); + } + + /** + * Returns a Observable that applies a closure of your choosing to the first item emitted by a + * source Observable, then feeds the result of that closure along with the second item emitted + * by a Observable into the same closure, and so on until all items have been emitted by the + * source Observable, emitting the result of each of these iterations as its own sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.scan.noseed&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.scan.noseed.png"></a> + * + * @param <T> + * the type item emitted by the source Observable + * @param sequence + * the source Observable + * @param accumulator + * an accumulator closure to be invoked on each element from the sequence, whose + * result will be emitted and used in the next accumulator call (if applicable) + * @return a Observable that emits a sequence of items that are the result of accumulating the + * output from the sequence emitted by the source Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> + */ + public static <T> Observable<T> scan(Observable<T> sequence, Func2<T, T, T> accumulator) { + return wrap(OperationScan.scan(sequence, accumulator)); + } + + /** + * Returns a Observable that applies a closure of your choosing to the first item emitted by a + * source Observable, then feeds the result of that closure along with the second item emitted + * by a Observable into the same closure, and so on until all items have been emitted by the + * source Observable, emitting the result of each of these iterations as its own sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.scan.noseed&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.scan.noseed.png"></a> + * + * @param <T> + * the type item emitted by the source Observable + * @param sequence + * the source Observable + * @param accumulator + * an accumulator closure to be invoked on each element from the sequence, whose + * result will be emitted and used in the next accumulator call (if applicable) + * @return a Observable that emits a sequence of items that are the result of accumulating the + * output from the sequence emitted by the source Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> + */ + public static <T> Observable<T> scan(final Observable<T> sequence, final Object accumulator) { + return scan(sequence, new Func2<T, T, T>() { + + @Override + public T call(T t1, T t2) { + return Functions.execute(accumulator, t1, t2); + } + + }); + } + + /** + * Returns a Observable that applies a closure of your choosing to the first item emitted by a + * source Observable, then feeds the result of that closure along with the second item emitted + * by a Observable into the same closure, and so on until all items have been emitted by the + * source Observable, emitting the result of each of these iterations as its own sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.scan&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.scan.png"></a> + * + * @param <T> + * the type item emitted by the source Observable + * @param sequence + * the source Observable + * @param initialValue + * the initial (seed) accumulator value + * @param accumulator + * an accumulator closure to be invoked on each element from the sequence, whose + * result will be emitted and used in the next accumulator call (if applicable) + * @return a Observable that emits a sequence of items that are the result of accumulating the + * output from the sequence emitted by the source Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> + */ + public static <T> Observable<T> scan(Observable<T> sequence, T initialValue, Func2<T, T, T> accumulator) { + return wrap(OperationScan.scan(sequence, initialValue, accumulator)); + } + + /** + * Returns a Observable that applies a closure of your choosing to the first item emitted by a + * source Observable, then feeds the result of that closure along with the second item emitted + * by a Observable into the same closure, and so on until all items have been emitted by the + * source Observable, emitting the result of each of these iterations as its own sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.scan&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.scan.png"></a> + * + * @param <T> + * the type item emitted by the source Observable + * @param sequence + * the source Observable + * @param initialValue + * the initial (seed) accumulator value + * @param accumulator + * an accumulator closure to be invoked on each element from the sequence, whose + * result will be emitted and used in the next accumulator call (if applicable) + * @return a Observable that emits a sequence of items that are the result of accumulating the + * output from the sequence emitted by the source Observable + * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> + */ + public static <T> Observable<T> scan(final Observable<T> sequence, final T initialValue, final Object accumulator) { + return scan(sequence, initialValue, new Func2<T, T, T>() { + + @Override + public T call(T t1, T t2) { + return Functions.execute(accumulator, t1, t2); + } + + }); + } + + /** + * Returns a Observable that skips the first <code>num</code> items emitted by the source + * Observable. You can ignore the first <code>num</code> items emitted by a Observable and attend + * only to those items that come after, by modifying the Observable with the <code>skip</code> method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.skip&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.skip.png"></a> + * + * @param items + * the source Observable + * @param num + * the number of items to skip + * @return a Observable that emits the same sequence of items emitted by the source Observable, + * except for the first <code>num</code> items + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229847(v=vs.103).aspx">MSDN: Observable.Skip Method</a> + */ + public static <T> Observable<T> skip(final Observable<T> items, int num) { + return wrap(OperationSkip.skip(items, num)); + } + + /** + * Accepts a Observable and wraps it in another Observable that ensures that the resulting + * Observable is chronologically well-behaved. + * <p> + * A well-behaved observable ensures <code>onNext</code>, <code>onCompleted</code>, or <code>onError</code> calls to its subscribers are not interleaved, <code>onCompleted</code> and + * <code>onError</code> are only called once respectively, and no + * <code>onNext</code> calls follow <code>onCompleted</code> and <code>onError</code> calls. + * + * @param observable + * the source Observable + * @param <T> + * the type of item emitted by the source Observable + * @return a Observable that is a chronologically well-behaved version of the source Observable + */ + public static <T> Observable<T> synchronize(Observable<T> observable) { + return wrap(OperationSynchronize.synchronize(observable)); + } + + /** + * Returns a Observable that emits the first <code>num</code> items emitted by the source + * Observable. + * <p> + * You can choose to pay attention only to the first <code>num</code> values emitted by a Observable by calling its <code>take</code> method. This method returns a Observable that will call a + * subscribing Observer's <code>onNext</code> closure a + * maximum of <code>num</code> times before calling <code>onCompleted</code>. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.take&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.take.png"></a> + * + * @param items + * the source Observable + * @param num + * the number of items from the start of the sequence emitted by the source + * Observable to emit + * @return a Observable that only emits the first <code>num</code> items emitted by the source + * Observable + */ + public static <T> Observable<T> take(final Observable<T> items, final int num) { + return wrap(OperationTake.take(items, num)); + } + + /** + * Returns a Observable that emits a single item, a list composed of all the items emitted by + * the source Observable. + * <p> + * Normally, a Observable that returns multiple items will do so by calling its Observer's <code>onNext</code> closure for each such item. You can change this behavior, instructing the Observable + * to + * compose a list of all of these multiple items and + * then to call the Observer's <code>onNext</code> closure once, passing it the entire list, by calling the Observable object's <code>toList</code> method prior to calling its + * <code>subscribe</code> + * method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.tolist&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.tolist.png"></a> + * + * @param that + * the source Observable + * @return a Observable that emits a single item: a <code>List</code> containing all of the + * items emitted by the source Observable + */ + public static <T> Observable<List<T>> toList(final Observable<T> that) { + return wrap(OperationToObservableList.toObservableList(that)); + } + + /** + * Converts an Iterable sequence to a Observable sequence. + * + * Any object that supports the Iterable interface can be converted into a Observable that emits + * each iterable item in the object, by passing the object into the <code>toObservable</code> method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.toObservable&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.toObservable.png"></a> + * + * @param iterable + * the source Iterable sequence + * @param <T> + * the type of items in the iterable sequence and the type emitted by the resulting + * Observable + * @return a Observable that emits each item in the source Iterable sequence + */ + public static <T> Observable<T> toObservable(Iterable<T> iterable) { + return wrap(OperationToObservableIterable.toObservableIterable(iterable)); + } + + /** + * Converts an Array sequence to a Observable sequence. + * + * An Array can be converted into a Observable that emits each item in the Array, by passing the + * Array into the <code>toObservable</code> method. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.toObservable&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.toObservable.png"></a> + * + * @param iterable + * the source Array + * @param <T> + * the type of items in the Array, and the type of items emitted by the resulting + * Observable + * @return a Observable that emits each item in the source Array + */ + public static <T> Observable<T> toObservable(T... items) { + return toObservable(Arrays.asList(items)); + } + + /** + * Sort T objects by their natural order (object must implement Comparable). + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.tolistsorted&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.tolistsorted.png"></a> + * + * @param sequence + * @throws ClassCastException + * if T objects do not implement Comparable + * @return + */ + public static <T> Observable<List<T>> toSortedList(Observable<T> sequence) { + return wrap(OperationToObservableSortedList.toSortedList(sequence)); + } + + /** + * Sort T objects using the defined sort function. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.tolistsorted.f&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.tolistsorted.f.png"></a> + * + * @param sequence + * @param sortFunction + * @return + */ + public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, Func2<Integer, T, T> sortFunction) { + return wrap(OperationToObservableSortedList.toSortedList(sequence, sortFunction)); + } + + /** + * Sort T objects using the defined sort function. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.tolistsorted.f&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.tolistsorted.f.png"></a> + * + * @param sequence + * @param sortFunction + * @return + */ + public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, final Object sortFunction) { + return wrap(OperationToObservableSortedList.toSortedList(sequence, new Func2<Integer, T, T>() { + + @Override + public Integer call(T t1, T t2) { + return Functions.execute(sortFunction, t1, t2); + } + + })); + } + + /** + * Allow wrapping responses with the <code>AbstractObservable</code> so that we have all of + * the utility methods available for subscribing. + * <p> + * This is not expected to benefit Java usage, but is intended for dynamic script which are a primary target of the Observable operations. + * <p> + * Since they are dynamic they can execute the "hidden" methods on <code>AbstractObservable</code> while appearing to only receive an <code>Observable</code> without first casting. + * + * @param o + * @return + */ + private static <T> Observable<T> wrap(final Observable<T> o) { + if (o instanceof Observable) { + // if the Observable is already an AbstractObservable, don't wrap it again. + return (Observable<T>) o; + } + return new Observable<T>() { + + @Override + public Subscription subscribe(Observer<T> observer) { + return o.subscribe(observer); + } + + }; + } + + /** + * Returns a Observable that applies a closure of your choosing to the combination of items + * emitted, in sequence, by two other Observables, with the results of this closure becoming the + * sequence emitted by the returned Observable. + * <p> + * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code> + * and the first item emitted by <code>w1</code>; the + * second item emitted by the new Observable will be the result of the closure applied to the second item emitted by <code>w0</code> and the second item emitted by <code>w1</code>; and so forth. + * <p> + * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the + * shortest sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.png"></a> + * + * @param w0 + * one source Observable + * @param w1 + * another source Observable + * @param reduceFunction + * a closure that, when applied to an item emitted by each of the source Observables, + * results in a value that will be emitted by the resulting Observable + * @return a Observable that emits the zipped results + */ + public static <R, T0, T1> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Func2<R, T0, T1> reduceFunction) { + return wrap(OperationZip.zip(w0, w1, reduceFunction)); + } + + /** + * Returns a Observable that applies a closure of your choosing to the combination of items + * emitted, in sequence, by two other Observables, with the results of this closure becoming the + * sequence emitted by the returned Observable. + * <p> + * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code> + * and the first item emitted by <code>w1</code>; the + * second item emitted by the new Observable will be the result of the closure applied to the second item emitted by <code>w0</code> and the second item emitted by <code>w1</code>; and so forth. + * <p> + * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the + * shortest sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.png"></a> + * + * @param w0 + * one source Observable + * @param w1 + * another source Observable + * @param reduceFunction + * a closure that, when applied to an item emitted by each of the source Observables, + * results in a value that will be emitted by the resulting Observable + * @return a Observable that emits the zipped results + */ + public static <R, T0, T1> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, final Object function) { + return zip(w0, w1, new Func2<R, T0, T1>() { + + @Override + public R call(T0 t0, T1 t1) { + return Functions.execute(function, t0, t1); + } + + }); + } + + /** + * Returns a Observable that applies a closure of your choosing to the combination of items + * emitted, in sequence, by three other Observables, with the results of this closure becoming + * the sequence emitted by the returned Observable. + * <p> + * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code>, + * the first item emitted by <code>w1</code>, and the + * first item emitted by <code>w2</code>; the second item emitted by the new Observable will be the result of the closure applied to the second item emitted by <code>w0</code>, the second item + * emitted by <code>w1</code>, and the second item + * emitted by <code>w2</code>; and so forth. + * <p> + * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the + * shortest sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip.3&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.3.png"></a> + * + * @param w0 + * one source Observable + * @param w1 + * another source Observable + * @param w2 + * a third source Observable + * @param function + * a closure that, when applied to an item emitted by each of the source Observables, + * results in a value that will be emitted by the resulting Observable + * @return a Observable that emits the zipped results + */ + public static <R, T0, T1, T2> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Func3<R, T0, T1, T2> function) { + return wrap(OperationZip.zip(w0, w1, w2, function)); + } - public void onError(Exception e) { - handleError(e); - if (onError != null) { - executeCallback(onError, e); - } - } + /** + * Returns a Observable that applies a closure of your choosing to the combination of items + * emitted, in sequence, by three other Observables, with the results of this closure becoming + * the sequence emitted by the returned Observable. + * <p> + * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code>, + * the first item emitted by <code>w1</code>, and the + * first item emitted by <code>w2</code>; the second item emitted by the new Observable will be the result of the closure applied to the second item emitted by <code>w0</code>, the second item + * emitted by <code>w1</code>, and the second item + * emitted by <code>w2</code>; and so forth. + * <p> + * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the + * shortest sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip.3&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.3.png"></a> + * + * @param w0 + * one source Observable + * @param w1 + * another source Observable + * @param w2 + * a third source Observable + * @param function + * a closure that, when applied to an item emitted by each of the source Observables, + * results in a value that will be emitted by the resulting Observable + * @return a Observable that emits the zipped results + */ + public static <R, T0, T1, T2> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, final Object function) { + return zip(w0, w1, w2, new Func3<R, T0, T1, T2>() { - public void onNext(Object args) { - if (onNext == null) { - throw new RuntimeException("onNext must be implemented"); - } - executeCallback(onNext, args); + @Override + public R call(T0 t0, T1 t1, T2 t2) { + return Functions.execute(function, t0, t1, t2); } }); } /** - * When an error occurs in any Observer we will invoke this to allow it to be handled by the global APIObservableErrorHandler + * Returns a Observable that applies a closure of your choosing to the combination of items + * emitted, in sequence, by four other Observables, with the results of this closure becoming + * the sequence emitted by the returned Observable. + * <p> + * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code>, + * the first item emitted by <code>w1</code>, the + * first item emitted by <code>w2</code>, and the first item emitted by <code>w3</code>; the second item emitted by the new Observable will be the result of the closure applied to the second item + * emitted by each of those Observables; and so forth. + * <p> + * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the + * shortest sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip.4&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.4.png"></a> * - * @param e + * @param w0 + * one source Observable + * @param w1 + * another source Observable + * @param w2 + * a third source Observable + * @param w3 + * a fourth source Observable + * @param reduceFunction + * a closure that, when applied to an item emitted by each of the source Observables, + * results in a value that will be emitted by the resulting Observable + * @return a Observable that emits the zipped results */ - private static void handleError(Exception e) { - // plugins have been removed during opensourcing but the intention is to provide these hooks again + public static <R, T0, T1, T2, T3> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Observable<T3> w3, Func4<R, T0, T1, T2, T3> reduceFunction) { + return wrap(OperationZip.zip(w0, w1, w2, w3, reduceFunction)); } /** - * Execute the callback with the given arguments. + * Returns a Observable that applies a closure of your choosing to the combination of items + * emitted, in sequence, by four other Observables, with the results of this closure becoming + * the sequence emitted by the returned Observable. * <p> - * The callbacks align with the onCompleted, onError and onNext methods an an IObserver. + * <code>zip</code> applies this closure in strict sequence, so the first item emitted by the new Observable will be the result of the closure applied to the first item emitted by <code>w0</code>, + * the first item emitted by <code>w1</code>, the + * first item emitted by <code>w2</code>, and the first item emitted by <code>w3</code>; the second item emitted by the new Observable will be the result of the closure applied to the second item + * emitted by each of those Observables; and so forth. + * <p> + * The resulting <code>Observable<R></code> returned from <code>zip</code> will call <code>onNext</code> as many times as the number <code>onNext</code> calls of the source Observable with the + * shortest sequence. + * <p> + * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.zip.4&ceoid=27321465&key=API&pageId=27321465"><img + * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.zip.4.png"></a> * - * @param callback - * Object to be invoked. It is left to the implementing class to determine the type, such as a Groovy Closure or JRuby closure conversion. - * @param args + * @param w0 + * one source Observable + * @param w1 + * another source Observable + * @param w2 + * a third source Observable + * @param w3 + * a fourth source Observable + * @param function + * a closure that, when applied to an item emitted by each of the source Observables, + * results in a value that will be emitted by the resulting Observable + * @return a Observable that emits the zipped results */ - private void executeCallback(final Object callback, Object... args) { - Functions.execute(callback, args); + public static <R, T0, T1, T2, T3> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Observable<T3> w3, final Object function) { + return zip(w0, w1, w2, w3, new Func4<R, T0, T1, T2, T3>() { + + @Override + public R call(T0 t0, T1 t1, T2 t2, T3 t3) { + return Functions.execute(function, t0, t1, t2, t3); + } + + }); } /** @@ -205,7 +1504,7 @@ private void executeCallback(final Object callback, Object... args) { * evaluates as <code>true</code> */ public Observable<T> filter(Func1<Boolean, T> predicate) { - return ObservableExtensions.filter(this, predicate); + return filter(this, predicate); } /** @@ -221,7 +1520,7 @@ public Observable<T> filter(Func1<Boolean, T> predicate) { * evaluates as "true" */ public Observable<T> filter(final Object callback) { - return ObservableExtensions.filter(this, new Func1<Boolean, T>() { + return filter(this, new Func1<Boolean, T>() { public Boolean call(T t1) { return Functions.execute(callback, t1); @@ -239,7 +1538,7 @@ public Boolean call(T t1) { * @return a Observable that emits only the last item emitted by the original Observable */ public Observable<T> last() { - return ObservableExtensions.last(this); + return last(this); } /** @@ -255,7 +1554,7 @@ public Observable<T> last() { * closure to each item in the sequence emitted by the input Observable. */ public <R> Observable<R> map(Func1<R, T> func) { - return ObservableExtensions.map(this, func); + return map(this, func); } /** @@ -271,7 +1570,7 @@ public <R> Observable<R> map(Func1<R, T> func) { * closure to each item in the sequence emitted by the input Observable. */ public <R> Observable<R> map(final Object callback) { - return ObservableExtensions.map(this, new Func1<R, T>() { + return map(this, new Func1<R, T>() { public R call(T t1) { return Functions.execute(callback, t1); @@ -295,7 +1594,7 @@ public R call(T t1) { * Observables obtained from this transformation. */ public <R> Observable<R> mapMany(Func1<Observable<R>, T> func) { - return ObservableExtensions.mapMany(this, func); + return mapMany(this, func); } /** @@ -314,7 +1613,7 @@ public <R> Observable<R> mapMany(Func1<Observable<R>, T> func) { * Observables obtained from this transformation. */ public <R> Observable<R> mapMany(final Object callback) { - return ObservableExtensions.mapMany(this, new Func1<Observable<R>, T>() { + return mapMany(this, new Func1<Observable<R>, T>() { public Observable<R> call(T t1) { return Functions.execute(callback, t1); @@ -359,21 +1658,21 @@ public Observable<Notification<T>> materialize() { * @return the original Observable, with appropriately modified behavior */ public Observable<T> onErrorResumeNext(final Func1<Observable<T>, Exception> resumeFunction) { - return ObservableExtensions.onErrorResumeNext(this, resumeFunction); + return onErrorResumeNext(this, resumeFunction); } /** - * Instruct a Observable to pass control to another Observable rather than calling - * <code>onError</code> if it encounters an error. + * Instruct a Observable to emit a particular item rather than calling <code>onError</code> if + * it encounters an error. * * By default, when a Observable encounters an error that prevents it from emitting the expected * item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and * then quits without calling any more of its Observer's closures. The * <code>onErrorResumeNext</code> method changes this behavior. If you pass another Observable - * (<code>resumeSequence</code>) to a Observable's <code>onErrorResumeNext</code> method, if the + * (<code>resumeFunction</code>) to a Observable's <code>onErrorResumeNext</code> method, if the * original Observable encounters an error, instead of calling its Observer's * <code>onError</code> closure, it will instead relinquish control to - * <code>resumeSequence</code> which will call the Observer's <code>onNext</code> method if it + * <code>resumeFunction</code> which will call the Observer's <code>onNext</code> method if it * is able to do so. In such a case, because no Observable necessarily invokes * <code>onError</code>, the Observer may never know that an error happened. * @@ -383,25 +1682,30 @@ public Observable<T> onErrorResumeNext(final Func1<Observable<T>, Exception> res * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorresumenext&ceoid=27321465&key=API&pageId=27321465"><img * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorresumenext.png"></a> * - * @param resumeSequence - * @return the original Observable, with appropriately modified behavior + * @param resumeFunction + * @return the original Observable with appropriately modified behavior */ - public Observable<T> onErrorResumeNext(final Observable<T> resumeSequence) { - return ObservableExtensions.onErrorResumeNext(this, resumeSequence); + public Observable<T> onErrorResumeNext(final Object resumeFunction) { + return onErrorResumeNext(this, new Func1<Observable<T>, Exception>() { + + public Observable<T> call(Exception e) { + return Functions.execute(resumeFunction, e); + } + }); } /** - * Instruct a Observable to emit a particular item rather than calling <code>onError</code> if - * it encounters an error. + * Instruct a Observable to pass control to another Observable rather than calling + * <code>onError</code> if it encounters an error. * * By default, when a Observable encounters an error that prevents it from emitting the expected * item to its Observer, the Observable calls its Observer's <code>onError</code> closure, and * then quits without calling any more of its Observer's closures. The * <code>onErrorResumeNext</code> method changes this behavior. If you pass another Observable - * (<code>resumeFunction</code>) to a Observable's <code>onErrorResumeNext</code> method, if the + * (<code>resumeSequence</code>) to a Observable's <code>onErrorResumeNext</code> method, if the * original Observable encounters an error, instead of calling its Observer's * <code>onError</code> closure, it will instead relinquish control to - * <code>resumeFunction</code> which will call the Observer's <code>onNext</code> method if it + * <code>resumeSequence</code> which will call the Observer's <code>onNext</code> method if it * is able to do so. In such a case, because no Observable necessarily invokes * <code>onError</code>, the Observer may never know that an error happened. * @@ -411,16 +1715,11 @@ public Observable<T> onErrorResumeNext(final Observable<T> resumeSequence) { * <a href="https://confluence.corp.netflix.com/plugins/gliffy/viewlargediagram.action?name=marble.onerrorresumenext&ceoid=27321465&key=API&pageId=27321465"><img * src="https://confluence.corp.netflix.com/download/attachments/27321465/marble.onerrorresumenext.png"></a> * - * @param resumeFunction - * @return the original Observable with appropriately modified behavior + * @param resumeSequence + * @return the original Observable, with appropriately modified behavior */ - public Observable<T> onErrorResumeNext(final Object resumeFunction) { - return ObservableExtensions.onErrorResumeNext(this, new Func1<Observable<T>, Exception>() { - - public Observable<T> call(Exception e) { - return Functions.execute(resumeFunction, e); - } - }); + public Observable<T> onErrorResumeNext(final Observable<T> resumeSequence) { + return onErrorResumeNext(this, resumeSequence); } /** @@ -446,7 +1745,7 @@ public Observable<T> call(Exception e) { * @return the original Observable with appropriately modified behavior */ public Observable<T> onErrorReturn(Func1<T, Exception> resumeFunction) { - return ObservableExtensions.onErrorReturn(this, resumeFunction); + return onErrorReturn(this, resumeFunction); } /** @@ -473,7 +1772,7 @@ public Observable<T> onErrorReturn(Func1<T, Exception> resumeFunction) { * @return the original Observable with appropriately modified behavior */ public Observable<T> onErrorReturn(final Object resumeFunction) { - return ObservableExtensions.onErrorReturn(this, new Func1<T, Exception>() { + return onErrorReturn(this, new Func1<T, Exception>() { public T call(Exception e) { return Functions.execute(resumeFunction, e); @@ -505,7 +1804,7 @@ public T call(Exception e) { * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ public Observable<T> reduce(Func2<T, T, T> accumulator) { - return ObservableExtensions.reduce(this, accumulator); + return reduce(this, accumulator); } /** @@ -532,7 +1831,7 @@ public Observable<T> reduce(Func2<T, T, T> accumulator) { * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ public Observable<T> reduce(Object accumulator) { - return ObservableExtensions.reduce(this, accumulator); + return reduce(this, accumulator); } /** @@ -561,7 +1860,7 @@ public Observable<T> reduce(Object accumulator) { * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ public Observable<T> reduce(T initialValue, Func2<T, T, T> accumulator) { - return ObservableExtensions.reduce(this, initialValue, accumulator); + return reduce(this, initialValue, accumulator); } /** @@ -589,7 +1888,7 @@ public Observable<T> reduce(T initialValue, Func2<T, T, T> accumulator) { * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ public Observable<T> reduce(T initialValue, Object accumulator) { - return ObservableExtensions.reduce(this, initialValue, accumulator); + return reduce(this, initialValue, accumulator); } /** @@ -612,7 +1911,7 @@ public Observable<T> reduce(T initialValue, Object accumulator) { * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> */ public Observable<T> scan(Func2<T, T, T> accumulator) { - return ObservableExtensions.scan(this, accumulator); + return scan(this, accumulator); } /** @@ -636,7 +1935,7 @@ public Observable<T> scan(Func2<T, T, T> accumulator) { * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> */ public Observable<T> scan(final Object accumulator) { - return ObservableExtensions.scan(this, accumulator); + return scan(this, accumulator); } /** @@ -660,7 +1959,7 @@ public Observable<T> scan(final Object accumulator) { * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> */ public Observable<T> scan(T initialValue, Func2<T, T, T> accumulator) { - return ObservableExtensions.scan(this, initialValue, accumulator); + return scan(this, initialValue, accumulator); } /** @@ -684,7 +1983,7 @@ public Observable<T> scan(T initialValue, Func2<T, T, T> accumulator) { * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> */ public Observable<T> scan(final T initialValue, final Object accumulator) { - return ObservableExtensions.scan(this, initialValue, accumulator); + return scan(this, initialValue, accumulator); } /** @@ -702,7 +2001,7 @@ public Observable<T> scan(final T initialValue, final Object accumulator) { * not emit the first <code>num</code> items from that sequence. */ public Observable<T> skip(int num) { - return ObservableExtensions.skip(this, num); + return skip(this, num); } /** @@ -723,7 +2022,7 @@ public Observable<T> skip(int num) { * fewer than <code>num</code> items. */ public Observable<T> take(final int num) { - return ObservableExtensions.take(this, num); + return take(this, num); } /** @@ -744,7 +2043,7 @@ public Observable<T> take(final int num) { * the source Observable. */ public Observable<List<T>> toList() { - return ObservableExtensions.toList(this); + return toList(this); } /** @@ -758,7 +2057,7 @@ public Observable<List<T>> toList() { * @return */ public Observable<List<T>> toSortedList() { - return ObservableExtensions.toSortedList(this); + return toSortedList(this); } /** @@ -771,7 +2070,7 @@ public Observable<List<T>> toSortedList() { * @return */ public Observable<List<T>> toSortedList(Func2<Integer, T, T> sortFunction) { - return ObservableExtensions.toSortedList(this, sortFunction); + return toSortedList(this, sortFunction); } /** @@ -784,18 +2083,91 @@ public Observable<List<T>> toSortedList(Func2<Integer, T, T> sortFunction) { * @return */ public Observable<List<T>> toSortedList(final Object sortFunction) { - return ObservableExtensions.toSortedList(this, sortFunction); + return toSortedList(this, sortFunction); } public static class UnitTest { + private static interface ScriptAssertion { + public void error(Exception o); + + public void received(Object o); + } + + private static class TestFactory { + int counter = 1; + + @SuppressWarnings("unused") + public Observable<Integer> getNumbers() { + return toObservable(1, 3, 2, 5, 4); + } + + @SuppressWarnings("unused") + public TestObservable getObservable() { + return new TestObservable(counter++); + } + } + + private static class TestObservable extends Observable<String> { + private final int count; + + public TestObservable(int count) { + this.count = count; + } + + public Subscription subscribe(Observer<String> observer) { + + observer.onNext("hello_" + count); + observer.onCompleted(); + + return new Subscription() { + + public void unsubscribe() { + // unregister ... will never be called here since we are executing synchronously + } + + }; + } + } + @Mock ScriptAssertion assertion; + @Mock + Observer<Integer> w; + @Before public void before() { MockitoAnnotations.initMocks(this); } + private void runGroovyScript(String script) { + ClassLoader parent = getClass().getClassLoader(); + @SuppressWarnings("resource") + GroovyClassLoader loader = new GroovyClassLoader(parent); + + Binding binding = new Binding(); + binding.setVariable("mockApiCall", new TestFactory()); + binding.setVariable("a", assertion); + binding.setVariable("o", org.rx.reactive.Observable.class); + + /* parse the script and execute it */ + InvokerHelper.createScript(loader.parseClass(script), binding).run(); + } + + @Test + public void testCreateViaGroovy() { + runGroovyScript("o.create({it.onNext('hello');it.onCompleted();}).subscribe({ result -> a.received(result)});"); + verify(assertion, times(1)).received("hello"); + } + + @Test + public void testFilterViaGroovy() { + runGroovyScript("o.filter(o.toObservable(1, 2, 3), {it >= 2}).subscribe({ result -> a.received(result)});"); + verify(assertion, times(0)).received(1); + verify(assertion, times(1)).received(2); + verify(assertion, times(1)).received(3); + } + @Test public void testLast() { String script = "mockApiCall.getObservable().last().subscribe({ result -> a.received(result)});"; @@ -811,93 +2183,149 @@ public void testMap() { } @Test - public void testScriptWithOnNext() { - String script = "mockApiCall.getObservable().subscribe({ result -> a.received(result)})"; - runGroovyScript(script); - verify(assertion).received("hello_1"); + public void testMapViaGroovy() { + runGroovyScript("o.map(o.toObservable(1, 2, 3), {'hello_' + it}).subscribe({ result -> a.received(result)});"); + verify(assertion, times(1)).received("hello_" + 1); + verify(assertion, times(1)).received("hello_" + 2); + verify(assertion, times(1)).received("hello_" + 3); } @Test - public void testScriptWithMerge() { - String script = "o.merge(mockApiCall.getObservable(), mockApiCall.getObservable()).subscribe({ result -> a.received(result)});"; - runGroovyScript(script); - verify(assertion, times(1)).received("hello_1"); - verify(assertion, times(1)).received("hello_2"); + public void testMaterializeViaGroovy() { + runGroovyScript("o.materialize(o.toObservable(1, 2, 3)).subscribe({ result -> a.received(result)});"); + // we expect 4 onNext calls: 3 for 1, 2, 3 ObservableNotification.OnNext and 1 for ObservableNotification.OnCompleted + verify(assertion, times(4)).received(any(Notification.class)); + verify(assertion, times(0)).error(any(Exception.class)); } @Test - public void testScriptWithMaterialize() { - String script = "mockApiCall.getObservable().materialize().subscribe({ result -> a.received(result)});"; - runGroovyScript(script); - // 2 times: once for hello_1 and once for onCompleted - verify(assertion, times(2)).received(any(Notification.class)); + public void testMergeDelayErrorViaGroovy() { + runGroovyScript("o.mergeDelayError(o.toObservable(1, 2, 3), o.merge(o.toObservable(6), o.error(new NullPointerException()), o.toObservable(7)), o.toObservable(4, 5)).subscribe({ result -> a.received(result)}, { exception -> a.error(exception)});"); + verify(assertion, times(1)).received(1); + verify(assertion, times(1)).received(2); + verify(assertion, times(1)).received(3); + verify(assertion, times(1)).received(4); + verify(assertion, times(1)).received(5); + verify(assertion, times(1)).received(6); + verify(assertion, times(0)).received(7); + verify(assertion, times(1)).error(any(NullPointerException.class)); } @Test - public void testToSortedList() { - runGroovyScript("mockApiCall.getNumbers().toSortedList().subscribe({ result -> a.received(result)});"); - verify(assertion, times(1)).received(Arrays.asList(1, 2, 3, 4, 5)); + public void testMergeViaGroovy() { + runGroovyScript("o.merge(o.toObservable(1, 2, 3), o.merge(o.toObservable(6), o.error(new NullPointerException()), o.toObservable(7)), o.toObservable(4, 5)).subscribe({ result -> a.received(result)}, { exception -> a.error(exception)});"); + // executing synchronously so we can deterministically know what order things will come + verify(assertion, times(1)).received(1); + verify(assertion, times(1)).received(2); + verify(assertion, times(1)).received(3); + verify(assertion, times(0)).received(4); // the NPE will cause this sequence to be skipped + verify(assertion, times(0)).received(5); // the NPE will cause this sequence to be skipped + verify(assertion, times(1)).received(6); // this comes before the NPE so should exist + verify(assertion, times(0)).received(7);// this comes in the sequence after the NPE + verify(assertion, times(1)).error(any(NullPointerException.class)); } @Test - public void testToSortedListWithFunction() { - runGroovyScript("mockApiCall.getNumbers().toSortedList({a, b -> a - b}).subscribe({ result -> a.received(result)});"); - verify(assertion, times(1)).received(Arrays.asList(1, 2, 3, 4, 5)); + public void testReduce() { + Observable<Integer> Observable = toObservable(1, 2, 3, 4); + reduce(Observable, new Func2<Integer, Integer, Integer>() { + + @Override + public Integer call(Integer t1, Integer t2) { + return t1 + t2; + } + + }).subscribe(w); + // we should be called only once + verify(w, times(1)).onNext(anyInt()); + verify(w).onNext(10); } - private void runGroovyScript(String script) { - ClassLoader parent = getClass().getClassLoader(); - @SuppressWarnings("resource") - GroovyClassLoader loader = new GroovyClassLoader(parent); + @Test + public void testReduceWithInitialValue() { + Observable<Integer> Observable = toObservable(1, 2, 3, 4); + reduce(Observable, 50, new Func2<Integer, Integer, Integer>() { - Binding binding = new Binding(); - binding.setVariable("mockApiCall", new TestFactory()); - binding.setVariable("a", assertion); - binding.setVariable("o", org.rx.operations.ObservableExtensions.class); + @Override + public Integer call(Integer t1, Integer t2) { + return t1 + t2; + } - /* parse the script and execute it */ - InvokerHelper.createScript(loader.parseClass(script), binding).run(); + }).subscribe(w); + // we should be called only once + verify(w, times(1)).onNext(anyInt()); + verify(w).onNext(60); } - private static class TestFactory { - int counter = 1; - - @SuppressWarnings("unused") - public TestObservable getObservable() { - return new TestObservable(counter++); - } + @Test + public void testScriptWithMaterialize() { + String script = "mockApiCall.getObservable().materialize().subscribe({ result -> a.received(result)});"; + runGroovyScript(script); + // 2 times: once for hello_1 and once for onCompleted + verify(assertion, times(2)).received(any(Notification.class)); + } - @SuppressWarnings("unused") - public Observable<Integer> getNumbers() { - return ObservableExtensions.toObservable(1, 3, 2, 5, 4); - } + @Test + public void testScriptWithMerge() { + String script = "o.merge(mockApiCall.getObservable(), mockApiCall.getObservable()).subscribe({ result -> a.received(result)});"; + runGroovyScript(script); + verify(assertion, times(1)).received("hello_1"); + verify(assertion, times(1)).received("hello_2"); } - private static class TestObservable extends Observable<String> { - private final int count; + @Test + public void testScriptWithOnNext() { + String script = "mockApiCall.getObservable().subscribe({ result -> a.received(result)})"; + runGroovyScript(script); + verify(assertion).received("hello_1"); + } - public TestObservable(int count) { - this.count = count; - } + @Test + public void testSkipTakeViaGroovy() { + runGroovyScript("o.skip(o.toObservable(1, 2, 3), 1).take(1).subscribe({ result -> a.received(result)});"); + verify(assertion, times(0)).received(1); + verify(assertion, times(1)).received(2); + verify(assertion, times(0)).received(3); + } - public Subscription subscribe(Observer<String> observer) { + @Test + public void testSkipViaGroovy() { + runGroovyScript("o.skip(o.toObservable(1, 2, 3), 2).subscribe({ result -> a.received(result)});"); + verify(assertion, times(0)).received(1); + verify(assertion, times(0)).received(2); + verify(assertion, times(1)).received(3); + } - observer.onNext("hello_" + count); - observer.onCompleted(); + @Test + public void testTakeViaGroovy() { + runGroovyScript("o.take(o.toObservable(1, 2, 3), 2).subscribe({ result -> a.received(result)});"); + verify(assertion, times(1)).received(1); + verify(assertion, times(1)).received(2); + verify(assertion, times(0)).received(3); + } - return new Subscription() { + @Test + public void testToSortedList() { + runGroovyScript("mockApiCall.getNumbers().toSortedList().subscribe({ result -> a.received(result)});"); + verify(assertion, times(1)).received(Arrays.asList(1, 2, 3, 4, 5)); + } - public void unsubscribe() { - // unregister ... will never be called here since we are executing synchronously - } + @Test + public void testToSortedListStatic() { + runGroovyScript("o.toSortedList(o.toObservable(1, 3, 2, 5, 4)).subscribe({ result -> a.received(result)});"); + verify(assertion, times(1)).received(Arrays.asList(1, 2, 3, 4, 5)); + } - }; - } + @Test + public void testToSortedListWithFunction() { + runGroovyScript("mockApiCall.getNumbers().toSortedList({a, b -> a - b}).subscribe({ result -> a.received(result)});"); + verify(assertion, times(1)).received(Arrays.asList(1, 2, 3, 4, 5)); } - private static interface ScriptAssertion { - public void received(Object o); + @Test + public void testToSortedListWithFunctionStatic() { + runGroovyScript("o.toSortedList(o.toObservable(1, 3, 2, 5, 4), {a, b -> a - b}).subscribe({ result -> a.received(result)});"); + verify(assertion, times(1)).received(Arrays.asList(1, 2, 3, 4, 5)); } } - } diff --git a/rxjava-core/src/main/java/org/rx/reactive/package.html b/rxjava-core/src/main/java/org/rx/reactive/package.html index df8f6f043b..dd99e9f8dd 100644 --- a/rxjava-core/src/main/java/org/rx/reactive/package.html +++ b/rxjava-core/src/main/java/org/rx/reactive/package.html @@ -1,7 +1,7 @@ <body> <p>A library that enables subscribing to and composing asynchronous events and callbacks.</p> - <p>The Watchable/Watcher interfaces and associated operators (in + <p>The Observable/Observer interfaces and associated operators (in the .operations package) are inspired by and attempt to conform to the Reactive Rx library in Microsoft .Net.</p> <p> @@ -12,10 +12,10 @@ <p>Compared with the Microsoft implementation: <ul> - <li>Watchable == IObservable</li> - <li>Watcher == IObserver</li> - <li>WatchableSubscription == IDisposable</li> - <li>WatchableExtensions == Observable</li> + <li>Observable == IObservable</li> + <li>Observer == IObserver</li> + <li>Subscription == IDisposable</li> + <li>ObservableExtensions == Observable</li> </ul> </p> <p>Services which intend on exposing data asynchronously and wish
1ffcd613de9c2fcc691b31355c635df9ffd6caca
drools
JBRULES-446 Support rulebase configuration via- jsr94 registerRuleExecutionSet properties--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@13123 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/drools-jsr94/.classpath b/drools-jsr94/.classpath index cab36f7a135..332f406afe5 100644 --- a/drools-jsr94/.classpath +++ b/drools-jsr94/.classpath @@ -1,22 +1,24 @@ -<classpath> - <classpathentry kind="src" path="src/main/java"/> - <classpathentry kind="src" path="src/main/resources" excluding="**/*.java"/> - <classpathentry kind="src" path="src/test/java" output="target/test-classes"/> - <classpathentry kind="src" path="src/test/resources" output="target/test-classes" excluding="**/*.java"/> - <classpathentry kind="output" path="target/classes"/> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> - <classpathentry kind="var" path="M2_REPO/xpp3/xpp3/1.1.3.4.O/xpp3-1.1.3.4.O.jar"/> - <classpathentry kind="src" path="/drools-core"/> - <classpathentry kind="src" path="/drools-compiler"/> - <classpathentry kind="var" path="M2_REPO/xerces/xercesImpl/2.4.0/xercesImpl-2.4.0.jar"/> - <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/> - <classpathentry kind="var" path="M2_REPO/org/mvel/mvel14/1.2beta27/mvel14-1.2beta27.jar"/> - <classpathentry kind="var" path="M2_REPO/jsr94/jsr94/1.1/jsr94-1.1.jar"/> - <classpathentry kind="var" path="M2_REPO/org/eclipse/jdt/core/3.2.3.v_686_R32x/core-3.2.3.v_686_R32x.jar"/> - <classpathentry kind="var" path="M2_REPO/janino/janino/2.5.7/janino-2.5.7.jar"/> - <classpathentry kind="var" path="M2_REPO/org/antlr/antlr-runtime/3.0/antlr-runtime-3.0.jar"/> - <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-sigtest/1.1/jsr94-sigtest-1.1.jar"/> - <classpathentry kind="var" path="M2_REPO/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar"/> - <classpathentry kind="var" path="M2_REPO/xstream/xstream/1.1.3/xstream-1.1.3.jar"/> - <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-tck/1.0.3/jsr94-tck-1.0.3.jar"/> -</classpath> \ No newline at end of file +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src/main/java"/> + <classpathentry excluding="**/*.java" kind="src" path="src/main/resources"/> + <classpathentry kind="src" output="target/test-classes" path="src/test/java"/> + <classpathentry excluding="**/*.java" kind="src" output="target/test-classes" path="src/test/resources"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="var" path="M2_REPO/xpp3/xpp3/1.1.3.4.O/xpp3-1.1.3.4.O.jar"/> + <classpathentry kind="src" path="/drools-core"/> + <classpathentry kind="src" path="/drools-compiler"/> + <classpathentry kind="var" path="M2_REPO/xerces/xercesImpl/2.4.0/xercesImpl-2.4.0.jar"/> + <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/> + <classpathentry kind="var" path="M2_REPO/org/mvel/mvel14/1.2beta27/mvel14-1.2beta27.jar"/> + <classpathentry kind="var" path="M2_REPO/jsr94/jsr94/1.1/jsr94-1.1.jar"/> + <classpathentry kind="var" path="M2_REPO/org/eclipse/jdt/core/3.2.3.v_686_R32x/core-3.2.3.v_686_R32x.jar"/> + <classpathentry kind="var" path="M2_REPO/janino/janino/2.5.7/janino-2.5.7.jar"/> + <classpathentry kind="var" path="M2_REPO/org/antlr/antlr-runtime/3.0/antlr-runtime-3.0.jar"/> + <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-sigtest/1.1/jsr94-sigtest-1.1.jar"/> + <classpathentry kind="var" path="M2_REPO/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar"/> + <classpathentry kind="var" path="M2_REPO/xstream/xstream/1.1.3/xstream-1.1.3.jar"/> + <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-tck/1.0.3/jsr94-tck-1.0.3.jar"/> + <classpathentry combineaccessrules="false" kind="src" path="/drools-decisiontables"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java index 1de15d3560b..0c4b40f427d 100644 --- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java +++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java @@ -37,4 +37,18 @@ private Constants() { /** <code>RuleExecutionSet</code> description constant. */ public static final String RES_DESCRIPTION = "javax.rules.admin.RuleExecutionSet.description"; + + public static final String RES_SOURCE = "javax.rules.admin.RuleExecutionSet.source"; + + public static final String RES_SOURCE_TYPE_XML = "javax.rules.admin.RuleExecutionSet.source.xml"; + + public static final String RES_SOURCE_TYPE_DECISION_TABLE = "javax.rules.admin.RuleExecutionSet.source.decisiontable"; + + public static final String RES_DSRL = "javax.rules.admin.RuleExecutionSet.dsrl"; + + /** <code>RuleExecutionSet</code> rulebase config constant. */ + public static final String RES_RULEBASE_CONFIG = "javax.rules.admin.RuleExecutionSet.ruleBaseConfiguration"; + + /** <code>RuleExecutionSet</code> package builder config constant. */ + public static final String RES_PACKAGEBUILDER_CONFIG = "javax.rules.admin.RuleExecutionSet.ruleBaseConfiguration"; } diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java index 252567344e4..78cba0e8602 100644 --- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java +++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java @@ -30,6 +30,10 @@ import org.drools.IntegrationException; import org.drools.compiler.DroolsParserException; import org.drools.compiler.PackageBuilder; +import org.drools.compiler.PackageBuilderConfiguration; +import org.drools.decisiontable.InputType; +import org.drools.decisiontable.SpreadsheetCompiler; +import org.drools.jsr94.rules.Constants; import org.drools.rule.Package; /** @@ -73,8 +77,23 @@ public LocalRuleExecutionSetProviderImpl() { * @return The created <code>RuleExecutionSet</code>. */ public RuleExecutionSet createRuleExecutionSet(final InputStream ruleExecutionSetStream, - final Map properties) throws RuleExecutionSetCreateException { - return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties); + final Map properties) throws RuleExecutionSetCreateException { + if ( properties != null ) { + String source = ( String ) properties.get( Constants.RES_SOURCE ); + if ( source == null ) { + // support legacy name + source = ( String ) properties.get( "source" ); + } + if ( source != null && source.equals( Constants.RES_SOURCE_TYPE_DECISION_TABLE ) ) { + final SpreadsheetCompiler converter = new SpreadsheetCompiler(); + final String drl = converter.compile( ruleExecutionSetStream, + InputType.XLS ); + return createRuleExecutionSet( new StringReader( drl ), properties ); + } else { + return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties); + } + } else + return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties); } @@ -99,37 +118,56 @@ public RuleExecutionSet createRuleExecutionSet(final InputStream ruleExecutionSe public RuleExecutionSet createRuleExecutionSet(final Reader ruleExecutionSetReader, final Map properties) throws RuleExecutionSetCreateException { try { - final PackageBuilder builder = new PackageBuilder(); - Object dsl = null; + PackageBuilderConfiguration config= null; + + if ( properties != null ) { + config = (PackageBuilderConfiguration) properties.get( Constants.RES_PACKAGEBUILDER_CONFIG ); + } + + PackageBuilder builder = null; + if ( config != null ) { + builder = new PackageBuilder(config); + } else { + builder = new PackageBuilder(); + } + + Object dsrl = null; String source = null; if ( properties != null ) { - dsl = properties.get( "dsl" ); - source = ( String ) properties.get( "source" ); + dsrl = properties.get( Constants.RES_DSRL ); + if ( dsrl == null ) { + // check for old legacy name ending + dsrl = properties.get( "dsl" ); + } + source = ( String ) properties.get( Constants.RES_SOURCE ); + if ( source == null ) { + // check for old legacy name ending + source = ( String ) properties.get( "source" ); + } } if ( source == null ) { source = "drl"; - } - + } - if ( dsl == null ) { - if ( source.equals( "xml" ) ) { + if ( dsrl == null ) { + if ( source.equals( Constants.RES_SOURCE_TYPE_XML ) || source.equals( "xml" ) ) { builder.addPackageFromXml( ruleExecutionSetReader ); } else { builder.addPackageFromDrl( ruleExecutionSetReader ); } } else { - if ( source.equals( "xml" ) ) { + if ( source.equals( Constants.RES_SOURCE_TYPE_XML ) || source.equals( "xml" ) ) { // xml cannot specify a dsl builder.addPackageFromXml( ruleExecutionSetReader ); } else { - if ( dsl instanceof Reader ) { + if ( dsrl instanceof Reader ) { builder.addPackageFromDrl( ruleExecutionSetReader, - (Reader) dsl ); + (Reader) dsrl ); } else { builder.addPackageFromDrl( ruleExecutionSetReader, - new StringReader( (String) dsl ) ); + new StringReader( (String) dsrl ) ); } } } diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java index 6da640ecd37..3636b65ff09 100644 --- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java +++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java @@ -26,9 +26,11 @@ import org.drools.IntegrationException; import org.drools.RuleBase; +import org.drools.RuleBaseConfiguration; import org.drools.RuleIntegrationException; import org.drools.StatefulSession; import org.drools.StatelessSession; +import org.drools.jsr94.rules.Constants; import org.drools.jsr94.rules.Jsr94FactHandleFactory; import org.drools.rule.Package; import org.drools.rule.Rule; @@ -114,9 +116,17 @@ public class RuleExecutionSetImpl } this.pkg = pkg; this.description = pkg.getName();//..getDocumentation( ); - - final org.drools.reteoo.ReteooRuleBase ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(), - new Jsr94FactHandleFactory() ); + + RuleBaseConfiguration config = ( RuleBaseConfiguration ) this.properties.get( Constants.RES_RULEBASE_CONFIG ); + org.drools.reteoo.ReteooRuleBase ruleBase; + if ( config != null ) { + ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(), + config, + new Jsr94FactHandleFactory() ); + } else { + ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(), + new Jsr94FactHandleFactory() ); + } ruleBase.addPackage( pkg ); this.ruleBase = ruleBase; diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java b/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java new file mode 100644 index 00000000000..d6ae471da6e --- /dev/null +++ b/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java @@ -0,0 +1,45 @@ +package org.drools.decisiontable; + +/* + * Copyright 2005 JBoss Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +public class Cheese { + private String type; + private int price; + + public Cheese() { + + } + public Cheese(final String type, + final int price) { + super(); + this.type = type; + this.price = price; + } + + public int getPrice() { + return this.price; + } + + public String getType() { + return this.type; + } + + public void setPrice(final int price) { + this.price = price; + } + +} \ No newline at end of file diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java b/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java new file mode 100644 index 00000000000..b467a800e0a --- /dev/null +++ b/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java @@ -0,0 +1,93 @@ +package org.drools.decisiontable; + +/* + * Copyright 2005 JBoss Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +public class Person { + private String name; + private String likes; + private int age; + + private char sex; + + private boolean alive; + + private String status; + + public Person() { + + } + public Person(final String name) { + this( name, + "", + 0 ); + } + + public Person(final String name, + final String likes) { + this( name, + likes, + 0 ); + } + + public Person(final String name, + final String likes, + final int age) { + this.name = name; + this.likes = likes; + this.age = age; + } + + public String getStatus() { + return this.status; + } + + public void setStatus(final String status) { + this.status = status; + } + + public String getLikes() { + return this.likes; + } + + public String getName() { + return this.name; + } + + public int getAge() { + return this.age; + } + + public boolean isAlive() { + return this.alive; + } + + public void setAlive(final boolean alive) { + this.alive = alive; + } + + public char getSex() { + return this.sex; + } + + public void setSex(final char sex) { + this.sex = sex; + } + + public String toString() { + return "[Person name='" + this.name + "']"; + } +} \ No newline at end of file diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java b/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java new file mode 100644 index 00000000000..4a7c9e302e0 --- /dev/null +++ b/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java @@ -0,0 +1,91 @@ +package org.drools.decisiontable; + +/* + * Copyright 2005 JBoss Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.rules.RuleRuntime; +import javax.rules.RuleServiceProvider; +import javax.rules.RuleServiceProviderManager; +import javax.rules.RuleSession; +import javax.rules.StatefulRuleSession; +import javax.rules.admin.LocalRuleExecutionSetProvider; +import javax.rules.admin.RuleAdministrator; +import javax.rules.admin.RuleExecutionSet; + +import junit.framework.TestCase; + +import org.acme.insurance.launcher.PricingRuleLauncher; +import org.drools.RuleBase; +import org.drools.RuleBaseFactory; +import org.drools.WorkingMemory; +import org.drools.compiler.PackageBuilder; +import org.drools.jsr94.rules.Constants; +import org.drools.jsr94.rules.ExampleRuleEngineFacade; +import org.drools.jsr94.rules.RuleEngineTestBase; +import org.drools.jsr94.rules.RuleServiceProviderImpl; +import org.drools.rule.Package; + +public class SpreadsheetIntegrationTest extends TestCase { + + public void testExecute() throws Exception { + Map properties = new HashMap(); + properties.put( Constants.RES_SOURCE, + Constants.RES_SOURCE_TYPE_DECISION_TABLE ); + + RuleServiceProviderManager.registerRuleServiceProvider( ExampleRuleEngineFacade.RULE_SERVICE_PROVIDER, + RuleServiceProviderImpl.class ); + + RuleServiceProvider ruleServiceProvider = RuleServiceProviderManager.getRuleServiceProvider( ExampleRuleEngineFacade.RULE_SERVICE_PROVIDER ); + RuleAdministrator ruleAdministrator = ruleServiceProvider.getRuleAdministrator(); + LocalRuleExecutionSetProvider ruleSetProvider = ruleAdministrator.getLocalRuleExecutionSetProvider( null ); + + RuleExecutionSet ruleExecutionSet = ruleSetProvider.createRuleExecutionSet( SpreadsheetIntegrationTest.class.getResourceAsStream( "IntegrationExampleTest.xls" ), + properties ); + + ruleAdministrator.registerRuleExecutionSet( "IntegrationExampleTest.xls", + ruleExecutionSet, + properties ); + + properties.clear(); + final List list = new ArrayList(); + properties.put( "list", + list ); + + RuleRuntime ruleRuntime = ruleServiceProvider.getRuleRuntime(); + StatefulRuleSession session = (StatefulRuleSession) ruleRuntime.createRuleSession( "IntegrationExampleTest.xls", + properties, + RuleRuntime.STATEFUL_SESSION_TYPE ); + + //ASSERT AND FIRE + session.addObject( new Cheese( "stilton", + 42 ) ); + session.addObject( new Person( "michael", + "stilton", + 42 ) ); + + session.executeRules(); + assertEquals( 1, + list.size() ); + + } + +} \ No newline at end of file diff --git a/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java b/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java index 18128d1e679..f735ca4ee47 100644 --- a/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java +++ b/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java @@ -86,7 +86,7 @@ public ExampleRuleEngineFacade() throws Exception { this.ruleAdministrator = this.ruleServiceProvider.getRuleAdministrator(); this.ruleSetProvider = this.ruleAdministrator.getLocalRuleExecutionSetProvider( null ); - } + } public void addRuleExecutionSet(final String bindUri, final InputStream resourceAsStream) throws Exception { diff --git a/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls b/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls new file mode 100644 index 00000000000..adf5d9829a8 Binary files /dev/null and b/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls differ
90d8dade254b4f34fd28d498ce529efd2177c606
spring-framework
fixed bug related to array autogrow--
c
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java index 46424861a78a..8a4cf937be05 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java @@ -848,8 +848,9 @@ private Object growArrayIfNecessary(Object array, int index, String name) { for (int i = length; i < Array.getLength(newArray); i++) { Array.set(newArray, i, newValue(componentType, name)); } + // TODO this is not efficient because conversion may create a copy ... set directly because we know its assignable. setPropertyValue(name, newArray); - return newArray; + return getPropertyValue(name); } else { return array; @@ -953,10 +954,6 @@ else if (propValue.getClass().isArray()) { // TODO reduce this grow algorithm along side the null gap algorithm for setting lists below ... the two are inconsistent propValue = growArrayIfNecessary(propValue, arrayIndex, actualName); Array.set(propValue, arrayIndex, convertedValue); - PropertyValue newValue = new PropertyValue(actualName, propValue); - newValue.resolvedDescriptor = pd; - newValue.conversionNecessary = false; - setPropertyValue(newValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java index 7f04d7b5a6b4..299c99194ad0 100644 --- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java +++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java @@ -8,7 +8,6 @@ import java.util.Map; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.ConversionServiceFactory; @@ -92,7 +91,6 @@ public void listOfListsElementAutogrowObject() throws Exception { } @Test - @Ignore public void arrayOfLists() throws Exception { // TODO TypeDescriptor not capable of accessing nested element type for arrays request.setRequestURI("/nested/arrayOfLists"); @@ -101,7 +99,6 @@ public void arrayOfLists() throws Exception { } @Test - @Ignore public void map() throws Exception { request.setRequestURI("/nested/map"); request.addParameter("nested.map['apple'].foo", "bar");
610fa618aae58af50c12ee8d0c29d12b7460fd8a
spring-framework
SPR-9056 Make DelegatingWebMvcConfiguration- config callbacks not final--It should be possible to progress from extending-WebMvcConfigurerAdapter (w/ @EnableWebMvc) to extending-WebMvcConfigurationSupport directly, to extending-DelegatingWebMvcConfigurationSupport. This change-makes that possible.-
p
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java index 5571532ed7dd..68d2043269b4 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java @@ -51,52 +51,52 @@ public void setConfigurers(List<WebMvcConfigurer> configurers) { } @Override - protected final void addInterceptors(InterceptorRegistry registry) { + protected void addInterceptors(InterceptorRegistry registry) { configurers.addInterceptors(registry); } @Override - protected final void addViewControllers(ViewControllerRegistry registry) { + protected void addViewControllers(ViewControllerRegistry registry) { configurers.addViewControllers(registry); } @Override - protected final void addResourceHandlers(ResourceHandlerRegistry registry) { + protected void addResourceHandlers(ResourceHandlerRegistry registry) { configurers.addResourceHandlers(registry); } @Override - protected final void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + protected void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurers.configureDefaultServletHandling(configurer); } @Override - protected final void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { + protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { configurers.addArgumentResolvers(argumentResolvers); } @Override - protected final void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { + protected void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { configurers.addReturnValueHandlers(returnValueHandlers); } @Override - protected final void configureMessageConverters(List<HttpMessageConverter<?>> converters) { + protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { configurers.configureMessageConverters(converters); } @Override - protected final void addFormatters(FormatterRegistry registry) { + protected void addFormatters(FormatterRegistry registry) { configurers.addFormatters(registry); } @Override - protected final Validator getValidator() { + protected Validator getValidator() { return configurers.getValidator(); } @Override - protected final void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { + protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { configurers.configureHandlerExceptionResolvers(exceptionResolvers); }
25ac0cd0efda9c5e814ad55c3689a02848a749cb
restlet-framework-java
Fixed ZipClientHelper test case.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/local/ZipClientHelper.java b/modules/org.restlet/src/org/restlet/engine/local/ZipClientHelper.java index dbab6b0335..8ec8262514 100644 --- a/modules/org.restlet/src/org/restlet/engine/local/ZipClientHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/local/ZipClientHelper.java @@ -154,7 +154,7 @@ protected void handleGet(Request request, Response response, File file, Entity entity = new ZipEntryEntity(zipFile, entryName, metadataService); - if (entity.exists()) { + if (!entity.exists()) { response.setStatus(Status.CLIENT_ERROR_NOT_FOUND); } else { final Representation output;
87a3c302325e42b2ec6c08b893e3aff50e0f4bd0
restlet-framework-java
Fixed NPE in the dataservices extension due to bad- parsing of referential constraints.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.dataservices/src/org/restlet/ext/dataservices/internal/edm/EntityType.java b/modules/org.restlet.ext.dataservices/src/org/restlet/ext/dataservices/internal/edm/EntityType.java index 67e89be7b7..20d190d4e8 100755 --- a/modules/org.restlet.ext.dataservices/src/org/restlet/ext/dataservices/internal/edm/EntityType.java +++ b/modules/org.restlet.ext.dataservices/src/org/restlet/ext/dataservices/internal/edm/EntityType.java @@ -143,13 +143,7 @@ public Set<EntityType> getImportedEntityTypes() { Set<EntityType> result = new TreeSet<EntityType>(); for (NavigationProperty property : getAssociations()) { - try { - System.err.println(property.getToRole().getType()); - result.add(property.getToRole().getType()); - } catch (Throwable e) { - e.printStackTrace(); - System.out.println(e.getMessage()); - } + result.add(property.getToRole().getType()); } return result; }
0150f4371b246f708942d3c10094499aa827fd5e
intellij-community
TreeUi: NPE when in showCentered() no visible- rows in tree--
c
https://github.com/JetBrains/intellij-community
diff --git a/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java b/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java index 638c12b73e2cf..4fadb6e1fbc4c 100644 --- a/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java +++ b/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java @@ -412,6 +412,9 @@ public static ActionCallback showRowCentered(final JTree tree, final int row, fi public static ActionCallback showRowCentered(final JTree tree, final int row, final boolean centerHorizontally, boolean scroll) { final int visible = getVisibleRowCount(tree); + + if (visible <= 0) return new ActionCallback.Done(); + final int top = visible > 0 ? row - (visible - 1)/ 2 : row; final int bottom = visible > 0 ? top + visible - 1 : row; return showAndSelect(tree, top, bottom, row, -1, false, scroll); @@ -571,9 +574,13 @@ private static int getFirstVisibleRow(final JTree tree) { private static int getVisibleRowCount(final JTree tree) { final Rectangle visible = tree.getVisibleRect(); + + if (visible == null) return 0; + int count = 0; for (int i=0; i < tree.getRowCount(); i++) { final Rectangle bounds = tree.getRowBounds(i); + if (bounds == null) continue; if (visible.y <= bounds.y && visible.y + visible.height >= bounds.y + bounds.height) { count++; }
8507d724657e71365720d430c737670c962c528f
hadoop
Merge -c 1235858 from trunk to branch-0.23 to fix- MAPREDUCE-3683. Fixed maxCapacity of queues to be product of parent- maxCapacities.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1235860 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt index 697030062a585..0fc6b385df2e4 100644 --- a/hadoop-mapreduce-project/CHANGES.txt +++ b/hadoop-mapreduce-project/CHANGES.txt @@ -513,6 +513,9 @@ Release 0.23.1 - Unreleased MAPREDUCE-3630. Fixes a NullPointer exception while running TeraGen - if a map is asked to generate 0 records. (Mahadev Konar via sseth) + MAPREDUCE-3683. Fixed maxCapacity of queues to be product of parent + maxCapacities. (acmurthy) + Release 0.23.0 - 2011-11-01 INCOMPATIBLE CHANGES diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CSQueueUtils.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CSQueueUtils.java index c238a8ad95545..7d38dcdbe4178 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CSQueueUtils.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CSQueueUtils.java @@ -17,12 +17,19 @@ */ package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity; +import org.apache.hadoop.yarn.api.records.Resource; + class CSQueueUtils { public static void checkMaxCapacity(String queueName, float capacity, float maximumCapacity) { - if (Math.round(100 * maximumCapacity) != CapacitySchedulerConfiguration.UNDEFINED && + if (maximumCapacity < 0.0f || maximumCapacity > 1.0f || maximumCapacity < capacity) { + throw new IllegalArgumentException( + "Illegal value of maximumCapacity " + maximumCapacity + + " used in call to setMaxCapacity for queue " + queueName); + } + if (maximumCapacity < capacity) { throw new IllegalArgumentException( "Illegal call to setMaxCapacity. " + "Queue '" + queueName + "' has " + @@ -30,5 +37,26 @@ public static void checkMaxCapacity(String queueName, "maximumCapacity (" + maximumCapacity + ")" ); } } + + public static float computeAbsoluteMaximumCapacity( + float maximumCapacity, CSQueue parent) { + float parentAbsMaxCapacity = + (parent == null) ? 1.0f : parent.getAbsoluteMaximumCapacity(); + return (parentAbsMaxCapacity * maximumCapacity); + } + + public static int computeMaxActiveApplications(Resource clusterResource, + float maxAMResourcePercent, float absoluteCapacity) { + return + Math.max( + (int)((clusterResource.getMemory() / (float)LeafQueue.DEFAULT_AM_RESOURCE) * + maxAMResourcePercent * absoluteCapacity), + 1); + } + + public static int computeMaxActiveApplicationsPerUser( + int maxActiveApplications, int userLimit, float userLimitFactor) { + return (int)(maxActiveApplications * (userLimit / 100.0f) * userLimitFactor); + } } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java index 911b9ef673ebc..1995739c5bf9b 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java @@ -149,7 +149,7 @@ public int getCapacity(String queue) { throw new IllegalArgumentException("Illegal " + "capacity of " + capacity + " for queue " + queue); } - LOG.debug("CSConf - setCapacity: queuePrefix=" + getQueuePrefix(queue) + + LOG.debug("CSConf - getCapacity: queuePrefix=" + getQueuePrefix(queue) + ", capacity=" + capacity); return capacity; } @@ -162,11 +162,15 @@ public void setCapacity(String queue, int capacity) { public int getMaximumCapacity(String queue) { int maxCapacity = - getInt(getQueuePrefix(queue) + MAXIMUM_CAPACITY, UNDEFINED); + getInt(getQueuePrefix(queue) + MAXIMUM_CAPACITY, MAXIMUM_CAPACITY_VALUE); return maxCapacity; } public void setMaximumCapacity(String queue, int maxCapacity) { + if (maxCapacity > MAXIMUM_CAPACITY_VALUE) { + throw new IllegalArgumentException("Illegal " + + "maximum-capacity of " + maxCapacity + " for queue " + queue); + } setInt(getQueuePrefix(queue) + MAXIMUM_CAPACITY, maxCapacity); LOG.debug("CSConf - setMaxCapacity: queuePrefix=" + getQueuePrefix(queue) + ", maxCapacity=" + maxCapacity); diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java index b8d89878ec2b7..402e03a35abc0 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java @@ -144,10 +144,10 @@ public LeafQueue(CapacitySchedulerContext cs, (float)cs.getConfiguration().getCapacity(getQueuePath()) / 100; float absoluteCapacity = parent.getAbsoluteCapacity() * capacity; - float maximumCapacity = (float)cs.getConfiguration().getMaximumCapacity(getQueuePath()) / 100; + float maximumCapacity = + (float)cs.getConfiguration().getMaximumCapacity(getQueuePath()) / 100; float absoluteMaxCapacity = - (Math.round(maximumCapacity * 100) == CapacitySchedulerConfiguration.UNDEFINED) ? - Float.MAX_VALUE : (parent.getAbsoluteCapacity() * maximumCapacity); + CSQueueUtils.computeAbsoluteMaximumCapacity(maximumCapacity, parent); int userLimit = cs.getConfiguration().getUserLimit(getQueuePath()); float userLimitFactor = @@ -161,10 +161,10 @@ public LeafQueue(CapacitySchedulerContext cs, this.maxAMResourcePercent = cs.getConfiguration().getMaximumApplicationMasterResourcePercent(); int maxActiveApplications = - computeMaxActiveApplications(cs.getClusterResources(), + CSQueueUtils.computeMaxActiveApplications(cs.getClusterResources(), maxAMResourcePercent, absoluteCapacity); int maxActiveApplicationsPerUser = - computeMaxActiveApplicationsPerUser(maxActiveApplications, userLimit, + CSQueueUtils.computeMaxActiveApplicationsPerUser(maxActiveApplications, userLimit, userLimitFactor); this.queueInfo = recordFactory.newRecordInstance(QueueInfo.class); @@ -193,20 +193,6 @@ public LeafQueue(CapacitySchedulerContext cs, this.activeApplications = new TreeSet<SchedulerApp>(applicationComparator); } - private int computeMaxActiveApplications(Resource clusterResource, - float maxAMResourcePercent, float absoluteCapacity) { - return - Math.max( - (int)((clusterResource.getMemory() / (float)DEFAULT_AM_RESOURCE) * - maxAMResourcePercent * absoluteCapacity), - 1); - } - - private int computeMaxActiveApplicationsPerUser(int maxActiveApplications, - int userLimit, float userLimitFactor) { - return (int)(maxActiveApplications * (userLimit / 100.0f) * userLimitFactor); - } - private synchronized void setupQueueConfigs( float capacity, float absoluteCapacity, float maximumCapacity, float absoluteMaxCapacity, @@ -254,8 +240,8 @@ private synchronized void setupQueueConfigs( "maxCapacity = " + maximumCapacity + " [= configuredMaxCapacity ]" + "\n" + "absoluteMaxCapacity = " + absoluteMaxCapacity + - " [= Float.MAX_VALUE if maximumCapacity undefined, " + - "(parentAbsoluteCapacity * maximumCapacity) / 100 otherwise ]" + "\n" + + " [= 1.0 maximumCapacity undefined, " + + "(parentAbsoluteMaxCapacity * maximumCapacity) / 100 otherwise ]" + "\n" + "userLimit = " + userLimit + " [= configuredUserLimit ]" + "\n" + "userLimitFactor = " + userLimitFactor + @@ -400,9 +386,7 @@ synchronized void setMaxCapacity(float maximumCapacity) { this.maximumCapacity = maximumCapacity; this.absoluteMaxCapacity = - (Math.round(maximumCapacity * 100) == CapacitySchedulerConfiguration.UNDEFINED) ? - Float.MAX_VALUE : - (parent.getAbsoluteCapacity() * maximumCapacity); + CSQueueUtils.computeAbsoluteMaximumCapacity(maximumCapacity, parent); } /** @@ -835,13 +819,14 @@ private synchronized boolean assignToQueue(Resource clusterResource, float potentialNewCapacity = (float)(usedResources.getMemory() + required.getMemory()) / clusterResource.getMemory(); - LOG.info(getQueueName() + - " usedResources: " + usedResources.getMemory() + - " currentCapacity " + ((float)usedResources.getMemory())/clusterResource.getMemory() + - " required " + required.getMemory() + - " potentialNewCapacity: " + potentialNewCapacity + " ( " + - " max-capacity: " + absoluteMaxCapacity + ")"); if (potentialNewCapacity > absoluteMaxCapacity) { + LOG.info(getQueueName() + + " usedResources: " + usedResources.getMemory() + + " clusterResources: " + clusterResource.getMemory() + + " currentCapacity " + ((float)usedResources.getMemory())/clusterResource.getMemory() + + " required " + required.getMemory() + + " potentialNewCapacity: " + potentialNewCapacity + " ( " + + " max-capacity: " + absoluteMaxCapacity + ")"); return false; } return true; @@ -1308,10 +1293,10 @@ synchronized void releaseResource(Resource clusterResource, public synchronized void updateClusterResource(Resource clusterResource) { // Update queue properties maxActiveApplications = - computeMaxActiveApplications(clusterResource, maxAMResourcePercent, + CSQueueUtils.computeMaxActiveApplications(clusterResource, maxAMResourcePercent, absoluteCapacity); maxActiveApplicationsPerUser = - computeMaxActiveApplicationsPerUser(maxActiveApplications, userLimit, + CSQueueUtils.computeMaxActiveApplicationsPerUser(maxActiveApplications, userLimit, userLimitFactor); // Update application properties diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java index 41ef854847980..7d3acc5ad3888 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java @@ -118,16 +118,14 @@ public ParentQueue(CapacitySchedulerContext cs, } float capacity = (float) rawCapacity / 100; - float parentAbsoluteCapacity = - (parent == null) ? 1.0f : parent.getAbsoluteCapacity(); + (rootQueue) ? 1.0f : parent.getAbsoluteCapacity(); float absoluteCapacity = parentAbsoluteCapacity * capacity; - float maximumCapacity = + float maximumCapacity = (float) cs.getConfiguration().getMaximumCapacity(getQueuePath()) / 100; float absoluteMaxCapacity = - (Math.round(maximumCapacity * 100) == CapacitySchedulerConfiguration.UNDEFINED) ? - Float.MAX_VALUE : (parentAbsoluteCapacity * maximumCapacity); + CSQueueUtils.computeAbsoluteMaximumCapacity(maximumCapacity, parent); QueueState state = cs.getConfiguration().getState(getQueuePath()); @@ -497,12 +495,8 @@ synchronized void setMaxCapacity(float maximumCapacity) { CSQueueUtils.checkMaxCapacity(getQueueName(), capacity, maximumCapacity); this.maximumCapacity = maximumCapacity; - float parentAbsoluteCapacity = - (rootQueue) ? 100.0f : parent.getAbsoluteCapacity(); this.absoluteMaxCapacity = - (maximumCapacity == CapacitySchedulerConfiguration.UNDEFINED) ? - Float.MAX_VALUE : - (parentAbsoluteCapacity * maximumCapacity); + CSQueueUtils.computeAbsoluteMaximumCapacity(maximumCapacity, parent); } @Override diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.java index 534697099cf83..bee6e02553a54 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.java @@ -255,7 +255,7 @@ public void testSingleQueueWithOneUser() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity - a.setMaxCapacity(-0.01f); + a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; @@ -377,7 +377,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { // Mock the queue LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity - a.setMaxCapacity(-0.01f); + a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; @@ -491,7 +491,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { // Revert max-capacity and user-limit-factor // Now, allocations should goto app_3 since it's under user-limit - a.setMaxCapacity(-0.01f); + a.setMaxCapacity(1.0f); a.setUserLimitFactor(1); a.assignContainers(clusterResource, node_0); assertEquals(7*GB, a.getUsedResources().getMemory()); @@ -548,7 +548,7 @@ public void testReservation() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity - a.setMaxCapacity(-0.01f); + a.setMaxCapacity(1.0f); // Users final String user_0 = "user_0"; @@ -571,7 +571,7 @@ public void testReservation() throws Exception { String host_0 = "host_0"; SchedulerNode node_0 = TestUtils.getMockNode(host_0, DEFAULT_RACK, 0, 4*GB); - final int numNodes = 1; + final int numNodes = 2; Resource clusterResource = Resources.createResource(numNodes * (4*GB)); when(csContext.getNumClusterNodes()).thenReturn(numNodes); @@ -646,7 +646,7 @@ public void testReservationExchange() throws Exception { // Manipulate queue 'a' LeafQueue a = stubLeafQueue((LeafQueue)queues.get(A)); //unset maxCapacity - a.setMaxCapacity(-0.01f); + a.setMaxCapacity(1.0f); a.setUserLimitFactor(10); // Users @@ -673,7 +673,7 @@ public void testReservationExchange() throws Exception { String host_1 = "host_1"; SchedulerNode node_1 = TestUtils.getMockNode(host_1, DEFAULT_RACK, 0, 4*GB); - final int numNodes = 2; + final int numNodes = 3; Resource clusterResource = Resources.createResource(numNodes * (4*GB)); when(csContext.getNumClusterNodes()).thenReturn(numNodes); when(csContext.getMaximumResourceCapability()).thenReturn( diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestQueueParsing.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestQueueParsing.java index c78924644e04a..8802c9dd11639 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestQueueParsing.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestQueueParsing.java @@ -30,6 +30,8 @@ public class TestQueueParsing { private static final Log LOG = LogFactory.getLog(TestQueueParsing.class); + private static final double DELTA = 0.000001; + @Test public void testQueueParsing() throws Exception { CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); @@ -37,6 +39,20 @@ public void testQueueParsing() throws Exception { CapacityScheduler capacityScheduler = new CapacityScheduler(); capacityScheduler.reinitialize(conf, null, null); + + CSQueue a = capacityScheduler.getQueue("a"); + Assert.assertEquals(0.10, a.getAbsoluteCapacity(), DELTA); + Assert.assertEquals(0.15, a.getAbsoluteMaximumCapacity(), DELTA); + + CSQueue b1 = capacityScheduler.getQueue("b1"); + Assert.assertEquals(0.2 * 0.5, b1.getAbsoluteCapacity(), DELTA); + Assert.assertEquals("Parent B has no MAX_CAP", + 0.85, b1.getAbsoluteMaximumCapacity(), DELTA); + + CSQueue c12 = capacityScheduler.getQueue("c12"); + Assert.assertEquals(0.7 * 0.5 * 0.45, c12.getAbsoluteCapacity(), DELTA); + Assert.assertEquals(0.7 * 0.55 * 0.7, + c12.getAbsoluteMaximumCapacity(), DELTA); } private void setupQueueConfiguration(CapacitySchedulerConfiguration conf) { @@ -47,12 +63,14 @@ private void setupQueueConfiguration(CapacitySchedulerConfiguration conf) { final String A = CapacitySchedulerConfiguration.ROOT + ".a"; conf.setCapacity(A, 10); + conf.setMaximumCapacity(A, 15); final String B = CapacitySchedulerConfiguration.ROOT + ".b"; conf.setCapacity(B, 20); - + final String C = CapacitySchedulerConfiguration.ROOT + ".c"; conf.setCapacity(C, 70); + conf.setMaximumCapacity(C, 70); LOG.info("Setup top-level queues"); @@ -61,15 +79,20 @@ private void setupQueueConfiguration(CapacitySchedulerConfiguration conf) { final String A2 = A + ".a2"; conf.setQueues(A, new String[] {"a1", "a2"}); conf.setCapacity(A1, 30); + conf.setMaximumCapacity(A1, 45); conf.setCapacity(A2, 70); + conf.setMaximumCapacity(A2, 85); final String B1 = B + ".b1"; final String B2 = B + ".b2"; final String B3 = B + ".b3"; conf.setQueues(B, new String[] {"b1", "b2", "b3"}); conf.setCapacity(B1, 50); + conf.setMaximumCapacity(B1, 85); conf.setCapacity(B2, 30); + conf.setMaximumCapacity(B2, 35); conf.setCapacity(B3, 20); + conf.setMaximumCapacity(B3, 35); final String C1 = C + ".c1"; final String C2 = C + ".c2"; @@ -77,9 +100,13 @@ private void setupQueueConfiguration(CapacitySchedulerConfiguration conf) { final String C4 = C + ".c4"; conf.setQueues(C, new String[] {"c1", "c2", "c3", "c4"}); conf.setCapacity(C1, 50); + conf.setMaximumCapacity(C1, 55); conf.setCapacity(C2, 10); + conf.setMaximumCapacity(C2, 25); conf.setCapacity(C3, 35); + conf.setMaximumCapacity(C3, 38); conf.setCapacity(C4, 5); + conf.setMaximumCapacity(C4, 5); LOG.info("Setup 2nd-level queues"); @@ -89,8 +116,11 @@ private void setupQueueConfiguration(CapacitySchedulerConfiguration conf) { final String C13 = C1 + ".c13"; conf.setQueues(C1, new String[] {"c11", "c12", "c13"}); conf.setCapacity(C11, 15); + conf.setMaximumCapacity(C11, 30); conf.setCapacity(C12, 45); + conf.setMaximumCapacity(C12, 70); conf.setCapacity(C13, 40); + conf.setMaximumCapacity(C13, 40); LOG.info("Setup 3rd-level queues"); } diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesCapacitySched.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesCapacitySched.java index 4c6ea02b533c6..b82171e1eae5b 100644 --- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesCapacitySched.java +++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesCapacitySched.java @@ -235,12 +235,13 @@ public void verifyClusterSchedulerXML(NodeList nodes) throws Exception { Element qElem = (Element) queues.item(j); String qName = WebServicesTestUtils.getXmlString(qElem, "queueName"); String q = CapacitySchedulerConfiguration.ROOT + "." + qName; - verifySubQueueXML(qElem, q, 100); + verifySubQueueXML(qElem, q, 100, 100); } } } - public void verifySubQueueXML(Element qElem, String q, float parentAbsCapacity) + public void verifySubQueueXML(Element qElem, String q, + float parentAbsCapacity, float parentAbsMaxCapacity) throws Exception { NodeList queues = qElem.getElementsByTagName("subQueues"); QueueInfo qi = (queues != null) ? new QueueInfo() : new LeafQueueInfo(); @@ -258,14 +259,15 @@ public void verifySubQueueXML(Element qElem, String q, float parentAbsCapacity) WebServicesTestUtils.getXmlString(qElem, "usedResources"); qi.queueName = WebServicesTestUtils.getXmlString(qElem, "queueName"); qi.state = WebServicesTestUtils.getXmlString(qElem, "state"); - verifySubQueueGeneric(q, qi, parentAbsCapacity); + verifySubQueueGeneric(q, qi, parentAbsCapacity, parentAbsMaxCapacity); if (queues != null) { for (int j = 0; j < queues.getLength(); j++) { Element subqElem = (Element) queues.item(j); String qName = WebServicesTestUtils.getXmlString(subqElem, "queueName"); String q2 = q + "." + qName; - verifySubQueueXML(subqElem, q2, qi.absoluteCapacity); + verifySubQueueXML(subqElem, q2, + qi.absoluteCapacity, qi.absoluteMaxCapacity); } } else { LeafQueueInfo lqi = (LeafQueueInfo) qi; @@ -309,7 +311,7 @@ private void verifyClusterScheduler(JSONObject json) throws JSONException, for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); String q = CapacitySchedulerConfiguration.ROOT + "." + obj.getString("queueName"); - verifySubQueue(obj, q, 100); + verifySubQueue(obj, q, 100, 100); } } @@ -323,7 +325,8 @@ private void verifyClusterSchedulerGeneric(String type, float usedCapacity, assertTrue("queueName doesn't match", "root".matches(queueName)); } - private void verifySubQueue(JSONObject info, String q, float parentAbsCapacity) + private void verifySubQueue(JSONObject info, String q, + float parentAbsCapacity, float parentAbsMaxCapacity) throws JSONException, Exception { int numExpectedElements = 11; boolean isParentQueue = true; @@ -345,7 +348,7 @@ private void verifySubQueue(JSONObject info, String q, float parentAbsCapacity) qi.queueName = info.getString("queueName"); qi.state = info.getString("state"); - verifySubQueueGeneric(q, qi, parentAbsCapacity); + verifySubQueueGeneric(q, qi, parentAbsCapacity, parentAbsMaxCapacity); if (isParentQueue) { JSONArray arr = info.getJSONArray("subQueues"); @@ -353,7 +356,7 @@ private void verifySubQueue(JSONObject info, String q, float parentAbsCapacity) for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); String q2 = q + "." + obj.getString("queueName"); - verifySubQueue(obj, q2, qi.absoluteCapacity); + verifySubQueue(obj, q2, qi.absoluteCapacity, qi.absoluteMaxCapacity); } } else { LeafQueueInfo lqi = (LeafQueueInfo) qi; @@ -371,7 +374,7 @@ private void verifySubQueue(JSONObject info, String q, float parentAbsCapacity) } private void verifySubQueueGeneric(String q, QueueInfo info, - float parentAbsCapacity) throws Exception { + float parentAbsCapacity, float parentAbsMaxCapacity) throws Exception { String[] qArr = q.split("\\."); assertTrue("q name invalid: " + q, qArr.length > 1); String qshortName = qArr[qArr.length - 1]; @@ -380,7 +383,7 @@ private void verifySubQueueGeneric(String q, QueueInfo info, assertEquals("capacity doesn't match", csConf.getCapacity(q), info.capacity, 1e-3f); float expectCapacity = csConf.getMaximumCapacity(q); - float expectAbsMaxCapacity = parentAbsCapacity * (info.maxCapacity/100); + float expectAbsMaxCapacity = parentAbsMaxCapacity * (info.maxCapacity/100); if (CapacitySchedulerConfiguration.UNDEFINED == expectCapacity) { expectCapacity = 100; expectAbsMaxCapacity = 100;
3df7007006114f98fde14577b0f77b560a435743
drools
Added Analysis Result as HTML--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@15004 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/experimental/drools-analytics/src/main/java/org/drools/analytics/result/ReportModeller.java b/experimental/drools-analytics/src/main/java/org/drools/analytics/result/ReportModeller.java index c7621b7fbf3..1f7b88cb16d 100644 --- a/experimental/drools-analytics/src/main/java/org/drools/analytics/result/ReportModeller.java +++ b/experimental/drools-analytics/src/main/java/org/drools/analytics/result/ReportModeller.java @@ -3,12 +3,18 @@ import org.drools.analytics.components.LiteralRestriction; import com.thoughtworks.xstream.XStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import org.drools.analytics.Analyzer; /** * * @author Toni Rikkola */ public class ReportModeller { + + private static String cssFile = "basic.css"; public static String writeXML(AnalysisResultNormal result) { XStream xstream = new XStream(); @@ -59,5 +65,134 @@ public static String writePlainText(AnalysisResultNormal result) { return str.toString(); } + + public static String writeHTML(AnalysisResultNormal result) { + StringBuffer str = new StringBuffer(""); + str.append("<html>\n"); + str.append("<head>\n"); + str.append("<title>\n"); + str.append("Analysis Result\n"); + str.append("</title>\n"); + //str.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"basic.css\" title=\"default\">\n"); + + str.append("<style type=\"text/css\">\n"); + str.append("<!--\n"); + BufferedReader reader = new BufferedReader(new InputStreamReader(Analyzer.class.getResourceAsStream(cssFile))); + try{ + String cssLine = null; + while((cssLine = reader.readLine()) != null) + { + str.append(cssLine); + str.append("\n"); + } + } + catch(IOException e) + { + e.printStackTrace(); + } + str.append("-->\n"); + str.append("</style>\n"); + + str.append("</head>\n"); + str.append("<body>\n\n"); + + str.append("<br>\n"); + str.append("<h1>\n"); + str.append("Analysis results"); + str.append("</h1>\n"); + str.append("<br>\n"); + + if(result.getErrors().size() > 0) + { + str.append("<table class=\"errors\">\n"); + str.append("<tr>\n"); + str.append("<th>\n"); + str.append("ERRORS ("); + str.append(result.getErrors().size()); + str.append(")\n"); + str.append("</th>\n"); + str.append("</tr>\n"); + for (AnalysisError error : result.getErrors()) { + str.append("<tr>\n"); + str.append("<td>\n"); + str.append(error); + str.append("</td>\n"); + str.append("</tr>\n"); + } + str.append("</table>\n"); + + str.append("<br>\n"); + str.append("<br>\n"); + } + + if(result.getWarnings().size() > 0) + { + str.append("<table class=\"warnings\">\n"); + str.append("<tr>\n"); + str.append("<th>\n"); + str.append("WARNINGS ("); + str.append(result.getWarnings().size()); + str.append(")\n"); + str.append("</th>\n"); + str.append("</tr>\n"); + for (AnalysisWarning warning : result.getWarnings()) { + str.append("<tr>\n"); + str.append("<td>\n"); + + str.append("Warning id = "); + str.append(warning.getId()); + str.append(":<BR>\n"); + + if (warning.getRuleName() != null) { + str.append("in rule "); + str.append(warning.getRuleName()); + str.append(": "); + } + + str.append(warning.getMessage()); + str.append("<BR>\n"); + str.append("&nbsp;&nbsp; Causes are [<BR>\n"); + + for (Cause cause : warning.getCauses()) { + str.append("&nbsp;&nbsp;&nbsp;&nbsp;"); + str.append(cause); + str.append("<BR>\n"); + } + str.append("&nbsp;&nbsp; ]\n"); + + str.append("</td>\n"); + str.append("</tr>\n"); + } + str.append("</table>\n"); + + str.append("<br>\n"); + str.append("<br>\n"); + } + + if(result.getNotes().size() > 0) + { + str.append("<table class=\"notes\">\n"); + str.append("<tr>\n"); + str.append("<th>\n"); + str.append("NOTES ("); + str.append(result.getNotes().size()); + str.append(")\n"); + str.append("</th>\n"); + str.append("</tr>\n"); + for (AnalysisNote note : result.getNotes()) { + str.append("<tr>\n"); + str.append("<td>\n"); + str.append(note); + str.append("</td>\n"); + str.append("</tr>\n"); + } + str.append("</table>\n"); + } + + str.append("</body>\n"); + str.append("</html>"); + + return str.toString(); + } } diff --git a/experimental/drools-analytics/src/test/resources/org/drools/analytics/AnalyticsTest.java b/experimental/drools-analytics/src/test/resources/org/drools/analytics/AnalyticsTest.java new file mode 100644 index 00000000000..c1c8cf911c2 --- /dev/null +++ b/experimental/drools-analytics/src/test/resources/org/drools/analytics/AnalyticsTest.java @@ -0,0 +1,43 @@ +package org.drools.analytics; + +import java.io.InputStreamReader; + +import org.drools.compiler.DrlParser; +import org.drools.lang.descr.PackageDescr; + +/** + * This is a sample file to launch a rule package from a rule source file. + */ +class AnalyticsTest { + + public static final void main(String[] args) { + try { + PackageDescr descr = new DrlParser().parse(new InputStreamReader( + Analyzer.class + .getResourceAsStream("MissingRangesForDates.drl"))); + PackageDescr descr2 = new DrlParser() + .parse(new InputStreamReader(Analyzer.class + .getResourceAsStream("MissingRangesForDoubles.drl"))); + PackageDescr descr3 = new DrlParser().parse(new InputStreamReader( + Analyzer.class + .getResourceAsStream("MissingRangesForInts.drl"))); + PackageDescr descr4 = new DrlParser() + .parse(new InputStreamReader( + Analyzer.class + .getResourceAsStream("MissingRangesForVariables.drl"))); + + Analyzer a = new Analyzer(); + a.addPackageDescr(descr); + // a.addPackageDescr(descr2); + // a.addPackageDescr(descr3); + // a.addPackageDescr(descr4); + a.fireAnalysis(); + // System.out.print(a.getResultAsPlainText()); + // System.out.print(a.getResultAsXML()); + System.out.print(a.getResultAsHTML()); + + } catch (Throwable t) { + t.printStackTrace(); + } + } +} diff --git a/experimental/drools-analytics/src/test/resources/org/drools/analytics/Analyzer.java b/experimental/drools-analytics/src/test/resources/org/drools/analytics/Analyzer.java new file mode 100644 index 00000000000..ef1e3475252 --- /dev/null +++ b/experimental/drools-analytics/src/test/resources/org/drools/analytics/Analyzer.java @@ -0,0 +1,108 @@ +package org.drools.analytics; + +import java.util.Collection; + +import org.drools.RuleBase; +import org.drools.RuleBaseFactory; +import org.drools.WorkingMemory; +import org.drools.analytics.dao.AnalyticsData; +import org.drools.analytics.dao.AnalyticsDataMaps; +import org.drools.analytics.result.AnalysisResultNormal; +import org.drools.analytics.result.ReportModeller; +import org.drools.lang.descr.PackageDescr; +import org.drools.rule.Package; + +/** + * + * @author Toni Rikkola + */ +public class Analyzer { + + private AnalysisResultNormal result = new AnalysisResultNormal(); + + public void addPackageDescr(PackageDescr descr) { + try { + + PackageDescrFlattener ruleFlattener = new PackageDescrFlattener(); + + ruleFlattener.insert(descr); + + } catch (Throwable t) { + t.printStackTrace(); + } + } + + public void fireAnalysis() { + try { + AnalyticsData data = AnalyticsDataMaps.getAnalyticsDataMaps(); + + System.setProperty("drools.accumulate.function.validatePattern", + "org.drools.analytics.accumulateFunction.ValidatePattern"); + + // load up the rulebase + RuleBase ruleBase = createRuleBase(); + + WorkingMemory workingMemory = ruleBase.newStatefulSession(); + + for (Object o : data.getAll()) { + workingMemory.insert(o); + } + + // Object that returns the results. + workingMemory.setGlobal("result", result); + workingMemory.fireAllRules(); + + } catch (Throwable t) { + t.printStackTrace(); + } + } + + /** + * Returns the analysis results as plain text. + * + * @return Analysis results as plain text. + */ + public String getResultAsPlainText() { + return ReportModeller.writePlainText(result); + } + + /** + * Returns the analysis results as XML. + * + * @return Analysis results as XML + */ + public String getResultAsXML() { + return ReportModeller.writeXML(result); + } + + /** + * Returns the analysis results as HTML. + * + * @return Analysis results as HTML + */ + public String getResultAsHTML() { + return ReportModeller.writeHTML(result); + } + + /** + * Returns the analysis results as <code>AnalysisResult</code> object. + * + * @return Analysis result + */ + public AnalysisResultNormal getResult() { + return result; + } + + private static RuleBase createRuleBase() throws Exception { + + RuleBase ruleBase = RuleBaseFactory.newRuleBase(); + + Collection<Package> packages = RuleLoader.loadPackages(); + for (Package pkg : packages) { + + ruleBase.addPackage(pkg); + } + + return ruleBase; + } +} diff --git a/experimental/drools-analytics/src/test/resources/org/drools/analytics/basic.css b/experimental/drools-analytics/src/test/resources/org/drools/analytics/basic.css new file mode 100644 index 00000000000..36257009419 --- /dev/null +++ b/experimental/drools-analytics/src/test/resources/org/drools/analytics/basic.css @@ -0,0 +1,54 @@ +/* JBoss Drools Analytics Style Sheet */ +/* Website: http://labs.jboss.com/jbossrules/ */ + +* +{ + border: 0; + margin: 0; + padding: 0; +} + +table +{ + background-color: #d2d7db; + text-align: left; + border-spacing: 0px; + border: 1px solid #aeb3b6; + border-collapse: collapse; +} + +table a, table, tbody, tfoot, tr, th, td +{ + font-family: georgia, "times new roman", serif; + line-height: 1.5em; + font-size: 13px; + color: #55595c; +} + +table caption +{ + border-top: 1px solid #aeb3b6; + padding: .5em 0; + font-size: 240%; + font-style: italic; + color: #d2d7db; +} + +table th +{ + width: 600px; +} + +tbody th +{ + color: #25c1e2; + font-style: italic; + background-color: #fff; + border-bottom: 1px solid #aeb3b6; +} + +td +{ + border: 1px dotted #fff; + padding: 0 2px; +}
0f8ab8e6e1bdac17585abf685efda33d71cbbff1
restlet-framework-java
- The ServletContextAdapter passed by the- ServerServlet to the Restlet's Application was not given to the- constructor but via the setContext() method. Reported by Tammy Croteau.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java b/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java index ef4b264e0f..15ed3500f7 100644 --- a/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java +++ b/modules/com.noelios.restlet.ext.servlet_2.5/src/com/noelios/restlet/ext/servlet/ServerServlet.java @@ -162,7 +162,9 @@ public Application createApplication(Context context) { // Create a new instance of the application class by // invoking the constructor with the Context parameter. application = (Application) targetClass.getConstructor( - Context.class).newInstance(context); + Context.class).newInstance( + new ServletContextAdapter(this, application, + context)); } catch (NoSuchMethodException e) { log( "[Noelios Restlet Engine] - The ServerServlet couldn't invoke the constructor of the target class. Please check this class has a constructor with a single parameter of Context. The empty constructor and the context setter wille used instead. " @@ -172,6 +174,10 @@ public Application createApplication(Context context) { // constructor then invoke the setContext method. application = (Application) targetClass.getConstructor() .newInstance(); + + // Set the context based on the Servlet's context + application.setContext(new ServletContextAdapter(this, + application, context)); } } catch (ClassNotFoundException e) { log( @@ -195,12 +201,6 @@ public Application createApplication(Context context) { "[Noelios Restlet Engine] - The ServerServlet couldn't instantiate the target class. An exception was thrown while creating " + applicationClassName, e); } - - if (application != null) { - // Set the context based on the Servlet's context - application.setContext(new ServletContextAdapter(this, - application, context)); - } } return application;
fc281e6694468fd90363a06cfb809e7368799908
restlet-framework-java
- Moved SIP test cases to test module--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.test/META-INF/MANIFEST.MF b/modules/org.restlet.test/META-INF/MANIFEST.MF index 12a2255a80..e1db49e7c5 100644 --- a/modules/org.restlet.test/META-INF/MANIFEST.MF +++ b/modules/org.restlet.test/META-INF/MANIFEST.MF @@ -37,7 +37,8 @@ Require-Bundle: org.restlet, org.junit4, org.springframework, org.apache.tika, - org.restlet.ext.odata;bundle-version="2.0.0" + org.restlet.ext.odata;bundle-version="2.0.0", + org.restlet.ext.sip;bundle-version="2.1.0" Export-Package: org.restlet.test, org.restlet.test.bench, org.restlet.test.component, diff --git a/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java b/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java index 638850e0d1..4a6303a718 100644 --- a/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java +++ b/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java @@ -59,6 +59,7 @@ import org.restlet.test.ext.jaxb.JaxbBasicConverterTestCase; import org.restlet.test.ext.jaxb.JaxbIntegrationConverterTestCase; import org.restlet.test.ext.odata.ODataTestSuite; +import org.restlet.test.ext.sip.AllSipTests; import org.restlet.test.ext.spring.AllSpringTests; import org.restlet.test.ext.velocity.VelocityTestCase; import org.restlet.test.ext.wadl.WadlTestCase; @@ -161,6 +162,7 @@ public RestletTestSuite() { addTest(EngineTestSuite.suite()); addTest(AllJaxRsTests.suite()); + addTest(AllSipTests.suite()); addTest(AllSpringTests.suite()); // [enddef] } diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AddressTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AddressTestCase.java similarity index 99% rename from modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AddressTestCase.java rename to modules/org.restlet.test/src/org/restlet/test/ext/sip/AddressTestCase.java index 5bd3330c87..ba14943a33 100644 --- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AddressTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AddressTestCase.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.ext.sip.test; +package org.restlet.test.ext.sip; import junit.framework.TestCase; diff --git a/modules/org.restlet.test/src/org/restlet/test/ext/sip/AllSipTests.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AllSipTests.java new file mode 100644 index 0000000000..7340ecb08f --- /dev/null +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AllSipTests.java @@ -0,0 +1,54 @@ +/** + * Copyright 2005-2010 Noelios Technologies. + * + * The contents of this file are subject to the terms of one of the following + * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the + * "Licenses"). You can select the license that you prefer but you may not use + * this file except in compliance with one of these Licenses. + * + * You can obtain a copy of the LGPL 3.0 license at + * http://www.opensource.org/licenses/lgpl-3.0.html + * + * You can obtain a copy of the LGPL 2.1 license at + * http://www.opensource.org/licenses/lgpl-2.1.php + * + * You can obtain a copy of the CDDL 1.0 license at + * http://www.opensource.org/licenses/cddl1.php + * + * You can obtain a copy of the EPL 1.0 license at + * http://www.opensource.org/licenses/eclipse-1.0.php + * + * See the Licenses for the specific language governing permissions and + * limitations under the Licenses. + * + * Alternatively, you can obtain a royalty free commercial license with less + * limitations, transferable or non-transferable, directly at + * http://www.noelios.com/products/restlet-engine + * + * Restlet is a registered trademark of Noelios Technologies. + */ + +package org.restlet.test.ext.sip; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Suite with all SIP unit tests. + * + * @author Jerome Louvel + */ +public class AllSipTests extends TestCase { + + public static Test suite() { + final TestSuite suite = new TestSuite(); + suite.setName("all spring-ext tests"); + suite.addTestSuite(AddressTestCase.class); + suite.addTestSuite(AvailabilityTestCase.class); + suite.addTestSuite(EventTypeTestCase.class); + suite.addTestSuite(SipRecipientInfoTestCase.class); + return suite; + } + +} diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AvailabilityTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AvailabilityTestCase.java similarity index 98% rename from modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AvailabilityTestCase.java rename to modules/org.restlet.test/src/org/restlet/test/ext/sip/AvailabilityTestCase.java index 6138ab301a..b2140da6cb 100644 --- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AvailabilityTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AvailabilityTestCase.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.ext.sip.test; +package org.restlet.test.ext.sip; import junit.framework.TestCase; diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/EventTypeTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/EventTypeTestCase.java similarity index 98% rename from modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/EventTypeTestCase.java rename to modules/org.restlet.test/src/org/restlet/test/ext/sip/EventTypeTestCase.java index 6624a87b6d..cdad3bc4d3 100644 --- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/EventTypeTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/EventTypeTestCase.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.ext.sip.test; +package org.restlet.test.ext.sip; import junit.framework.TestCase; diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/SipRecipientInfoTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/SipRecipientInfoTestCase.java similarity index 99% rename from modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/SipRecipientInfoTestCase.java rename to modules/org.restlet.test/src/org/restlet/test/ext/sip/SipRecipientInfoTestCase.java index 9e23da89a9..01bfaa4714 100644 --- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/SipRecipientInfoTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/SipRecipientInfoTestCase.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.ext.sip.test; +package org.restlet.test.ext.sip; import junit.framework.TestCase;
5bd0f4b011f861f866121b22a0fdb3c000bc5e01
orientdb
Minor improvement on collection remove--
p
https://github.com/orientechnologies/orientdb
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OMultiValue.java b/commons/src/main/java/com/orientechnologies/common/collection/OMultiValue.java index fddd1d4bc2f..c76cf1476fa 100755 --- a/commons/src/main/java/com/orientechnologies/common/collection/OMultiValue.java +++ b/commons/src/main/java/com/orientechnologies/common/collection/OMultiValue.java @@ -402,7 +402,7 @@ else if (iToAdd != null && iToAdd.getClass().isArray()) { * True if the all occurrences must be removed or false of only the first one (Like java.util.Collection.remove()) * @return */ - public static Object remove(Object iObject, final Object iToRemove, final boolean iAllOccurrences) { + public static Object remove(Object iObject, Object iToRemove, final boolean iAllOccurrences) { if (iObject != null) { if (iObject instanceof OMultiCollectionIterator<?>) { final Collection<Object> list = new LinkedList<Object>(); @@ -411,6 +411,14 @@ public static Object remove(Object iObject, final Object iToRemove, final boolea iObject = list; } + if (iToRemove instanceof OMultiCollectionIterator<?>) { + // TRANSFORM IN SET ONCE TO OPTIMIZE LOOPS DURING REMOVE + final Set<Object> set = new HashSet<Object>(); + for (Object o : ((OMultiCollectionIterator<?>) iToRemove)) + set.add(o); + iToRemove = set; + } + if (iObject instanceof Collection<?>) { // COLLECTION - ? final Collection<Object> coll = (Collection<Object>) iObject;
7f75579b43b6d2f804a092459ec53027dea9a64c
intellij-community
Check VFS sanity action--
p
https://github.com/JetBrains/intellij-community
diff --git a/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java b/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java index c315c12dd438d..f7a96b05f3200 100644 --- a/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java +++ b/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java @@ -912,7 +912,7 @@ private static void checkRecordSanity(final int id, final int recordCount, final } String name = getName(id); - assert name.length() > 0: "File with empty name found under " + (parentId == 0 ? "<root> " : getName(parentId)); + assert parentId > 0 || name.length() > 0: "File with empty name found under " + getName(parentId); int attributeRecordId; try {
cb378074d6e3fd71a3ab1681a5b1f9c61239245b
restlet-framework-java
- Fixed NIO client blocking due to reuse attempt- of a busy connection--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/connector/BaseHelper.java b/modules/org.restlet/src/org/restlet/engine/connector/BaseHelper.java index 12616a9647..c62b58dec4 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/BaseHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/BaseHelper.java @@ -78,7 +78,7 @@ * <tr> * <td>minThreads</td> * <td>int</td> - * <td>5</td> + * <td>1</td> * <td>Minimum number of worker threads waiting to service calls, even if they * are idle.</td> * </tr> @@ -152,7 +152,8 @@ * <td>boolean</td> * <td>true</td> * <td>Indicates if direct NIO buffers should be allocated instead of regular - * buffers. See NIO's ByteBuffer Javadocs.</td> + * buffers. See NIO's ByteBuffer Javadocs. Note that tracing must be disabled to + * use direct buffers.</td> * </tr> * <tr> * <td>transport</td> @@ -418,7 +419,7 @@ public int getMaxThreads() { */ public int getMinThreads() { return Integer.parseInt(getHelpedParameters().getFirstValue( - "minThreads", "5")); + "minThreads", "1")); } /** @@ -502,13 +503,15 @@ public boolean isClientSide() { public abstract boolean isControllerDaemon(); /** - * Indicates if direct NIO buffers should be used. + * Indicates if direct NIO buffers should be used. Note that tracing must be + * disabled to use direct buffers. * * @return True if direct NIO buffers should be used. */ public boolean isDirectBuffers() { - return Boolean.parseBoolean(getHelpedParameters().getFirstValue( - "directBuffers", "true")); + return !isTracing() + && Boolean.parseBoolean(getHelpedParameters().getFirstValue( + "directBuffers", "true")); } /** diff --git a/modules/org.restlet/src/org/restlet/engine/connector/ConnectionClientHelper.java b/modules/org.restlet/src/org/restlet/engine/connector/ConnectionClientHelper.java index 7dbd70cfca..4e15d9e088 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/ConnectionClientHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/ConnectionClientHelper.java @@ -393,9 +393,13 @@ protected Connection<Client> getBestConnection(Request request) if (socketAddress.equals(currConn.getSocketAddress())) { if (currConn.getState().equals(ConnectionState.OPEN) + && currConn.getInboundWay().getMessageState() + .equals(MessageState.IDLE) && currConn.getInboundWay().getIoState() .equals(IoState.IDLE) && currConn.getInboundWay().getMessages().isEmpty() + && currConn.getOutboundWay().getMessageState() + .equals(MessageState.IDLE) && currConn.getOutboundWay().getIoState() .equals(IoState.IDLE) && currConn.getOutboundWay().getMessages() diff --git a/modules/org.restlet/src/org/restlet/engine/io/ReadableBufferedChannel.java b/modules/org.restlet/src/org/restlet/engine/io/ReadableBufferedChannel.java index 2d407cf3ca..e2477ad0cc 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/ReadableBufferedChannel.java +++ b/modules/org.restlet/src/org/restlet/engine/io/ReadableBufferedChannel.java @@ -205,7 +205,7 @@ public void postRead(int length) { * been reached. */ public int read(ByteBuffer targetBuffer) throws IOException { - int totalRead = 0; + int result = 0; int currentRead = 0; boolean tryAgain = true; @@ -231,7 +231,7 @@ public int read(ByteBuffer targetBuffer) throws IOException { targetBuffer.put(getByteBuffer().get()); } - totalRead += currentRead; + result += currentRead; } if (getByteBuffer().remaining() == 0) { @@ -248,7 +248,7 @@ public int read(ByteBuffer targetBuffer) throws IOException { } } - return totalRead; + return result; } /**
3dbcd5fa303e8eecaaa2b5b256f96e0127be0cdf
orientdb
Improved import/export tools--
p
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/document/OLazyRecordMap.java b/core/src/main/java/com/orientechnologies/orient/core/db/document/OLazyRecordMap.java index 1ad048c2794..2a36c82afdb 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/document/OLazyRecordMap.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/document/OLazyRecordMap.java @@ -15,7 +15,7 @@ */ package com.orientechnologies.orient.core.db.document; -import java.util.HashMap; +import java.util.LinkedHashMap; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.id.ORID; @@ -24,7 +24,7 @@ import com.orientechnologies.orient.core.record.ORecordInternal; @SuppressWarnings({ "serial" }) -public class OLazyRecordMap extends HashMap<String, Object> { +public class OLazyRecordMap extends LinkedHashMap<String, Object> { private ODatabaseRecord<?> database; private byte recordType; private boolean converted = false; diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java index 5dc9d28b596..24e14cd65f6 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java @@ -533,14 +533,15 @@ private ORID linkToStream(final StringBuilder buffer, final ORecordSchemaAware<? ((ODatabaseRecord<ORecordInternal<?>>) iLinkedRecord.getDatabase()).save((ORecordInternal<?>) iLinkedRecord); } - if (iLinkedRecord instanceof ORecordSchemaAware<?>) { - final ORecordSchemaAware<?> schemaAwareRecord = (ORecordSchemaAware<?>) iLinkedRecord; - - if (schemaAwareRecord.getClassName() != null) { - buffer.append(schemaAwareRecord.getClassName()); - buffer.append(OStringSerializerHelper.CLASS_SEPARATOR); - } - } + // TEMPORARY DISABLED SINCE IT MAKES NOT SENSE AT CURRENT RELEASE (0.9.21)! + // if (iLinkedRecord instanceof ORecordSchemaAware<?>) { + // final ORecordSchemaAware<?> schemaAwareRecord = (ORecordSchemaAware<?>) iLinkedRecord; + // + // if (schemaAwareRecord.getClassName() != null) { + // buffer.append(schemaAwareRecord.getClassName()); + // buffer.append(OStringSerializerHelper.CLASS_SEPARATOR); + // } + // } if (iParentRecord.getDatabase() instanceof ODatabaseRecord<?>) { final ODatabaseRecord<?> db = (ODatabaseRecord<?>) iParentRecord.getDatabase(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java index 5160e702809..6d862c64651 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java @@ -19,8 +19,8 @@ import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -158,11 +158,12 @@ private Object getValue(final ODocument iRecord, String iFieldName, String iFiel return fromString(iRecord.getDatabase(), iFieldValue, null); else { // MAP - final Map<String, Object> embeddedMap; - embeddedMap = new HashMap<String, Object>(); + final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>(); for (int i = 0; i < fields.length; i += 2) { iFieldName = fields[i]; + if (iFieldName.length() >= 2) + iFieldName = iFieldName.substring(1, iFieldName.length() - 1); iFieldValue = fields[i + 1]; iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue; diff --git a/tools/src/main/java/com/orientechnologies/utility/cmd/OConsoleDatabaseCompare.java b/tools/src/main/java/com/orientechnologies/utility/cmd/OConsoleDatabaseCompare.java index 757ae944452..b19b9734d81 100644 --- a/tools/src/main/java/com/orientechnologies/utility/cmd/OConsoleDatabaseCompare.java +++ b/tools/src/main/java/com/orientechnologies/utility/cmd/OConsoleDatabaseCompare.java @@ -25,14 +25,13 @@ import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.utility.console.OCommandListener; -public class OConsoleDatabaseCompare { - private OStorage storage1; - private OStorage storage2; - private OCommandListener listener; - private int differences = 0; +public class OConsoleDatabaseCompare extends OConsoleDatabaseImpExpAbstract { + private OStorage storage1; + private OStorage storage2; + private int differences = 0; public OConsoleDatabaseCompare(final String iDb1URL, final String iDb2URL, final OCommandListener iListener) throws IOException { - listener = iListener; + super(null, null, iListener); listener.onMessage("\nComparing two databases:\n1) " + iDb1URL + "\n2) " + iDb2URL + "\n"); storage1 = Orient.instance().accessToLocalStorage(iDb1URL, "rw"); @@ -78,27 +77,36 @@ private boolean compareClusters() { int cluster2Id; boolean ok; - for (String cl1 : storage1.getClusterNames()) { + for (String clusterName : storage1.getClusterNames()) { + // CHECK IF THE CLUSTER IS INCLUDED + if (includeClusters != null) { + if (!includeClusters.contains(clusterName)) + continue; + } else if (excludeClusters != null) { + if (excludeClusters.contains(clusterName)) + continue; + } + ok = true; - cluster2Id = storage2.getClusterIdByName(cl1); + cluster2Id = storage2.getClusterIdByName(clusterName); - listener.onMessage("\n- Checking cluster " + String.format("%-25s: ", "'" + cl1 + "'")); + listener.onMessage("\n- Checking cluster " + String.format("%-25s: ", "'" + clusterName + "'")); if (cluster2Id == -1) { - listener.onMessage("KO: cluster name " + cl1 + " was not found on database " + storage2); + listener.onMessage("KO: cluster name " + clusterName + " was not found on database " + storage2); ++differences; ok = false; } - if (cluster2Id != storage1.getClusterIdByName(cl1)) { - listener.onMessage("KO: cluster id is different for cluster " + cl1 + ": " + storage1.getClusterIdByName(cl1) + " <-> " - + cluster2Id); + if (cluster2Id != storage1.getClusterIdByName(clusterName)) { + listener.onMessage("KO: cluster id is different for cluster " + clusterName + ": " + + storage1.getClusterIdByName(clusterName) + " <-> " + cluster2Id); ++differences; ok = false; } if (storage1.count(cluster2Id) != storage2.count(cluster2Id)) { - listener.onMessage("KO: record number are different in cluster '" + cl1 + "' (id=" + cluster2Id + "): " + listener.onMessage("KO: number of records differents in cluster '" + clusterName + "' (id=" + cluster2Id + "): " + storage1.count(cluster2Id) + " <-> " + storage2.count(cluster2Id)); ++differences; ok = false; @@ -116,51 +124,81 @@ private boolean compareRecords() { listener.onMessage("\nStarting deep comparison record by record. It can takes some minutes. Wait please..."); int clusterId; - long clusterMax; ORawBuffer buffer1, buffer2; for (String clusterName : storage1.getClusterNames()) { + // CHECK IF THE CLUSTER IS INCLUDED + if (includeClusters != null) { + if (!includeClusters.contains(clusterName)) + continue; + } else if (excludeClusters != null) { + if (excludeClusters.contains(clusterName)) + continue; + } + clusterId = storage1.getClusterIdByName(clusterName); - clusterMax = storage1.getClusterLastEntryPosition(clusterId); - for (int i = 0; i < clusterMax; ++i) { - buffer1 = storage1.readRecord(null, 0, clusterId, i, null); - buffer2 = storage2.readRecord(null, 0, clusterId, i, null); - if (buffer1 == null && buffer2 == null || buffer1.buffer == null && buffer2.buffer == null) - continue; + long db1Max = storage1.getClusterLastEntryPosition(clusterId); + long db2Max = storage2.getClusterLastEntryPosition(clusterId); - if (buffer1.recordType != buffer2.recordType) { - listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " recordType is different: " + (char) buffer1.recordType - + " <-> " + (char) buffer2.recordType); - ++differences; - } + long clusterMax = Math.max(db1Max, db2Max); + for (int i = 0; i < clusterMax; ++i) { + buffer1 = i < db1Max ? storage1.readRecord(null, 0, clusterId, i, null) : null; + buffer2 = i < db2Max ? storage2.readRecord(null, 0, clusterId, i, null) : null; - if (buffer1.buffer == null && buffer2.buffer != null) { - listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " content is different: null <-> " + buffer2.buffer.length); - ++differences; - } else if (buffer1.buffer != null && buffer2.buffer == null) { - listener - .onMessage("\n- KO: RID=" + clusterId + ":" + i + " content is different: " + buffer1.buffer.length + " <-> null"); + if (buffer1 == null && buffer2 == null) + // BOTH RECORD NULL, OK + continue; + else if (buffer1 == null && buffer2 != null) { + // REC1 NULL + listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " is null in DB1"); ++differences; - } else if (buffer1.buffer.length != buffer2.buffer.length) { - listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " content length is different: " + buffer1.buffer.length - + " <-> " + buffer2.buffer.length); - if (buffer1.recordType == ODocument.RECORD_TYPE || buffer1.recordType == ORecordFlat.RECORD_TYPE - || buffer1.recordType == ORecordColumn.RECORD_TYPE) - listener.onMessage("\n--- REC1: " + new String(buffer1.buffer)); - if (buffer2.recordType == ODocument.RECORD_TYPE || buffer2.recordType == ORecordFlat.RECORD_TYPE - || buffer2.recordType == ORecordColumn.RECORD_TYPE) - listener.onMessage("\n--- REC2: " + new String(buffer2.buffer)); - + } else if (buffer1 != null && buffer2 == null) { + // REC2 NULL + listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " is null in DB2"); ++differences; } else { - // CHECK BYTE PER BYTE - for (int b = 0; b < buffer1.buffer.length; ++b) { - if (buffer1.buffer[b] != buffer2.buffer[b]) { - listener.onMessage("\n--- KO: RID=" + clusterId + ":" + i + " content is different at byte #" + b + ": " - + buffer1.buffer[b] + " <-> " + buffer2.buffer[b]); - ++differences; + if (buffer1.recordType != buffer2.recordType) { + listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " recordType is different: " + (char) buffer1.recordType + + " <-> " + (char) buffer2.recordType); + ++differences; + } + + if (buffer1.buffer == null && buffer2.buffer != null) { + listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " content is different: null <-> " + buffer2.buffer.length); + ++differences; + + } else if (buffer1.buffer != null && buffer2.buffer == null) { + listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " content is different: " + buffer1.buffer.length + + " <-> null"); + ++differences; + + } else if (buffer1.buffer.length != buffer2.buffer.length) { + listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " content length is different: " + buffer1.buffer.length + + " <-> " + buffer2.buffer.length); + if (buffer1.recordType == ODocument.RECORD_TYPE || buffer1.recordType == ORecordFlat.RECORD_TYPE + || buffer1.recordType == ORecordColumn.RECORD_TYPE) + listener.onMessage("\n--- REC1: " + new String(buffer1.buffer)); + if (buffer2.recordType == ODocument.RECORD_TYPE || buffer2.recordType == ORecordFlat.RECORD_TYPE + || buffer2.recordType == ORecordColumn.RECORD_TYPE) + listener.onMessage("\n--- REC2: " + new String(buffer2.buffer)); + listener.onMessage("\n"); + + ++differences; + + } else { + // CHECK BYTE PER BYTE + for (int b = 0; b < buffer1.buffer.length; ++b) { + if (buffer1.buffer[b] != buffer2.buffer[b]) { + listener.onMessage("\n- KO: RID=" + clusterId + ":" + i + " content is different at byte #" + b + ": " + + buffer1.buffer[b] + " <-> " + buffer2.buffer[b]); + listener.onMessage("\n--- REC1: " + new String(buffer1.buffer)); + listener.onMessage("\n--- REC2: " + new String(buffer2.buffer)); + listener.onMessage("\n"); + ++differences; + break; + } } } }
28174744a74e08cc974a54041e304dc4aafa5334
spring-framework
Fix race when flushing messages--The use of an AtomicBoolean and no lock meant that it was possible-for a message to be queued and then never be flushed and sent to the-broker:--1. On t1, a message is received and isConnected is false. The message- will be queued.-2. On t2, CONNECTED is received from the broker. isConnected is set- to true, the queue is drained and the queued messages are forwarded-3. On t1, the message is added to the queue--To fix this, checking that isConnected is false (step 1 above) and the-queueing of a message (step 3 above) need to be performed as a unit-so that the flushing of the queued messages can't be interleaved. This-is achieved by synchronizing on a monitor and performing steps 1-and 3 and synchronizing on the same monitor while performing step 2.--The monitor is held while the messages are actually being forwarded-to the broker. An alternative would be to drain the queue into-a local variable, release the monitor, and then forward the messages.-The main advantage of this alternative is that the monitor is held for-less time. It also reduces the theoretical risk of deadlock by not-holding the monitor while making an alien call. The downside of the-alternative is that it may lead to messages being forwarded out of-order. For this reason the alternative approach was rejected.-
c
https://github.com/spring-projects/spring-framework
diff --git a/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java b/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java index 2337814fcadc..ae8df8f91a2c 100644 --- a/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java +++ b/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java @@ -24,7 +24,6 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicBoolean; import org.springframework.http.MediaType; import org.springframework.messaging.Message; @@ -171,10 +170,11 @@ private final class RelaySession { private final Promise<TcpConnection<String, String>> promise; - private final AtomicBoolean isConnected = new AtomicBoolean(false); - private final BlockingQueue<M> messageQueue = new LinkedBlockingQueue<M>(50); + private final Object monitor = new Object(); + + private boolean isConnected = false; public RelaySession(final M message, final StompHeaders stompHeaders) { @@ -224,8 +224,10 @@ private void readStompFrame(String stompFrame) { StompHeaders headers = StompHeaders.fromMessageHeaders(message.getHeaders()); if (StompCommand.CONNECTED == headers.getStompCommand()) { - this.isConnected.set(true); - flushMessages(promise.get()); + synchronized(this.monitor) { + this.isConnected = true; + flushMessages(promise.get()); + } return; } if (StompCommand.ERROR == headers.getStompCommand()) { @@ -248,14 +250,14 @@ private void sendError(String sessionId, String errorText) { public void forward(M message, StompHeaders headers) { - if (!this.isConnected.get()) { - @SuppressWarnings("unchecked") - M m = (M) MessageBuilder.fromPayloadAndHeaders(message.getPayload(), headers.toMessageHeaders()).build(); - if (logger.isTraceEnabled()) { - logger.trace("Adding to queue message " + m + ", queue size=" + this.messageQueue.size()); + synchronized(this.monitor) { + if (!this.isConnected) { + if (logger.isTraceEnabled()) { + logger.trace("Adding to queue message " + message + ", queue size=" + this.messageQueue.size()); + } + this.messageQueue.add(message); + return; } - this.messageQueue.add(m); - return; } TcpConnection<String, String> connection = this.promise.get();
9cbc1d502d0c0ead391ffd65bf1cbd812ed53654
spring-framework
SPR- - Allow XStreamMarshaller subclasses to- customise XStream object--
a
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java b/org.springframework.oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java index 81f5b9281361..68026ab49044 100644 --- a/org.springframework.oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java +++ b/org.springframework.oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java @@ -57,6 +57,7 @@ import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; +import org.springframework.beans.factory.InitializingBean; import org.springframework.oxm.MarshallingFailureException; import org.springframework.oxm.UncategorizedMappingException; import org.springframework.oxm.UnmarshallingFailureException; @@ -87,7 +88,7 @@ * @see #setConverters * @see #setEncoding */ -public class XStreamMarshaller extends AbstractMarshaller { +public class XStreamMarshaller extends AbstractMarshaller implements InitializingBean { /** * The default encoding used for stream access: UTF-8. @@ -251,6 +252,17 @@ public void setSupportedClasses(Class[] supportedClasses) { this.supportedClasses = supportedClasses; } + public final void afterPropertiesSet() throws Exception { + customizeXStream(getXStream()); + } + + /** + * Template to allow for customizing of the given {@link XStream}. + * <p>Default implementation is empty. + * @param xstream the {@code XStream} instance + */ + protected void customizeXStream(XStream xstream) { + } public boolean supports(Class clazz) { if (ObjectUtils.isEmpty(this.supportedClasses)) {
7ac59de1ff24646c5b84b7b559fdc3d6622d1922
camel
Removed the System out from the GenericFile--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@752424 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java index 80e2280a4f13b..d8a13c98df6db 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java @@ -99,9 +99,7 @@ public void changeFileName(String newName) { String newFileName = FileUtil.normalizePath(newName); File file = new File(newFileName); if (!absolute) { - // for relative then we should avoid having the endpoint path duplicated so clip it - System.out.println("endpointPath " + endpointPath); - System.out.println("newName " + newFileName); + // for relative then we should avoid having the endpoint path duplicated so clip it if (ObjectHelper.isNotEmpty(endpointPath) && newFileName.startsWith(endpointPath)) { // clip starting endpoint in case it was added newFileName = ObjectHelper.after(newFileName, endpointPath + getFileSeparator());
d7c90cff145edc3193a63b1b7751aee203d5c4d6
spring-framework
made ConversionExecutor internal; removed other- unused operations from public SPI--
p
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionService.java b/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionService.java index 372e41fb2df2..782f78d8bd02 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionService.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionService.java @@ -16,10 +16,10 @@ package org.springframework.core.convert; /** - * A service interface for type conversion. This is the entry point into the convert system. Call one of the - * <i>executeConversion</i> operations to perform a thread-safe type conversion using - * this system. Call one of the <i>getConversionExecutor</i> operations to obtain - * a thread-safe {@link ConversionExecutor} command for later use. + * A service interface for type conversion. This is the entry point into the convert system. + * <p> + * Call {@link #executeConversion(Object, TypeDescriptor)} to perform a thread-safe type conversion using + * this system. * * @author Keith Donald */ @@ -28,47 +28,21 @@ public interface ConversionService { /** * Returns true if objects of sourceType can be converted to targetType. * @param source the source to convert from (may be null) - * @param targetType the target type to convert to + * @param targetType context about the target type to convert to * @return true if a conversion can be performed, false if not */ public boolean canConvert(Class<?> sourceType, TypeDescriptor targetType); - /** - * Returns true if the source can be converted to targetType. - * @param source the source to convert from (may be null) - * @param targetType the target type to convert to - * @return true if a conversion can be performed, false if not - */ - public boolean canConvert(Object source, TypeDescriptor targetType); - /** * Convert the source to targetType. * @param source the source to convert from (may be null) - * @param targetType the target type to convert to - * @return the converted object, an instance of the <code>targetType</code>, or <code>null</code> if a null source + * @param targetType context about the target type to convert to + * @return the converted object, an instance of {@link TypeDescriptor#getType()}</code>, or <code>null</code> if a null source * was provided - * @throws ConversionExecutorNotFoundException if no suitable conversion executor could be found to convert the + * @throws ConverterNotFoundException if no suitable conversion executor could be found to convert the * source to an instance of targetType * @throws ConversionException if an exception occurred during the conversion process */ - public Object executeConversion(Object source, TypeDescriptor targetType) throws ConversionExecutorNotFoundException, - ConversionException; - - /** - * Get a ConversionExecutor that converts objects from sourceType to targetType. - * The returned ConversionExecutor is thread-safe and may safely be cached for later use by client code. - * @param sourceType the source type to convert from (required) - * @param targetType the target type to convert to (required) - * @return the executor that can execute instance type conversion, never null - * @throws ConversionExecutorNotFoundException when no suitable conversion executor could be found - */ - public ConversionExecutor getConversionExecutor(Class<?> sourceType, TypeDescriptor targetType) - throws ConversionExecutorNotFoundException; - - /** - * Get a type by its name; may be the fully-qualified class name or a registered type alias such as 'int'. - * @return the class, or <code>null</code> if no such name exists - */ - public Class<?> getType(String name); + public Object executeConversion(Object source, TypeDescriptor targetType); } \ No newline at end of file diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/ConverterNotFoundException.java b/org.springframework.core/src/main/java/org/springframework/core/convert/ConverterNotFoundException.java new file mode 100644 index 000000000000..8856a84101c8 --- /dev/null +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/ConverterNotFoundException.java @@ -0,0 +1,54 @@ +/* + * Copyright 2004-2009 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.core.convert; + +/** + * Thrown when a conversion executor could not be found in a conversion service. + * + * @author Keith Donald + */ +public class ConverterNotFoundException extends ConversionException { + + private Class<?> sourceType; + + private TypeDescriptor targetType; + + /** + * Creates a new conversion executor not found exception. + * @param sourceType the source type requested to convert from + * @param targetType the target type requested to convert to + * @param message a descriptive message + */ + public ConverterNotFoundException(Class<?> sourceType, TypeDescriptor targetType, String message) { + super(message); + this.sourceType = sourceType; + this.targetType = targetType; + } + + /** + * Returns the source type that was requested to convert from. + */ + public Class<?> getSourceType() { + return sourceType; + } + + /** + * Returns the target type that was requested to convert to. + */ + public TypeDescriptor getTargetType() { + return targetType; + } +} diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/AbstractCollectionConverter.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/AbstractCollectionConverter.java index a43fa91155a6..a5ef6262e974 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/AbstractCollectionConverter.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/AbstractCollectionConverter.java @@ -16,7 +16,6 @@ package org.springframework.core.convert.service; import org.springframework.core.convert.ConversionExecutionException; -import org.springframework.core.convert.ConversionExecutor; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; @@ -26,7 +25,7 @@ */ abstract class AbstractCollectionConverter implements ConversionExecutor { - private ConversionService conversionService; + private GenericConversionService conversionService; private ConversionExecutor elementConverter; @@ -34,7 +33,7 @@ abstract class AbstractCollectionConverter implements ConversionExecutor { private TypeDescriptor targetCollectionType; - public AbstractCollectionConverter(TypeDescriptor sourceCollectionType, TypeDescriptor targetCollectionType, ConversionService conversionService) { + public AbstractCollectionConverter(TypeDescriptor sourceCollectionType, TypeDescriptor targetCollectionType, GenericConversionService conversionService) { this.conversionService = conversionService; this.sourceCollectionType = sourceCollectionType; this.targetCollectionType = targetCollectionType; @@ -61,7 +60,7 @@ protected Class<?> getTargetElementType() { return targetCollectionType.getElementType(); } - protected ConversionService getConversionService() { + protected GenericConversionService getConversionService() { return conversionService; } diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/ArrayToCollection.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/ArrayToCollection.java index d971a645ce29..e21315f56174 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/ArrayToCollection.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/ArrayToCollection.java @@ -18,7 +18,6 @@ import java.lang.reflect.Array; import java.util.Collection; -import org.springframework.core.convert.ConversionExecutor; import org.springframework.core.convert.TypeDescriptor; /** diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToArray.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToArray.java index b7e2ed98dbaf..d70bdae51597 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToArray.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToArray.java @@ -19,7 +19,6 @@ import java.util.Collection; import java.util.Iterator; -import org.springframework.core.convert.ConversionExecutor; import org.springframework.core.convert.TypeDescriptor; /** diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToCollection.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToCollection.java index a5921926cb0d..b189b547035a 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToCollection.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToCollection.java @@ -18,7 +18,6 @@ import java.util.Collection; import java.util.Iterator; -import org.springframework.core.convert.ConversionExecutor; import org.springframework.core.convert.TypeDescriptor; /** diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/ConversionExecutor.java similarity index 87% rename from org.springframework.core/src/main/java/org/springframework/core/convert/ConversionExecutor.java rename to org.springframework.core/src/main/java/org/springframework/core/convert/service/ConversionExecutor.java index 3059f003b729..a84bbe5019ce 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionExecutor.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/ConversionExecutor.java @@ -13,7 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.core.convert; +package org.springframework.core.convert.service; + +import org.springframework.core.convert.ConversionExecutionException; /** * A command parameterized with the information necessary to perform a conversion of a source input to a @@ -29,6 +31,6 @@ public interface ConversionExecutor { * @param source the source to convert * @throws ConversionExecutionException if an exception occurs during type conversion */ - public Object execute(Object source) throws ConversionExecutionException; + public Object execute(Object source); } \ No newline at end of file diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/DefaultConversionService.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/DefaultConversionService.java index a149217bf58b..73e28ea151a1 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/DefaultConversionService.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/DefaultConversionService.java @@ -49,7 +49,6 @@ public class DefaultConversionService extends GenericConversionService { */ public DefaultConversionService() { addDefaultConverters(); - addDefaultAliases(); } /** @@ -73,21 +72,4 @@ protected void addDefaultConverters() { addConverter(new ObjectToString()); } - protected void addDefaultAliases() { - addAlias("string", String.class); - addAlias("byte", Byte.class); - addAlias("boolean", Boolean.class); - addAlias("char", Character.class); - addAlias("short", Short.class); - addAlias("int", Integer.class); - addAlias("long", Long.class); - addAlias("float", Float.class); - addAlias("double", Double.class); - addAlias("bigInt", BigInteger.class); - addAlias("bigDecimal", BigDecimal.class); - addAlias("locale", Locale.class); - addAlias("enum", Enum.class); - addAlias("date", Date.class); - } - } \ No newline at end of file diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/GenericConversionService.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/GenericConversionService.java index 74d19fdcc082..8cee88e12eb1 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/GenericConversionService.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/GenericConversionService.java @@ -26,10 +26,8 @@ import java.util.Map; import org.springframework.core.GenericTypeResolver; -import org.springframework.core.convert.ConversionException; -import org.springframework.core.convert.ConversionExecutor; -import org.springframework.core.convert.ConversionExecutorNotFoundException; import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterInfo; @@ -61,11 +59,6 @@ public class GenericConversionService implements ConversionService { */ private final Map sourceTypeSuperConverters = new HashMap(); - /** - * Indexes classes by well-known aliases. - */ - private final Map aliasMap = new HashMap<String, Class<?>>(); - /** * An optional parent conversion service. */ @@ -132,48 +125,41 @@ public static <S, T> Converter<S, T> converterFor(Class<S> sourceType, Class<T> return new SuperTwoWayConverterConverter(converter, sourceType, targetType); } - /** - * Add a convenient alias for the target type. {@link #getType(String)} can then be used to lookup the type given - * the alias. - * @see #getType(String) - */ - public void addAlias(String alias, Class targetType) { - aliasMap.put(alias, targetType); - } - // implementing ConversionService public boolean canConvert(Class<?> sourceType, TypeDescriptor targetType) { - try { - getConversionExecutor(sourceType, targetType); + ConversionExecutor executor = getConversionExecutor(sourceType, targetType); + if (executor != null) { return true; - } catch (ConversionExecutorNotFoundException e) { - return false; - } - } - - public boolean canConvert(Object source, TypeDescriptor targetType) { - if (source == null) { - return true; - } - try { - getConversionExecutor(source.getClass(), targetType); - return true; - } catch (ConversionExecutorNotFoundException e) { - return false; + } else { + if (parent != null) { + return parent.canConvert(sourceType, targetType); + } else { + return false; + } } } - public Object executeConversion(Object source, TypeDescriptor targetType) - throws ConversionExecutorNotFoundException, ConversionException { + public Object executeConversion(Object source, TypeDescriptor targetType) { if (source == null) { return null; } - return getConversionExecutor(source.getClass(), targetType).execute(source); + ConversionExecutor executor = getConversionExecutor(source.getClass(), targetType); + if (executor != null) { + return executor.execute(source); + } else { + if (parent != null) { + return parent.executeConversion(source, targetType); + } else { + throw new ConverterNotFoundException(source.getClass(), targetType, + "No converter found that can convert from sourceType [" + source.getClass().getName() + + "] to targetType [" + targetType.getName() + "]"); + } + } } - public ConversionExecutor getConversionExecutor(Class sourceClass, TypeDescriptor targetType) - throws ConversionExecutorNotFoundException { + ConversionExecutor getConversionExecutor(Class sourceClass, TypeDescriptor targetType) + throws ConverterNotFoundException { Assert.notNull(sourceClass, "The sourceType to convert from is required"); Assert.notNull(targetType, "The targetType to convert to is required"); TypeDescriptor sourceType = TypeDescriptor.valueOf(sourceClass); @@ -193,21 +179,21 @@ public ConversionExecutor getConversionExecutor(Class sourceClass, TypeDescripto if (sourceType.isCollection()) { return new CollectionToArray(sourceType, targetType, this); } else { - throw new ConversionExecutorNotFoundException(sourceType, targetType, "Object to Array conversion not yet supported"); + return null; } } if (sourceType.isCollection()) { if (targetType.isCollection()) { return new CollectionToCollection(sourceType, targetType, this); } else { - throw new ConversionExecutorNotFoundException(sourceType, targetType, "Object to Collection conversion not yet supported"); + return null; } } if (sourceType.isMap()) { if (targetType.isMap()) { return new MapToMap(sourceType, targetType, this); } else { - throw new ConversionExecutorNotFoundException(sourceType, targetType, "Object to Map conversion not yet supported"); + return null; } } Converter converter = findRegisteredConverter(sourceClass, targetType.getType()); @@ -217,28 +203,10 @@ public ConversionExecutor getConversionExecutor(Class sourceClass, TypeDescripto SuperConverter superConverter = findRegisteredSuperConverter(sourceClass, targetType.getType()); if (superConverter != null) { return new StaticSuperConversionExecutor(sourceType, targetType, superConverter); - } - if (parent != null) { - return parent.getConversionExecutor(sourceClass, targetType); } else { if (sourceType.isAssignableTo(targetType)) { return new StaticConversionExecutor(sourceType, targetType, NoOpConverter.INSTANCE); } - throw new ConversionExecutorNotFoundException(sourceType, targetType, - "No ConversionExecutor found for converting from sourceType [" + sourceType.getName() - + "] to targetType [" + targetType.getName() + "]"); - } - } - } - - public Class getType(String name) throws IllegalArgumentException { - Class clazz = (Class) aliasMap.get(name); - if (clazz != null) { - return clazz; - } else { - if (parent != null) { - return parent.getType(name); - } else { return null; } } diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/MapToMap.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/MapToMap.java index 90db0082c844..9d6712433e63 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/MapToMap.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/MapToMap.java @@ -22,7 +22,6 @@ import java.util.TreeMap; import org.springframework.core.convert.ConversionExecutionException; -import org.springframework.core.convert.ConversionExecutor; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; @@ -36,7 +35,7 @@ class MapToMap implements ConversionExecutor { private TypeDescriptor targetType; - private ConversionService conversionService; + private GenericConversionService conversionService; private EntryConverter entryConverter; @@ -46,7 +45,7 @@ class MapToMap implements ConversionExecutor { * @param targetType the target map type * @param conversionService the conversion service */ - public MapToMap(TypeDescriptor sourceType, TypeDescriptor targetType, ConversionService conversionService) { + public MapToMap(TypeDescriptor sourceType, TypeDescriptor targetType, GenericConversionService conversionService) { this.sourceType = sourceType; this.targetType = targetType; this.conversionService = conversionService; diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/NoOpConversionExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/NoOpConversionExecutor.java index 817731724939..086eb3330be5 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/NoOpConversionExecutor.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/NoOpConversionExecutor.java @@ -16,7 +16,6 @@ package org.springframework.core.convert.service; import org.springframework.core.convert.ConversionExecutionException; -import org.springframework.core.convert.ConversionExecutor; /** * Conversion executor that does nothing. Access singleton at {@link #INSTANCE}.s diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticConversionExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticConversionExecutor.java index 857d7d3dc27f..be3b767a9aaf 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticConversionExecutor.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticConversionExecutor.java @@ -16,7 +16,6 @@ package org.springframework.core.convert.service; import org.springframework.core.convert.ConversionExecutionException; -import org.springframework.core.convert.ConversionExecutor; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.Converter; import org.springframework.core.style.ToStringCreator; diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticSuperConversionExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticSuperConversionExecutor.java index 58241e9f615d..e1f1303391ca 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticSuperConversionExecutor.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticSuperConversionExecutor.java @@ -16,7 +16,6 @@ package org.springframework.core.convert.service; import org.springframework.core.convert.ConversionExecutionException; -import org.springframework.core.convert.ConversionExecutor; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.SuperConverter; import org.springframework.core.style.ToStringCreator; diff --git a/org.springframework.core/src/test/java/org/springframework/core/convert/service/GenericConversionServiceTests.java b/org.springframework.core/src/test/java/org/springframework/core/convert/service/GenericConversionServiceTests.java index dd96160956ad..201ca828855e 100644 --- a/org.springframework.core/src/test/java/org/springframework/core/convert/service/GenericConversionServiceTests.java +++ b/org.springframework.core/src/test/java/org/springframework/core/convert/service/GenericConversionServiceTests.java @@ -31,8 +31,7 @@ import org.junit.Ignore; import org.junit.Test; import org.springframework.core.convert.ConversionExecutionException; -import org.springframework.core.convert.ConversionExecutor; -import org.springframework.core.convert.ConversionExecutorNotFoundException; +import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.NumberToNumber; @@ -84,9 +83,9 @@ public void convertReverseIndex() { @Test public void convertExecutorNotFound() { try { - service.getConversionExecutor(String.class, type(Integer.class)); + service.executeConversion("3", type(Integer.class)); fail("Should have thrown an exception"); - } catch (ConversionExecutorNotFoundException e) { + } catch (ConverterNotFoundException e) { } } @@ -161,9 +160,9 @@ public CharSequence convertBack(Number target) throws Exception { } }); try { - ConversionExecutor executor = service.getConversionExecutor(String.class, type(Integer.class)); + service.executeConversion("3", type(Integer.class)); fail("Should have failed"); - } catch (ConversionExecutorNotFoundException e) { + } catch (ConverterNotFoundException e) { } } diff --git a/org.springframework.expression/src/main/java/org/springframework/expression/spel/support/StandardTypeConverter.java b/org.springframework.expression/src/main/java/org/springframework/expression/spel/support/StandardTypeConverter.java index e1f4bfa5d428..3b11b06081b2 100644 --- a/org.springframework.expression/src/main/java/org/springframework/expression/spel/support/StandardTypeConverter.java +++ b/org.springframework.expression/src/main/java/org/springframework/expression/spel/support/StandardTypeConverter.java @@ -17,7 +17,7 @@ package org.springframework.expression.spel.support; import org.springframework.core.convert.ConversionException; -import org.springframework.core.convert.ConversionExecutorNotFoundException; +import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.service.DefaultConversionService; @@ -53,7 +53,7 @@ public <T> T convertValue(Object value, Class<T> targetType) throws EvaluationEx public Object convertValue(Object value, TypeDescriptor typeDescriptor) throws EvaluationException { try { return conversionService.executeConversion(value, typeDescriptor); - } catch (ConversionExecutorNotFoundException cenfe) { + } catch (ConverterNotFoundException cenfe) { throw new SpelException(cenfe, SpelMessages.TYPE_CONVERSION_ERROR, value.getClass(), typeDescriptor.asString()); } catch (ConversionException ce) { throw new SpelException(ce, SpelMessages.TYPE_CONVERSION_ERROR, value.getClass(), typeDescriptor.asString()); diff --git a/org.springframework.expression/src/test/java/org/springframework/expression/spel/ExpressionTestsUsingCoreConversionService.java b/org.springframework.expression/src/test/java/org/springframework/expression/spel/ExpressionTestsUsingCoreConversionService.java index 2215acb3a4ff..d3920f8b6d62 100644 --- a/org.springframework.expression/src/test/java/org/springframework/expression/spel/ExpressionTestsUsingCoreConversionService.java +++ b/org.springframework.expression/src/test/java/org/springframework/expression/spel/ExpressionTestsUsingCoreConversionService.java @@ -19,7 +19,6 @@ import java.util.ArrayList; import java.util.List; -import org.springframework.core.convert.ConversionExecutor; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.service.DefaultConversionService; import org.springframework.core.convert.service.GenericConversionService; @@ -65,17 +64,14 @@ public void testConversionsAvailable() throws Exception { // ArrayList containing List<Integer> to List<String> Class<?> clazz = typeDescriptorForListOfString.getElementType(); assertEquals(String.class,clazz); - ConversionExecutor executor = tcs.getConversionExecutor(ArrayList.class, typeDescriptorForListOfString); - assertNotNull(executor); - List l = (List)executor.execute(listOfInteger); + List l = (List) tcs.executeConversion(listOfInteger, typeDescriptorForListOfString); assertNotNull(l); // ArrayList containing List<String> to List<Integer> clazz = typeDescriptorForListOfInteger.getElementType(); assertEquals(Integer.class,clazz); - executor = tcs.getConversionExecutor(ArrayList.class, typeDescriptorForListOfInteger); - assertNotNull(executor); - l = (List)executor.execute(listOfString); + + l = (List) tcs.executeConversion(listOfString, typeDescriptorForListOfString); assertNotNull(l); }
6a3f6b3b9a32d70c7b58bbbf40046497bc415931
intellij-community
Maven: escaping support in the resource- compiler (IDEADEV-35524)--
c
https://github.com/JetBrains/intellij-community
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java index 64d18ee679890..2d9a8b2893f2a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java @@ -11,6 +11,7 @@ import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; @@ -132,10 +133,15 @@ protected void run(Result<ProcessingItem[]> resultObject) throws Throwable { if (mavenProject == null) continue; Properties properties = loadFilters(context, mavenProject); + String escapeString = mavenProject.findPluginConfigurationValue("org.apache.maven.plugins", + "maven-resources-plugin", + "escapeString"); + if (escapeString == null) escapeString = "\\"; + long propertiesHashCode = calculateHashCode(properties); - collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, false, itemsToProcess); - collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, true, itemsToProcess); + collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, escapeString, false, itemsToProcess); + collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, escapeString, true, itemsToProcess); collectItemsToDelete(eachModule, itemsToProcess, filesToDelete); } if (!filesToDelete.isEmpty()) { @@ -181,6 +187,7 @@ private void collectProcessingItems(Module module, CompileContext context, Properties properties, long propertiesHashCode, + String escapeString, boolean tests, List<ProcessingItem> result) { String outputDir = CompilerPaths.getModuleOutputPath(module, tests); @@ -206,6 +213,7 @@ private void collectProcessingItems(Module module, each.isFiltering(), properties, propertiesHashCode, + escapeString, result, context.getProgressIndicator()); } @@ -232,6 +240,7 @@ private void collectProcessingItems(Module module, boolean isSourceRootFiltered, Properties properties, long propertiesHashCode, + String escapeString, List<ProcessingItem> result, ProgressIndicator indicator) { indicator.checkCanceled(); @@ -247,6 +256,7 @@ private void collectProcessingItems(Module module, isSourceRootFiltered, properties, propertiesHashCode, + escapeString, result, indicator); } @@ -255,7 +265,13 @@ private void collectProcessingItems(Module module, if (!MavenUtil.isIncluded(relPath, includes, excludes)) continue; String outputPath = outputDir + "/" + relPath; - result.add(new MyProcessingItem(module, eachSourceFile, outputPath, isSourceRootFiltered, properties, propertiesHashCode)); + result.add(new MyProcessingItem(module, + eachSourceFile, + outputPath, + isSourceRootFiltered, + properties, + propertiesHashCode, + escapeString)); } } } @@ -318,7 +334,7 @@ public ProcessingItem[] process(final CompileContext context, ProcessingItem[] i String charset = getCharsetName(sourceVirtualFile); String text = new String(FileUtil.loadFileBytes(sourceFile), charset); - text = PropertyResolver.resolve(eachItem.getModule(), text, eachItem.getProperties()); + text = PropertyResolver.resolve(eachItem.getModule(), text, eachItem.getProperties(), eachItem.getEscapeString()); FileUtil.writeToFile(outputFile, text.getBytes(charset)); } else { @@ -382,6 +398,7 @@ private static class MyProcessingItem implements ProcessingItem { private final String myOutputPath; private final boolean myFiltered; private final Properties myProperties; + private String myEscapeString; private final MyValididtyState myState; public MyProcessingItem(Module module, @@ -389,13 +406,15 @@ public MyProcessingItem(Module module, String outputPath, boolean isFiltered, Properties properties, - long propertiesHashCode) { + long propertiesHashCode, + String escapeString) { myModule = module; mySourceFile = sourceFile; myOutputPath = outputPath; myFiltered = isFiltered; myProperties = properties; - myState = new MyValididtyState(mySourceFile, isFiltered, propertiesHashCode); + myEscapeString = escapeString; + myState = new MyValididtyState(sourceFile, isFiltered, propertiesHashCode, escapeString); } @NotNull @@ -419,6 +438,10 @@ public Properties getProperties() { return myProperties; } + public String getEscapeString() { + return myEscapeString; + } + public ValidityState getValidityState() { return myState; } @@ -445,19 +468,21 @@ private static class MyValididtyState implements ValidityState { TimestampValidityState myTimestampState; private boolean myFiltered; private long myPropertiesHashCode; + private String myEscapeString; public static MyValididtyState load(DataInput in) throws IOException { - return new MyValididtyState(TimestampValidityState.load(in), in.readBoolean(), in.readLong()); + return new MyValididtyState(TimestampValidityState.load(in), in.readBoolean(), in.readLong(), in.readUTF()); } - public MyValididtyState(VirtualFile file, boolean isFiltered, long propertiesHashCode) { - this(new TimestampValidityState(file.getTimeStamp()), isFiltered, propertiesHashCode); + public MyValididtyState(VirtualFile file, boolean isFiltered, long propertiesHashCode, String escapeString) { + this(new TimestampValidityState(file.getTimeStamp()), isFiltered, propertiesHashCode, escapeString); } - private MyValididtyState(TimestampValidityState timestampState, boolean isFiltered, long propertiesHashCode) { + private MyValididtyState(TimestampValidityState timestampState, boolean isFiltered, long propertiesHashCode, String escapeString) { myTimestampState = timestampState; myFiltered = isFiltered; myPropertiesHashCode = propertiesHashCode; + myEscapeString = escapeString; } public boolean equalsTo(ValidityState otherState) { @@ -465,13 +490,15 @@ public boolean equalsTo(ValidityState otherState) { MyValididtyState state = (MyValididtyState)otherState; return myTimestampState.equalsTo(state.myTimestampState) && myFiltered == state.myFiltered - && myPropertiesHashCode == state.myPropertiesHashCode; + && myPropertiesHashCode == state.myPropertiesHashCode + && Comparing.strEqual(myEscapeString, state.myEscapeString); } public void save(DataOutput out) throws IOException { myTimestampState.save(out); out.writeBoolean(myFiltered); out.writeLong(myPropertiesHashCode); + out.writeUTF(myEscapeString); } } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/PropertyResolver.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/PropertyResolver.java index b213b54337ad4..2210fe5da5a49 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/PropertyResolver.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/PropertyResolver.java @@ -23,11 +23,11 @@ public class PropertyResolver { private static final Pattern PATTERN = Pattern.compile("\\$\\{([^}]+)\\}"); - public static String resolve(Module module, String text, Properties additionalProperties) { + public static String resolve(Module module, String text, Properties additionalProperties, String escapeString) { MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject()); MavenProjectModel mavenProject = manager.findProject(module); if (mavenProject == null) return text; - return doResolve(text, mavenProject, additionalProperties, new Stack<String>()); + return doResolve(text, mavenProject, additionalProperties, escapeString, new Stack<String>()); } public static String resolve(GenericDomValue<String> value) { @@ -44,7 +44,7 @@ public static String resolve(String text, DomFileElement<MavenModel> dom) { MavenProjectModel mavenProject = manager.findProject(file); if (mavenProject == null) return text; - return doResolve(text, mavenProject, collectPropertiesFromDOM(mavenProject, dom), new Stack<String>()); + return doResolve(text, mavenProject, collectPropertiesFromDOM(mavenProject, dom), null, new Stack<String>()); } private static Properties collectPropertiesFromDOM(MavenProjectModel project, DomFileElement<MavenModel> dom) { @@ -71,18 +71,38 @@ private static void collectPropertiesFromDOM(Properties result, MavenProperties } } - private static String doResolve(String text, MavenProjectModel project, Properties additionalProperties, Stack<String> resolutionStack) { + private static String doResolve(String text, + MavenProjectModel project, + Properties additionalProperties, + String escapeString, + Stack<String> resolutionStack) { Matcher matcher = PATTERN.matcher(text); StringBuffer buff = new StringBuffer(); + StringBuffer dummy = new StringBuffer(); + int last = 0; while (matcher.find()) { String propText = matcher.group(); String propName = matcher.group(1); + + int tempLast = last; + last = matcher.start() + propText.length(); + + if (escapeString != null) { + int pos = matcher.start(); + if (pos > escapeString.length() && text.substring(pos - escapeString.length(), pos).equals(escapeString)) { + buff.append(text.substring(tempLast, pos - escapeString.length())); + buff.append(propText); + matcher.appendReplacement(dummy, ""); + continue; + } + } + String resolved = doResolveProperty(propName, project, additionalProperties); if (resolved == null) resolved = propText; if (!resolved.equals(propText) && !resolutionStack.contains(propName)) { resolutionStack.push(propName); - resolved = doResolve(resolved, project, additionalProperties, resolutionStack); + resolved = doResolve(resolved, project, additionalProperties, escapeString, resolutionStack); resolutionStack.pop(); } matcher.appendReplacement(buff, Matcher.quoteReplacement(resolved)); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java index 397e2092d1d59..3ac9b58a94c5c 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java @@ -456,6 +456,71 @@ public void testPluginDirectoriesFiltering() throws Exception { assertResult("target/classes/file2.properties", "value=${xxx}"); } + public void testEscapingFiltering() throws Exception { + createProjectSubFile("filters/filter.properties", "xxx=value"); + createProjectSubFile("resources/file.properties", + "value1=\\${xxx}\n" + + "value2=${xxx}\n"); + + importProject("<groupId>test</groupId>" + + "<artifactId>project</artifactId>" + + "<version>1</version>" + + + "<build>" + + " <filters>" + + " <filter>filters/filter.properties</filter>" + + " </filters>" + + " <resources>" + + " <resource>" + + " <directory>resources</directory>" + + " <filtering>true</filtering>" + + " </resource>" + + " </resources>" + + "</build>"); + + compileModules("project"); + assertResult("target/classes/file.properties", + "value1=${xxx}\n" + + "value2=value\n"); + } + + public void testCustomEscapingFiltering() throws Exception { + createProjectSubFile("filters/filter.properties", "xxx=value"); + createProjectSubFile("resources/file.properties", + "value1=^${xxx}\n" + + "value2=\\${xxx}\n"); + + importProject("<groupId>test</groupId>" + + "<artifactId>project</artifactId>" + + "<version>1</version>" + + + "<build>" + + " <filters>" + + " <filter>filters/filter.properties</filter>" + + " </filters>" + + " <resources>" + + " <resource>" + + " <directory>resources</directory>" + + " <filtering>true</filtering>" + + " </resource>" + + " </resources>" + + " <plugins>" + + " <plugin>" + + " <groupId>org.apache.maven.plugins</groupId>" + + " <artifactId>maven-resources-plugin</artifactId>" + + " <configuration>" + + " <escapeString>^</escapeString>" + + " </configuration>" + + " </plugin>" + + " </plugins>" + + "</build>"); + + compileModules("project"); + assertResult("target/classes/file.properties", + "value1=${xxx}\n" + + "value2=\\value\n"); + } + private void assertResult(String relativePath, String content) throws IOException { assertResult(myProjectPom, relativePath, content); } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/PropertyResolverTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/PropertyResolverTest.java index 03b9c437adf41..18b592f93f67f 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/PropertyResolverTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/PropertyResolverTest.java @@ -12,6 +12,7 @@ import org.jetbrains.idea.maven.dom.model.MavenModel; import java.io.File; +import java.util.Properties; public class PropertyResolverTest extends MavenImportingTestCase { public void testResolvingProjectAttributes() throws Exception { @@ -229,6 +230,21 @@ public void testUncomittedProperties() throws Exception { assertEquals("value", resolve("${uncomitted}", myProjectPom)); } + public void testEscaping() throws Exception { + importProject("<groupId>test</groupId>" + + "<artifactId>project</artifactId>" + + "<version>1</version>"); + + assertEquals("foo ^project bar", + PropertyResolver.resolve(getModule("project"), "foo ^${project.artifactId} bar", new Properties(), "/")); + assertEquals("foo ${project.artifactId} bar", + PropertyResolver.resolve(getModule("project"), "foo ^^${project.artifactId} bar", new Properties(), "^^")); + assertEquals("project ${project.artifactId} project ${project.artifactId}", + PropertyResolver.resolve(getModule("project"), + "${project.artifactId} ^${project.artifactId} ${project.artifactId} ^${project.artifactId}", + new Properties(), "^")); + } + private String resolve(String text, VirtualFile f) { Document d = FileDocumentManager.getInstance().getDocument(f); PsiFile psi = PsiDocumentManager.getInstance(myProject).getPsiFile(d);