commit_id
stringlengths 40
40
| project
stringclasses 91
values | commit_message
stringlengths 9
4.65k
| type
stringclasses 3
values | url
stringclasses 91
values | git_diff
stringlengths 555
2.23M
|
|---|---|---|---|---|---|
b2b6fb85f6257cca5f28ad34b9a88ca660a9f0d9
|
aeshell$aesh
|
Introduce a cleaner lower level API with the Console interface.
It provides a signal api, access to the underlying terminal capabilities and stty settings.
It also brings support for virtual consoles when using remote connections for example.
It抯 not much leveraged in the remaining of the code. Things like cursor movements, etc.. should leverage this information.
The AeshInputStream hacks for transforming windows arrow keys can be just removed, and it should also be noted that the AeshInputStream does not correctly handle the encoding of the input stream and assumes the default charset, which is always not the case, especially on windows.
The only external dependency on those 3 new packages (api, impl, utils) is the LoggerUtil class.
This means that this can easily be extracted as the very-low component.
|
a
|
https://github.com/aeshell/aesh
|
diff --git a/pom.xml b/pom.xml
index 6de416fdd..d0e97931f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -100,6 +100,13 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.8</source>
+ <target>1.8</target>
+ </configuration>
+ </plugin>
</plugins>
</build>
diff --git a/src/main/java/org/jboss/aesh/console/settings/SettingsImpl.java b/src/main/java/org/jboss/aesh/console/settings/SettingsImpl.java
index 403a35591..8c6df5f9f 100644
--- a/src/main/java/org/jboss/aesh/console/settings/SettingsImpl.java
+++ b/src/main/java/org/jboss/aesh/console/settings/SettingsImpl.java
@@ -30,9 +30,8 @@
import org.jboss.aesh.edit.ViEditMode;
import org.jboss.aesh.io.FileResource;
import org.jboss.aesh.io.Resource;
-import org.jboss.aesh.terminal.POSIXTerminal;
+import org.jboss.aesh.terminal.ShellWrapper;
import org.jboss.aesh.terminal.Terminal;
-import org.jboss.aesh.terminal.WindowsTerminal;
import java.io.File;
import java.io.InputStream;
@@ -372,10 +371,7 @@ public void setStdErr(PrintStream stdErr) {
@Override
public Terminal getTerminal() {
if(terminal == null) {
- if(Config.isOSPOSIXCompatible())
- terminal = new POSIXTerminal();
- else
- terminal = new WindowsTerminal();
+ terminal = new ShellWrapper(this);
}
return terminal;
diff --git a/src/main/java/org/jboss/aesh/terminal/AbstractTerminal.java b/src/main/java/org/jboss/aesh/terminal/AbstractTerminal.java
deleted file mode 100644
index 86c9755a8..000000000
--- a/src/main/java/org/jboss/aesh/terminal/AbstractTerminal.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
- * as indicated by the @authors tag. All rights reserved.
- * See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * 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.jboss.aesh.terminal;
-
-import org.jboss.aesh.console.Config;
-import org.jboss.aesh.console.reader.AeshStandardStream;
-import org.jboss.aesh.console.settings.Settings;
-import org.jboss.aesh.util.ANSI;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * @author <a href="mailto:[email protected]">Ståle W. Pedersen</a>
- */
-public abstract class AbstractTerminal implements Terminal, Shell {
-
- private final Logger logger;
- protected Settings settings;
- private boolean mainBuffer = true;
-
- AbstractTerminal(Logger logger) {
- this.logger = logger;
- }
-
-
- /**
- * Return the row position if we use a ansi terminal
- * Send a terminal: '<ESC>[6n'
- * and we receive the position as: '<ESC>[n;mR'
- * where n = current row and m = current column
- */
- @Override
- public CursorPosition getCursor() {
- if(settings.isAnsiConsole() && Config.isOSPOSIXCompatible()) {
- try {
- StringBuilder col = new StringBuilder(4);
- StringBuilder row = new StringBuilder(4);
- out().print(ANSI.CURSOR_ROW);
- out().flush();
- boolean gotSep = false;
- //read the position
- int[] input = read();
-
- for(int i=2; i < input.length-1; i++) {
- if(input[i] == 59) // we got a ';' which is the separator
- gotSep = true;
- else {
- if(gotSep)
- col.append((char) input[i]);
- else
- row.append((char) input[i]);
- }
- }
- return new CursorPosition(Integer.parseInt(row.toString()), Integer.parseInt(col.toString()));
- }
- catch (Exception e) {
- if(settings.isLogging())
- logger.log(Level.SEVERE, "Failed to find current row with ansi code: ",e);
- return new CursorPosition(-1,-1);
- }
- }
- return new CursorPosition(-1,-1);
- }
-
- @Override
- public void setCursor(CursorPosition position) {
- if(getSize().isPositionWithinSize(position)) {
- out().print(position.asAnsi());
- out().flush();
- }
- }
-
- @Override
- public void moveCursor(int rows, int columns) {
- CursorPosition cp = getCursor();
- cp.move(rows, columns);
- if(getSize().isPositionWithinSize(cp)) {
- setCursor(cp);
- }
- }
-
- @Override
- public void clear() {
- out().print(ANSI.CLEAR_SCREEN);
- out().flush();
- }
-
- @Override
- public boolean isMainBuffer() {
- return mainBuffer;
- }
-
- @Override
- public void enableAlternateBuffer() {
- if(isMainBuffer()) {
- out().print(ANSI.ALTERNATE_BUFFER);
- out().flush();
- mainBuffer = false;
- }
- }
-
- @Override
- public void enableMainBuffer() {
- if(!isMainBuffer()) {
- out().print(ANSI.MAIN_BUFFER);
- out().flush();
- mainBuffer = true;
- }
- }
-
- @Override
- public Shell getShell() {
- return this;
- }
-
- @Override
- public AeshStandardStream in() {
- return null;
- }
-}
diff --git a/src/main/java/org/jboss/aesh/terminal/InfocmpManager.java b/src/main/java/org/jboss/aesh/terminal/InfocmpManager.java
index 5d9535388..f6861adf4 100644
--- a/src/main/java/org/jboss/aesh/terminal/InfocmpManager.java
+++ b/src/main/java/org/jboss/aesh/terminal/InfocmpManager.java
@@ -19,7 +19,9 @@
*/
package org.jboss.aesh.terminal;
-import org.jboss.aesh.terminal.InfoCmp.Capability;
+import org.jboss.aesh.terminal.utils.Curses;
+import org.jboss.aesh.terminal.utils.InfoCmp;
+import org.jboss.aesh.terminal.utils.InfoCmp.Capability;
import org.jboss.aesh.util.LoggerUtil;
import java.io.StringWriter;
diff --git a/src/main/java/org/jboss/aesh/terminal/POSIXTerminal.java b/src/main/java/org/jboss/aesh/terminal/POSIXTerminal.java
deleted file mode 100644
index b7ab7c6d5..000000000
--- a/src/main/java/org/jboss/aesh/terminal/POSIXTerminal.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
- * as indicated by the @authors tag. All rights reserved.
- * See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * 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.jboss.aesh.terminal;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.jboss.aesh.console.Config;
-import org.jboss.aesh.console.reader.ConsoleInputSession;
-import org.jboss.aesh.console.settings.Settings;
-import org.jboss.aesh.util.LoggerUtil;
-
-/**
- * Terminal that should work on most POSIX systems
- *
- * @author Ståle W. Pedersen <[email protected]>
- */
-public class POSIXTerminal extends AbstractTerminal {
-
- private TerminalSize size;
- private boolean echoEnabled;
- private String ttyConfig;
- private String ttyProps;
- private long ttyPropsLastFetched;
- private boolean restored = false;
-
- private ConsoleInputSession input;
- private PrintStream stdOut;
- private PrintStream stdErr;
-
- private static final long TIMEOUT_PERIOD = 3000;
-
- private static final Logger LOGGER = LoggerUtil.getLogger(POSIXTerminal.class.getName());
-
- public POSIXTerminal() {
- super(LOGGER);
- }
-
- @Override
- public void init(Settings settings) {
- this.settings = settings;
- // save the initial tty configuration, this should work on posix and cygwin
- try {
- ttyConfig = stty("-g");
-
- // sanity check
- if ((ttyConfig.length() == 0)
- || ((!ttyConfig.contains("=")) && (!ttyConfig.contains(":")))) {
- if(settings.isLogging())
- LOGGER.log(Level.SEVERE, "Unrecognized stty code: "+ttyConfig);
- throw new RuntimeException("Unrecognized stty code: " + ttyConfig);
- }
-
- if(Config.isCygwin()) {
- stty("-ixon -icanon min 1 intr undef -echo");
- }
- else {
- // set the console to be character-buffered instead of line-buffered
- // -ixon will give access to ctrl-s/ctrl-q
- //intr undef ctrl-c will no longer send the interrupt signal
- //icrnl, translate carriage return to newline (needed when aesh is started in the background)
- //susb undef, ctrl-z will no longer send the stop signal
- stty("-ixon -icanon min 1 intr undef icrnl susp undef");
-
- // disable character echoing
- stty("-echo");
- }
- echoEnabled = false;
-
- }
- catch (IOException ioe) {
- if(settings.isLogging())
- LOGGER.log(Level.SEVERE, "tty failed: ",ioe);
- }
- catch (InterruptedException e) {
- if(settings.isLogging())
- LOGGER.log(Level.SEVERE, "failed while waiting for process to end: ",e);
- e.printStackTrace();
- }
-
- //setting up input
- //input = new AeshInputStream(settings.getInputStream());
- input = new ConsoleInputSession(settings.getInputStream());
-
- this.stdOut = settings.getStdOut();
- this.stdErr = settings.getStdErr();
- size = new TerminalSize(getHeight(), getWidth());
- }
-
- /**
- * @see org.jboss.aesh.terminal.Terminal
- */
- @Override
- public int[] read() throws IOException {
- return input.readAll();
- }
-
- @Override
- public boolean hasInput() {
- return input.hasInput();
- }
-
- @Override
- public TerminalSize getSize() {
- if(propertiesTimedOut()) {
- size.setHeight(getHeight());
- size.setWidth(getWidth());
- }
- return size;
- }
-
- private int getHeight() {
- int height = 0;
- try {
- height = getTerminalProperty("rows");
- }
- catch (Exception e) {
- if(settings.isLogging())
- LOGGER.log(Level.SEVERE,"Failed to fetch terminal height: ",e);
- }
- //cant use height < 1
- if(height < 1)
- height = 24;
-
- return height;
- }
-
- private int getWidth() {
- int width = 0;
- try {
- width = getTerminalProperty("columns");
- }
- catch (Exception e) {
- if(settings.isLogging())
- LOGGER.log(Level.SEVERE,"Failed to fetch terminal width: ",e);
- }
- //cant use with < 1
- if(width < 1)
- width = 80;
-
- return width;
- }
-
- /**
- * @see org.jboss.aesh.terminal.Terminal
- */
- @Override
- public boolean isEchoEnabled() {
- return echoEnabled;
- }
-
- /**
- * @see org.jboss.aesh.terminal.Terminal
- */
- @Override
- public void reset() throws IOException {
- if(!restored) {
- if (ttyConfig != null) {
- try {
- stty(ttyConfig);
- ttyConfig = null;
- restored = true;
- }
- catch (InterruptedException e) {
- if(settings.isLogging())
- LOGGER.log(Level.SEVERE,"Failed to reset terminal: ",e);
- }
- }
- }
- }
-
- @Override
- public void writeToInputStream(String data) {
- input.writeToInput(data);
- }
-
- @Override
- public void changeOutputStream(PrintStream output) {
- stdOut = output;
- }
-
- @Override
- public void close() throws IOException {
- input.stop();
- }
-
- private boolean propertiesTimedOut() {
- return (System.currentTimeMillis() -ttyPropsLastFetched) > TIMEOUT_PERIOD;
- }
-
- private int getTerminalProperty(String prop) throws IOException, InterruptedException {
- // tty properties are cached so we don't have to worry too much about getting term width/height
- if (ttyProps == null || propertiesTimedOut()) {
- ttyProps = stty("-a");
- ttyPropsLastFetched = System.currentTimeMillis();
- }
- // need to be able handle both output formats:
- // speed 9600 baud; 24 rows; 140 columns;
- // and:
- // speed 38400 baud; rows = 49; columns = 111;
- for (String str : ttyProps.split(";")) {
- str = str.trim();
- if (str.startsWith(prop)) {
- int index = str.lastIndexOf(" ");
-
- return Integer.parseInt(str.substring(index).trim());
- }
- else if (str.endsWith(prop)) {
- int index = str.indexOf(" ");
-
- return Integer.parseInt(str.substring(0, index).trim());
- }
- }
-
- return -1;
- }
-
- /**
- * Run stty with arguments on the active terminal
- *
- * @param args arguments
- * @return output
- * @throws IOException stream
- * @throws InterruptedException stream
- */
- protected static String stty(final String args) throws IOException, InterruptedException {
- return exec("stty " + args + " < /dev/tty").trim();
- }
-
- /**
- * Run a command and return the output
- *
- * @param cmd what to execute
- * @return output
- * @throws java.io.IOException stream
- * @throws InterruptedException stream
- */
- private static String exec(final String cmd) throws IOException, InterruptedException {
- return exec(new String[] { "sh", "-c", cmd });
- }
-
- /**
- * Run a command and return the output
- *
- * @param cmd the command
- * @return output
- * @throws IOException stream
- * @throws InterruptedException stream
- */
- private static String exec(final String[] cmd) throws IOException, InterruptedException {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
-
- Process p = Runtime.getRuntime().exec(cmd);
- int c;
- InputStream in = null;
- InputStream err = null;
- OutputStream out = null;
-
- try {
- in = p.getInputStream();
-
- while ((c = in.read()) != -1) {
- bout.write(c);
- }
-
- err = p.getErrorStream();
-
- while ((c = err.read()) != -1) {
- bout.write(c);
- }
-
- out = p.getOutputStream();
-
- p.waitFor();
- }
- finally {
- try {
- if(in != null)
- in.close();
- if(err != null)
- err.close();
- if(out != null)
- out.close();
- }
- catch (Exception e) {
- LOGGER.log(Level.SEVERE,"Failed to close streams: ",e);
- }
- }
-
- return new String(bout.toByteArray());
- }
-
- @Override
- public PrintStream err() {
- return stdErr;
- }
-
- @Override
- public PrintStream out() {
- return stdOut;
- }
-
-}
diff --git a/src/main/java/org/jboss/aesh/terminal/ShellWrapper.java b/src/main/java/org/jboss/aesh/terminal/ShellWrapper.java
new file mode 100644
index 000000000..2e94b11bf
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/ShellWrapper.java
@@ -0,0 +1,211 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
+ * as indicated by the @authors tag. All rights reserved.
+ * See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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.jboss.aesh.terminal;
+
+import java.io.IOError;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.jboss.aesh.console.reader.AeshStandardStream;
+import org.jboss.aesh.console.reader.ConsoleInputSession;
+import org.jboss.aesh.console.settings.Settings;
+import org.jboss.aesh.terminal.api.Attributes;
+import org.jboss.aesh.terminal.api.Console;
+import org.jboss.aesh.terminal.api.Console.Signal;
+import org.jboss.aesh.terminal.api.ConsoleBuilder;
+import org.jboss.aesh.terminal.api.Size;
+import org.jboss.aesh.terminal.utils.InfoCmp.Capability;
+import org.jboss.aesh.util.LoggerUtil;
+
+public class ShellWrapper implements Terminal, Shell {
+
+ private static final Logger LOGGER = LoggerUtil.getLogger(ShellWrapper.class.getName());
+
+ private Settings settings;
+ private Console console;
+ private PrintStream out;
+ private PrintStream err;
+ private ConsoleInputSession input;
+ private Attributes attributes;
+
+ private boolean mainBuffer = true;
+
+ public ShellWrapper(Settings settings) {
+ this.settings = settings;
+ }
+
+ @Override
+ public void init(Settings settings) {
+ try {
+ console = ConsoleBuilder.builder()
+ .streams(settings.getInputStream(), settings.getStdOut())
+ .name("Aesh console")
+ .build();
+ attributes = console.enterRawMode();
+ out = new PrintStream(console.output());
+ err = settings.getStdErr();
+ input = new ConsoleInputSession(console.input());
+ // bridge to the current way of supporting signals
+ console.handle(Signal.INT, s -> input.writeToInput("\u0003"));
+ } catch (IOException e) {
+ throw new IOError(e);
+ }
+ }
+
+ @Override
+ public PrintStream out() {
+ return out;
+ }
+
+ @Override
+ public PrintStream err() {
+ return err;
+ }
+
+ @Override
+ public TerminalSize getSize() {
+ Size size = console.getSize();
+ return new TerminalSize(size.getHeight(), size.getWidth());
+ }
+
+ @Override
+ public int[] read() throws IOException {
+ return input.readAll();
+ }
+
+ @Override
+ public boolean hasInput() {
+ return input.hasInput();
+ }
+
+ @Override
+ public boolean isEchoEnabled() {
+ return console.echo();
+ }
+
+ @Override
+ public void reset() throws IOException {
+ console.setAttributes(attributes);
+ }
+
+ @Override
+ public void writeToInputStream(String data) {
+ input.writeToInput(data);
+ }
+
+ @Override
+ public void changeOutputStream(PrintStream output) {
+ out = output;
+ }
+
+ @Override
+ public void close() throws IOException {
+ console.close();
+ }
+
+ @Override
+ public Shell getShell() {
+ return this;
+ }
+
+ @Override
+ public void clear() throws IOException {
+ console.puts(Capability.clear_screen);
+ }
+
+ @Override
+ public AeshStandardStream in() {
+ return null;
+ }
+
+ @Override
+ public CursorPosition getCursor() {
+ if (console.puts(Capability.user7)) {
+ try {
+ console.flush();
+ StringBuilder col = new StringBuilder(4);
+ StringBuilder row = new StringBuilder(4);
+ boolean gotSep = false;
+ //read the position
+ int[] input = read();
+
+ for(int i=2; i < input.length-1; i++) {
+ if(input[i] == 59) // we got a ';' which is the separator
+ gotSep = true;
+ else {
+ if(gotSep)
+ col.append((char) input[i]);
+ else
+ row.append((char) input[i]);
+ }
+ }
+ return new CursorPosition(Integer.parseInt(row.toString()), Integer.parseInt(col.toString()));
+ }
+ catch (Exception e) {
+ if(settings.isLogging())
+ LOGGER.log(Level.SEVERE, "Failed to find current row with ansi code: ",e);
+ return new CursorPosition(-1,-1);
+ }
+ }
+ return new CursorPosition(-1,-1);
+ }
+
+ @Override
+ public void setCursor(CursorPosition position) {
+ if (getSize().isPositionWithinSize(position)
+ && console.puts(Capability.cursor_address,
+ position.getRow(),
+ position.getColumn())) {
+ console.flush();
+ }
+ }
+
+ @Override
+ public void moveCursor(int rows, int columns) {
+ CursorPosition cp = getCursor();
+ cp.move(rows, columns);
+ if (getSize().isPositionWithinSize(cp)) {
+ setCursor(cp);
+ }
+ }
+
+ @Override
+ public boolean isMainBuffer() {
+ return mainBuffer;
+ }
+
+ @Override
+ public void enableAlternateBuffer() {
+ if (isMainBuffer() && console.puts(Capability.enter_ca_mode)) {
+ console.flush();
+ mainBuffer = false;
+ }
+ }
+
+ @Override
+ public void enableMainBuffer() {
+ if (!isMainBuffer() && console.puts(Capability.exit_ca_mode)) {
+ console.flush();
+ mainBuffer = false;
+ }
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/WindowsTerminal.java b/src/main/java/org/jboss/aesh/terminal/WindowsTerminal.java
deleted file mode 100644
index 33406a26b..000000000
--- a/src/main/java/org/jboss/aesh/terminal/WindowsTerminal.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
- * as indicated by the @authors tag. All rights reserved.
- * See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * 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.jboss.aesh.terminal;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.fusesource.jansi.AnsiOutputStream;
-import org.fusesource.jansi.WindowsAnsiOutputStream;
-import org.fusesource.jansi.internal.WindowsSupport;
-import org.jboss.aesh.console.reader.ConsoleInputSession;
-import org.jboss.aesh.console.settings.Settings;
-import org.jboss.aesh.util.LoggerUtil;
-
-/**
- *
- * @author Ståle W. Pedersen <[email protected]>
- */
-public class WindowsTerminal extends AbstractTerminal {
-
- private PrintStream stdOut;
- private PrintStream stdErr;
- private TerminalSize size;
- private ConsoleInputSession input;
-
- private long ttyPropsLastFetched;
- private static long TIMEOUT_PERIOD = 2000;
-
- private static final Logger LOGGER = LoggerUtil.getLogger(WindowsTerminal.class.getName());
-
- public WindowsTerminal() {
- super(LOGGER);
- }
-
- @Override
- public void init(Settings settings) {
- this.settings = settings;
- //setting up reader
- try {
- //AnsiConsole.systemInstall();
- this.stdOut = new PrintStream( new WindowsAnsiOutputStream(settings.getStdOut()), true);
- this.stdErr = new PrintStream( new WindowsAnsiOutputStream(settings.getStdErr()), true);
-
- }
- catch (Exception ioe) {
- this.stdOut = new PrintStream( new AnsiOutputStream(settings.getStdOut()), true);
- this.stdErr = new PrintStream( new AnsiOutputStream(settings.getStdErr()), true);
- }
-
- if(settings.getInputStream().equals(System.in)) {
- InputStream inStream = new InputStream() {
- @Override
- public int read() throws IOException {
- return WindowsSupport.readByte();
- }
-
- @Override
- public int read(byte[] in) throws IOException {
- byte[] tmp = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(WindowsSupport.readByte()).array();
- in[0] = tmp[0];
- return 1;
- }
-
- public void close() {
- WindowsSupport.flushConsoleInputBuffer();
- }
- };
- this.input = new ConsoleInputSession(inStream);
- //this.input = new ConsoleInputSession(inStream).getExternalInputStream();
- }
- else {
- this.input = new ConsoleInputSession(settings.getInputStream());
- }
- }
-
- @Override
- public int[] read() throws IOException {
- return input.readAll();
- }
-
- @Override
- public boolean hasInput() {
- return input.hasInput();
- }
-
- private int getHeight() {
- int height;
- height = WindowsSupport.getWindowsTerminalHeight();
- ttyPropsLastFetched = System.currentTimeMillis();
- if(height < 1) {
- if(settings.isLogging())
- LOGGER.log(Level.SEVERE, "Fetched terminal height is "+height+", setting it to 24");
- height = 24;
- }
- return height;
- }
-
- private int getWidth() {
- int width;
- width = WindowsSupport.getWindowsTerminalWidth();
- ttyPropsLastFetched = System.currentTimeMillis();
- if(width < 1) {
- if(settings.isLogging())
- LOGGER.log(Level.SEVERE, "Fetched terminal width is "+width+", setting it to 80");
- width = 80;
- }
- return width;
- }
-
- @Override
- public TerminalSize getSize() {
- if(propertiesTimedOut()) {
- if(size == null) {
- size = new TerminalSize(getHeight(), getWidth());
- }
- else {
- size.setHeight(getHeight());
- size.setWidth(getWidth());
- }
- }
- return size;
- }
-
- @Override
- public boolean isEchoEnabled() {
- return false;
- }
-
- @Override
- public void reset() throws IOException {
- }
-
- @Override
- public void writeToInputStream(String data) {
- input.writeToInput(data);
- }
-
- @Override
- public void changeOutputStream(PrintStream output) {
- stdOut = output;
- }
-
- @Override
- public void close() throws IOException {
- input.stop();
- }
-
- private boolean propertiesTimedOut() {
- return (System.currentTimeMillis() -ttyPropsLastFetched) > TIMEOUT_PERIOD;
- }
-
- @Override
- public PrintStream err() {
- return stdErr;
- }
-
- @Override
- public PrintStream out() {
- return stdOut;
- }
-}
-
diff --git a/src/main/java/org/jboss/aesh/terminal/api/Attributes.java b/src/main/java/org/jboss/aesh/terminal/api/Attributes.java
new file mode 100644
index 000000000..aa6c45e9e
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/api/Attributes.java
@@ -0,0 +1,392 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.api;
+
+import java.util.EnumSet;
+
+public class Attributes {
+
+ /**
+ * Control characters
+ */
+ public enum ControlChar {
+ VEOF(0),
+ VEOL(1),
+ VEOL2(2),
+ VERASE(3),
+ VWERASE(4),
+ VKILL(5),
+ VREPRINT(6),
+ VINTR(8),
+ VQUIT(9),
+ VSUSP(10),
+ VDSUSP(11),
+ VSTART(12),
+ VSTOP(13),
+ VLNEXT(14),
+ VDISCARD(15),
+ VMIN(16),
+ VTIME(17),
+ VSTATUS(18);
+
+ final int value;
+
+ ControlChar(int value) {
+ this.value = value;
+ }
+
+ }
+
+ /**
+ * Input flags - software input processing
+ */
+ public enum InputFlag {
+ IGNBRK (0x00000001), /* ignore BREAK condition */
+ BRKINT (0x00000002), /* map BREAK to SIGINTR */
+ IGNPAR (0x00000004), /* ignore (discard) parity errors */
+ PARMRK (0x00000008), /* mark parity and framing errors */
+ INPCK (0x00000010), /* enable checking of parity errors */
+ ISTRIP (0x00000020), /* strip 8th bit off chars */
+ INLCR (0x00000040), /* map NL into CR */
+ IGNCR (0x00000080), /* ignore CR */
+ ICRNL (0x00000100), /* map CR to NL (ala CRMOD) */
+ IXON (0x00000200), /* enable output flow control */
+ IXOFF (0x00000400), /* enable input flow control */
+ IXANY (0x00000800), /* any char will restart after stop */
+ IMAXBEL(0x00002000), /* ring bell on input queue full */
+ IUTF8 (0x00004000); /* maintain state for UTF-8 VERASE */
+
+ final int value;
+
+ InputFlag(int value) {
+ this.value = value;
+ }
+ }
+
+ /*
+ * Output flags - software output processing
+ */
+ public enum OutputFlag {
+ OPOST (0x00000001), /* enable following output processing */
+ ONLCR (0x00000002), /* map NL to CR-NL (ala CRMOD) */
+ OXTABS(0x00000004), /* expand tabs to spaces */
+ ONOEOT(0x00000008), /* discard EOT's (^D) on output) */
+ OCRNL (0x00000010), /* map CR to NL on output */
+ ONOCR (0x00000020), /* no CR output at column 0 */
+ ONLRET(0x00000040), /* NL performs CR function */
+ OFILL (0x00000080), /* use fill characters for delay */
+ NLDLY (0x00000300), /* \n delay */
+ TABDLY(0x00000c04), /* horizontal tab delay */
+ CRDLY (0x00003000), /* \r delay */
+ FFDLY (0x00004000), /* form feed delay */
+ BSDLY (0x00008000), /* \b delay */
+ VTDLY (0x00010000), /* vertical tab delay */
+ OFDEL (0x00020000); /* fill is DEL, else NUL */
+
+ final int value;
+
+ OutputFlag(int value) {
+ this.value = value;
+ }
+ }
+
+ /*
+ * Control flags - hardware control of terminal
+ */
+ public enum ControlFlag {
+ CIGNORE (0x00000001), /* ignore control flags */
+ CSIZE (0x00000300), /* character size mask */
+ CS5 (0x00000000), /* 5 bits (pseudo) */
+ CS6 (0x00000100), /* 6 bits */
+ CS7 (0x00000200), /* 7 bits */
+ CS8 (0x00000300), /* 8 bits */
+ CSTOPB (0x00000400), /* send 2 stop bits */
+ CREAD (0x00000800), /* enable receiver */
+ PARENB (0x00001000), /* parity enable */
+ PARODD (0x00002000), /* odd parity, else even */
+ HUPCL (0x00004000), /* hang up on last close */
+ CLOCAL (0x00008000), /* ignore modem status lines */
+ CCTS_OFLOW (0x00010000), /* CTS flow control of output */
+ CRTS_IFLOW (0x00020000), /* RTS flow control of input */
+ CRTSCTS (CCTS_OFLOW.value | CRTS_IFLOW.value),
+ CDTR_IFLOW (0x00040000), /* DTR flow control of input */
+ CDSR_OFLOW (0x00080000), /* DSR flow control of output */
+ CCAR_OFLOW (0x00100000); /* DCD flow control of output */
+
+ final int value;
+
+ ControlFlag(int value) {
+ this.value = value;
+ }
+ }
+
+ /*
+ * "Local" flags - dumping ground for other state
+ *
+ * Warning: some flags in this structure begin with
+ * the letter "I" and look like they belong in the
+ * input flag.
+ */
+ public enum LocalFlag {
+ ECHOKE (0x00000001), /* visual erase for line kill */
+ ECHOE (0x00000002), /* visually erase chars */
+ ECHOK (0x00000004), /* echo NL after line kill */
+ ECHO (0x00000008), /* enable echoing */
+ ECHONL (0x00000010), /* echo NL even if ECHO is off */
+ ECHOPRT (0x00000020), /* visual erase mode for hardcopy */
+ ECHOCTL (0x00000040), /* echo control chars as ^(Char) */
+ ISIG (0x00000080), /* enable signals INTR, QUIT, [D]SUSP */
+ ICANON (0x00000100), /* canonicalize input lines */
+ ALTWERASE (0x00000200), /* use alternate WERASE algorithm */
+ IEXTEN (0x00000400), /* enable DISCARD and LNEXT */
+ EXTPROC (0x00000800), /* external processing */
+ TOSTOP (0x00400000), /* stop background jobs from output */
+ FLUSHO (0x00800000), /* output being flushed (state) */
+ NOKERNINFO (0x02000000), /* no kernel output from VSTATUS */
+ PENDIN (0x20000000), /* XXX retype pending input (state) */
+ NOFLSH (0x80000000); /* don't flush after interrupt */
+
+ final int value;
+
+ LocalFlag(int value) {
+ this.value = value;
+ }
+ }
+
+ long c_iflag;
+ long c_oflag;
+ long c_cflag;
+ long c_lflag;
+ byte[] c_cc = new byte[20];
+
+ public Attributes() {
+ }
+
+ public Attributes(Attributes attr) {
+ copy(attr);
+ }
+
+ //
+ // Input flags
+ //
+
+ public EnumSet<InputFlag> getInputFlags() {
+ EnumSet<InputFlag> flags = EnumSet.noneOf(InputFlag.class);
+ for (InputFlag flag : InputFlag.values()) {
+ if (getInputFlag(flag)) {
+ flags.add(flag);
+ }
+ }
+ return flags;
+ }
+
+ public void setInputFlags(EnumSet<InputFlag> flags) {
+ int v = 0;
+ for (InputFlag f : flags) {
+ v |= f.value;
+ }
+ c_iflag = v;
+ }
+
+ public boolean getInputFlag(InputFlag flag) {
+ return (c_iflag & flag.value) == flag.value;
+ }
+
+ public void setInputFlags(EnumSet<InputFlag> flags, boolean value) {
+ int v = 0;
+ for (InputFlag f : flags) {
+ v |= f.value;
+ }
+ if (value) {
+ c_iflag |= v;
+ } else {
+ c_iflag &= ~v;
+ }
+ }
+
+ public void setInputFlag(InputFlag flag, boolean value) {
+ if (value) {
+ c_iflag |= flag.value;
+ } else {
+ c_iflag &= ~flag.value;
+ }
+ }
+
+ //
+ // Output flags
+ //
+
+ public EnumSet<OutputFlag> getOutputFlags() {
+ EnumSet<OutputFlag> flags = EnumSet.noneOf(OutputFlag.class);
+ for (OutputFlag flag : OutputFlag.values()) {
+ if (getOutputFlag(flag)) {
+ flags.add(flag);
+ }
+ }
+ return flags;
+ }
+
+ public void setOutputFlags(EnumSet<OutputFlag> flags) {
+ int v = 0;
+ for (OutputFlag f : flags) {
+ v |= f.value;
+ }
+ c_oflag = v;
+ }
+
+ public boolean getOutputFlag(OutputFlag flag) {
+ return (c_oflag & flag.value) == flag.value;
+ }
+
+ public void setOutputFlags(EnumSet<OutputFlag> flags, boolean value) {
+ int v = 0;
+ for (OutputFlag f : flags) {
+ v |= f.value;
+ }
+ if (value) {
+ c_oflag |= v;
+ } else {
+ c_oflag &= ~v;
+ }
+ }
+
+ public void setOutputFlag(OutputFlag flag, boolean value) {
+ if (value) {
+ c_oflag |= flag.value;
+ } else {
+ c_oflag &= ~flag.value;
+ }
+ }
+
+ //
+ // Control flags
+ //
+
+ public EnumSet<ControlFlag> getControlFlags() {
+ EnumSet<ControlFlag> flags = EnumSet.noneOf(ControlFlag.class);
+ for (ControlFlag flag : ControlFlag.values()) {
+ if (getControlFlag(flag)) {
+ flags.add(flag);
+ }
+ }
+ return flags;
+ }
+
+ public void setControlFlags(EnumSet<ControlFlag> flags) {
+ int v = 0;
+ for (ControlFlag f : flags) {
+ v |= f.value;
+ }
+ c_cflag = v;
+ }
+
+ public boolean getControlFlag(ControlFlag flag) {
+ switch (flag) {
+ case CS5:
+ case CS6:
+ case CS7:
+ case CS8:
+ return (c_cflag & ControlFlag.CSIZE.value) == flag.value;
+ case CSIZE:
+ return false;
+ default:
+ return (c_cflag & flag.value) == flag.value;
+ }
+ }
+
+ public void setControlFlags(EnumSet<ControlFlag> flags, boolean value) {
+ int v = 0;
+ for (ControlFlag f : flags) {
+ v |= f.value;
+ }
+ if (value) {
+ c_cflag |= v;
+ } else {
+ c_cflag &= ~v;
+ }
+ }
+
+ public void setControlFlag(ControlFlag flag, boolean value) {
+ if (value) {
+ c_cflag |= flag.value;
+ } else {
+ c_cflag &= ~flag.value;
+ }
+ }
+
+ //
+ // Local flags
+ //
+
+ public EnumSet<LocalFlag> getLocalFlags() {
+ EnumSet<LocalFlag> flags = EnumSet.noneOf(LocalFlag.class);
+ for (LocalFlag flag : LocalFlag.values()) {
+ if (getLocalFlag(flag)) {
+ flags.add(flag);
+ }
+ }
+ return flags;
+ }
+
+ public void setLocalFlags(EnumSet<LocalFlag> flags) {
+ int v = 0;
+ for (LocalFlag f : flags) {
+ v |= f.value;
+ }
+ c_lflag = v;
+ }
+
+ public boolean getLocalFlag(LocalFlag flag) {
+ return (c_lflag & flag.value) == flag.value;
+ }
+
+ public void setLocalFlags(EnumSet<LocalFlag> flags, boolean value) {
+ int v = 0;
+ for (LocalFlag f : flags) {
+ v |= f.value;
+ }
+ if (value) {
+ c_lflag |= v;
+ } else {
+ c_lflag &= ~v;
+ }
+ }
+
+ public void setLocalFlag(LocalFlag flag, boolean value) {
+ if (value) {
+ c_lflag |= flag.value;
+ } else {
+ c_lflag &= ~flag.value;
+ }
+ }
+
+ //
+ // Control chars
+ //
+
+ public int getControlChar(ControlChar c) {
+ return c_cc[c.value] & 0xff;
+ }
+
+ public void setControlChar(ControlChar c, int value) {
+ c_cc[c.value] = (byte) value;
+ }
+
+ //
+ // Miscellaneous methods
+ //
+
+ public void copy(Attributes attributes) {
+ System.arraycopy(attributes.c_cc, 0, c_cc, 0, c_cc.length);
+ c_cflag = attributes.c_cflag;
+ c_iflag = attributes.c_iflag;
+ c_lflag = attributes.c_lflag;
+ c_oflag = attributes.c_oflag;
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/api/Console.java b/src/main/java/org/jboss/aesh/terminal/api/Console.java
new file mode 100644
index 000000000..fc263be31
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/api/Console.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.api;
+
+import java.io.Closeable;
+import java.io.Flushable;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.io.Reader;
+
+import org.jboss.aesh.terminal.impl.NativeSignalHandler;
+import org.jboss.aesh.terminal.utils.InfoCmp.Capability;
+
+
+public interface Console extends Closeable, Flushable {
+
+ String getName();
+
+ //
+ // Signal support
+ //
+
+ enum Signal {
+ INT,
+ QUIT,
+ TSTP,
+ CONT,
+ INFO,
+ WINCH
+ }
+
+ interface SignalHandler {
+
+ SignalHandler SIG_DFL = NativeSignalHandler.SIG_DFL;
+ SignalHandler SIG_IGN = NativeSignalHandler.SIG_IGN;
+
+ void handle(Signal signal);
+ }
+
+ SignalHandler handle(Signal signal, SignalHandler handler);
+
+ void raise(Signal signal);
+
+ //
+ // Input / output
+ //
+
+ Reader reader();
+
+ PrintWriter writer();
+
+ InputStream input();
+
+ OutputStream output();
+
+ //
+ // Pty settings
+ //
+
+ Attributes enterRawMode();
+
+ boolean echo();
+
+ boolean echo(boolean echo);
+
+ Attributes getAttributes();
+
+ void setAttributes(Attributes attr);
+
+ Size getSize();
+
+ void setSize(Size size);
+
+ default int getWidth() {
+ return getSize().getWidth();
+ }
+
+ default int getHeight() {
+ return getSize().getHeight();
+ }
+
+ void flush();
+
+ //
+ // Infocmp capabilities
+ //
+
+ String getType();
+
+ boolean puts(Capability capability, Object... params);
+
+ boolean getBooleanCapability(Capability capability);
+
+ Integer getNumericCapability(Capability capability);
+
+ String getStringCapability(Capability capability);
+
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/api/ConsoleBuilder.java b/src/main/java/org/jboss/aesh/terminal/api/ConsoleBuilder.java
new file mode 100644
index 000000000..69fb0b0c4
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/api/ConsoleBuilder.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.api;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+
+import org.jboss.aesh.terminal.impl.CygwinPty;
+import org.jboss.aesh.terminal.impl.ExecPty;
+import org.jboss.aesh.terminal.impl.ExternalConsole;
+import org.jboss.aesh.terminal.impl.PosixSysConsole;
+import org.jboss.aesh.terminal.impl.Pty;
+import org.jboss.aesh.terminal.impl.WinSysConsole;
+import org.jboss.aesh.terminal.utils.OSUtils;
+
+public final class ConsoleBuilder {
+
+ public static Console console() throws IOException {
+ return builder().build();
+ }
+
+ public static ConsoleBuilder builder() {
+ return new ConsoleBuilder();
+ }
+
+ private String name;
+ private InputStream in;
+ private OutputStream out;
+ private String type;
+ private String encoding;
+ private Boolean system;
+ private boolean nativeSignals = true;
+
+ private ConsoleBuilder() {
+ }
+
+ public ConsoleBuilder name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public ConsoleBuilder streams(InputStream in, OutputStream out) {
+ this.in = in;
+ this.out = out;
+ return this;
+ }
+
+ public ConsoleBuilder system(boolean system) {
+ this.system = system;
+ return this;
+ }
+
+ public ConsoleBuilder type(String type) {
+ this.type = type;
+ return this;
+ }
+
+ public ConsoleBuilder encoding(String encoding) {
+ this.encoding = encoding;
+ return this;
+ }
+
+ public Console build() throws IOException {
+ String name = this.name;
+ if (name == null) {
+ name = "JLine console";
+ }
+ if ((system != null && system)
+ || (system == null
+ && (in == null || in == System.in)
+ && (out == null || out == System.out))) {
+ //
+ // Cygwin support
+ //
+ if (OSUtils.IS_CYGWIN) {
+ String type = this.type;
+ if (type == null) {
+ type = System.getenv("TERM");
+ }
+ String encoding = this.encoding;
+ if (encoding == null) {
+ encoding = Charset.defaultCharset().name();
+ }
+ Pty pty = CygwinPty.current();
+ return new PosixSysConsole(name, type, pty, encoding, nativeSignals);
+ }
+ else if (OSUtils.IS_WINDOWS) {
+ return new WinSysConsole(name, nativeSignals);
+ } else {
+ String type = this.type;
+ if (type == null) {
+ type = System.getenv("TERM");
+ }
+ String encoding = this.encoding;
+ if (encoding == null) {
+ encoding = Charset.defaultCharset().name();
+ }
+ Pty pty = ExecPty.current();
+ return new PosixSysConsole(name, type, pty, encoding, nativeSignals);
+ }
+ } else {
+ return new ExternalConsole(name, type, in, out, encoding);
+ }
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/api/Size.java b/src/main/java/org/jboss/aesh/terminal/api/Size.java
new file mode 100644
index 000000000..7d03395a6
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/api/Size.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.api;
+
+public class Size {
+
+ private int height;
+ private int width;
+
+ public Size() {
+ }
+
+ public Size(int height, int width) {
+ this.height = height;
+ this.width = width;
+ }
+
+ public int getWidth() {
+ return width;
+ }
+
+ public void setWidth(int width) {
+ this.width = (short) width;
+ }
+
+ public int getHeight() {
+ return height;
+ }
+
+ public void setHeight(int height) {
+ this.height = (short) height;
+ }
+
+ public void copy(Size size) {
+ setWidth(size.getWidth());
+ setHeight(size.getHeight());
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ Size size = (Size) o;
+
+ if (height != size.height) return false;
+ return width == size.width;
+
+ }
+
+ @Override
+ public int hashCode() {
+ int result = height;
+ result = 31 * result + width;
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "Size[" +
+ "cols=" + width +
+ ", rows=" + height +
+ ']';
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/AbstractConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/AbstractConsole.java
new file mode 100644
index 000000000..578e665ff
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/AbstractConsole.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+import java.io.IOError;
+import java.io.IOException;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.jboss.aesh.terminal.api.Attributes;
+import org.jboss.aesh.terminal.api.Attributes.ControlChar;
+import org.jboss.aesh.terminal.api.Attributes.InputFlag;
+import org.jboss.aesh.terminal.api.Attributes.LocalFlag;
+import org.jboss.aesh.terminal.api.Console;
+import org.jboss.aesh.terminal.utils.Curses;
+import org.jboss.aesh.terminal.utils.InfoCmp;
+import org.jboss.aesh.terminal.utils.InfoCmp.Capability;
+import org.jboss.aesh.util.LoggerUtil;
+
+public abstract class AbstractConsole implements Console {
+
+ protected final Logger LOGGER = LoggerUtil.getLogger(getClass().getName());
+
+ protected final String name;
+ protected final String type;
+ protected final Map<Signal, SignalHandler> handlers = new HashMap<>();
+ protected final Set<Capability> bools = new HashSet<>();
+ protected final Map<Capability, Integer> ints = new HashMap<>();
+ protected final Map<Capability, String> strings = new HashMap<>();
+
+ public AbstractConsole(String name, String type) throws IOException {
+ this.name = name;
+ this.type = type;
+ for (Signal signal : Signal.values()) {
+ handlers.put(signal, SignalHandler.SIG_DFL);
+ }
+ }
+
+ public SignalHandler handle(Signal signal, SignalHandler handler) {
+ assert signal != null;
+ assert handler != null;
+ return handlers.put(signal, handler);
+ }
+
+ public void raise(Signal signal) {
+ assert signal != null;
+ SignalHandler handler = handlers.get(signal);
+ if (handler == SignalHandler.SIG_DFL) {
+ handleDefaultSignal(signal);
+ } else if (handler != SignalHandler.SIG_IGN) {
+ handler.handle(signal);
+ }
+ }
+
+ protected void handleDefaultSignal(Signal signal) {
+ }
+
+ protected void echoSignal(Signal signal) {
+ ControlChar cc = null;
+ switch (signal) {
+ case INT:
+ cc = ControlChar.VINTR;
+ break;
+ case QUIT:
+ cc = ControlChar.VQUIT;
+ break;
+ case TSTP:
+ cc = ControlChar.VSUSP;
+ break;
+ }
+ if (cc != null) {
+ int vcc = getAttributes().getControlChar(cc);
+ if (vcc > 0 && vcc < 32) {
+ writer().write(new char[]{'^', (char) (vcc + '@')}, 0, 2);
+ }
+ }
+ }
+
+ public Attributes enterRawMode() {
+ Attributes prvAttr = getAttributes();
+ Attributes newAttr = new Attributes(prvAttr);
+ newAttr.setLocalFlags(EnumSet.of(LocalFlag.ICANON, LocalFlag.ECHO, LocalFlag.IEXTEN), false);
+ newAttr.setInputFlags(EnumSet.of(InputFlag.IXON, InputFlag.ICRNL, InputFlag.INLCR), false);
+ newAttr.setControlChar(ControlChar.VMIN, 1);
+ newAttr.setControlChar(ControlChar.VTIME, 0);
+ setAttributes(newAttr);
+ return prvAttr;
+ }
+
+ public boolean echo() {
+ return getAttributes().getLocalFlag(LocalFlag.ECHO);
+ }
+
+ public boolean echo(boolean echo) {
+ Attributes attr = getAttributes();
+ boolean prev = attr.getLocalFlag(LocalFlag.ECHO);
+ if (prev != echo) {
+ attr.setLocalFlag(LocalFlag.ECHO, echo);
+ setAttributes(attr);
+ }
+ return prev;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void flush() {
+ writer().flush();
+ }
+
+ public boolean puts(Capability capability, Object... params) {
+ String str = getStringCapability(capability);
+ if (str == null) {
+ return false;
+ }
+ try {
+ Curses.tputs(writer(), str, params);
+ } catch (IOException e) {
+ throw new IOError(e);
+ }
+ return true;
+ }
+
+ public boolean getBooleanCapability(Capability capability) {
+ return bools.contains(capability);
+ }
+
+ public Integer getNumericCapability(Capability capability) {
+ return ints.get(capability);
+ }
+
+ public String getStringCapability(Capability capability) {
+ return strings.get(capability);
+ }
+
+ protected void parseInfoCmp() {
+ String capabilities = null;
+ if (type != null) {
+ try {
+ capabilities = InfoCmp.getInfoCmp(type);
+ } catch (Exception e) {
+ LOGGER.log(Level.WARNING, "Unable to retrieve infocmp for type " + type, e);
+ }
+ }
+ if (capabilities == null) {
+ capabilities = InfoCmp.ANSI_CAPS;
+ }
+ InfoCmp.parseInfoCmp(capabilities, bools, ints, strings);
+ }
+
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/AbstractPosixConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/AbstractPosixConsole.java
new file mode 100644
index 000000000..9f1447e44
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/AbstractPosixConsole.java
@@ -0,0 +1,61 @@
+package org.jboss.aesh.terminal.impl;
+
+import java.io.IOError;
+import java.io.IOException;
+
+import org.jboss.aesh.terminal.api.Attributes;
+import org.jboss.aesh.terminal.api.Size;
+
+public abstract class AbstractPosixConsole extends AbstractConsole {
+
+ protected final Pty pty;
+ protected final Attributes originalAttributes;
+
+ public AbstractPosixConsole(String name, String type, Pty pty) throws IOException {
+ super(name, type);
+ assert pty != null;
+ this.pty = pty;
+ this.originalAttributes = this.pty.getAttr();
+ }
+
+ protected Pty getPty() {
+ return pty;
+ }
+
+ public Attributes getAttributes() {
+ try {
+ return pty.getAttr();
+ } catch (IOException e) {
+ throw new IOError(e);
+ }
+ }
+
+ public void setAttributes(Attributes attr) {
+ try {
+ pty.setAttr(attr);
+ } catch (IOException e) {
+ throw new IOError(e);
+ }
+ }
+
+ public Size getSize() {
+ try {
+ return pty.getSize();
+ } catch (IOException e) {
+ throw new IOError(e);
+ }
+ }
+
+ public void setSize(Size size) {
+ try {
+ pty.setSize(size);
+ } catch (IOException e) {
+ throw new IOError(e);
+ }
+ }
+
+ public void close() throws IOException {
+ pty.setAttr(originalAttributes);
+ pty.close();
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/CygwinPty.java b/src/main/java/org/jboss/aesh/terminal/impl/CygwinPty.java
new file mode 100644
index 000000000..8590142fe
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/CygwinPty.java
@@ -0,0 +1,288 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.io.OutputStream;
+import java.lang.ProcessBuilder.Redirect;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.jboss.aesh.terminal.api.Attributes;
+import org.jboss.aesh.terminal.api.Attributes.ControlChar;
+import org.jboss.aesh.terminal.api.Attributes.ControlFlag;
+import org.jboss.aesh.terminal.api.Attributes.InputFlag;
+import org.jboss.aesh.terminal.api.Attributes.LocalFlag;
+import org.jboss.aesh.terminal.api.Attributes.OutputFlag;
+import org.jboss.aesh.terminal.api.Size;
+import org.jboss.aesh.terminal.utils.ExecHelper;
+import org.jboss.aesh.terminal.utils.OSUtils;
+import org.jboss.aesh.util.LoggerUtil;
+
+
+public class CygwinPty implements Pty {
+
+ private static final Logger LOGGER = LoggerUtil.getLogger(CygwinPty.class.getName());
+
+ private final String name;
+
+ public static Pty current() throws IOException {
+ try {
+ Process p = new ProcessBuilder(OSUtils.TTY_COMMAND)
+ .redirectInput(Redirect.INHERIT)
+ .start();
+ String result = ExecHelper.waitAndCapture(p).trim();
+ if (p.exitValue() != 0) {
+ throw new IOException("Not a tty");
+ }
+ return new CygwinPty(result);
+ } catch (InterruptedException e) {
+ throw (IOException) new InterruptedIOException("Command interrupted").initCause(e);
+ }
+ }
+
+ protected CygwinPty(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public void close() throws IOException {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public InputStream getMasterInput() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public OutputStream getMasterOutput() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public InputStream getSlaveInput() throws IOException {
+ return new FileInputStream(FileDescriptor.in);
+ }
+
+ @Override
+ public OutputStream getSlaveOutput() throws IOException {
+ return new FileOutputStream(FileDescriptor.out);
+ }
+
+ @Override
+ public Attributes getAttr() throws IOException {
+ String cfg = doGetConfig();
+ return doGetAttr(cfg);
+ }
+
+ @Override
+ public void setAttr(Attributes attr) throws IOException {
+ Attributes current = getAttr();
+ List<String> commands = new ArrayList<>();
+ for (InputFlag flag : InputFlag.values()) {
+ if (attr.getInputFlag(flag) != current.getInputFlag(flag)) {
+ commands.add((attr.getInputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase());
+ }
+ }
+ for (OutputFlag flag : OutputFlag.values()) {
+ if (attr.getOutputFlag(flag) != current.getOutputFlag(flag)) {
+ commands.add((attr.getOutputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase());
+ }
+ }
+ for (ControlFlag flag : ControlFlag.values()) {
+ if (attr.getControlFlag(flag) != current.getControlFlag(flag)) {
+ commands.add((attr.getControlFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase());
+ }
+ }
+ for (LocalFlag flag : LocalFlag.values()) {
+ if (attr.getLocalFlag(flag) != current.getLocalFlag(flag)) {
+ commands.add((attr.getLocalFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase());
+ }
+ }
+ String undef = System.getProperty("os.name").toLowerCase().startsWith("hp") ? "^-" : "undef";
+ for (ControlChar cchar : ControlChar.values()) {
+ if (attr.getControlChar(cchar) != current.getControlChar(cchar)) {
+ String str = "";
+ int v = attr.getControlChar(cchar);
+ commands.add(cchar.name().toLowerCase().substring(1));
+ if (cchar == ControlChar.VMIN || cchar == ControlChar.VTIME) {
+ commands.add(Integer.toBinaryString(v));
+ }
+ else if (v == 0) {
+ commands.add(undef);
+ }
+ else {
+ if (v >= 128) {
+ v -= 128;
+ str += "M-";
+ }
+ if (v < 32 || v == 127) {
+ v ^= 0x40;
+ str += "^";
+ }
+ str += (char) v;
+ commands.add(str);
+ }
+ }
+ }
+ if (!commands.isEmpty()) {
+ commands.add(0, OSUtils.STTY_COMMAND);
+ exec(commands.toArray(new String[commands.size()]));
+ }
+ }
+
+ @Override
+ public Size getSize() throws IOException {
+ String cfg = doGetConfig();
+ return doGetSize(cfg);
+ }
+
+ protected String doGetConfig() throws IOException {
+ return exec(OSUtils.STTY_COMMAND, "-a");
+ }
+
+ static Attributes doGetAttr(String cfg) throws IOException {
+ Attributes attributes = new Attributes();
+ for (InputFlag flag : InputFlag.values()) {
+ Boolean value = doGetFlag(cfg, flag);
+ if (value != null) {
+ attributes.setInputFlag(flag, value);
+ }
+ }
+ for (OutputFlag flag : OutputFlag.values()) {
+ Boolean value = doGetFlag(cfg, flag);
+ if (value != null) {
+ attributes.setOutputFlag(flag, value);
+ }
+ }
+ for (ControlFlag flag : ControlFlag.values()) {
+ Boolean value = doGetFlag(cfg, flag);
+ if (value != null) {
+ attributes.setControlFlag(flag, value);
+ }
+ }
+ for (LocalFlag flag : LocalFlag.values()) {
+ Boolean value = doGetFlag(cfg, flag);
+ if (value != null) {
+ attributes.setLocalFlag(flag, value);
+ }
+ }
+ for (ControlChar cchar : ControlChar.values()) {
+ String name = cchar.name().toLowerCase().substring(1);
+ if ("reprint".endsWith(name)) {
+ name = "(?:reprint|rprnt)";
+ }
+ Matcher matcher = Pattern.compile("[\\s;]" + name + "\\s*=\\s*(.+?)[\\s;]").matcher(cfg);
+ if (matcher.find()) {
+ attributes.setControlChar(cchar, parseControlChar(matcher.group(1).toUpperCase()));
+ }
+ }
+ return attributes;
+ }
+
+ private static Boolean doGetFlag(String cfg, Enum<?> flag) {
+ Matcher matcher = Pattern.compile("(?:^|[\\s;])(\\-?" + flag.name().toLowerCase() + ")(?:[\\s;]|$)").matcher(cfg);
+ return matcher.find() ? !matcher.group(1).startsWith("-") : null;
+ }
+
+ static int parseControlChar(String str) {
+ // undef
+ if ("<UNDEF>".equals(str)) {
+ return -1;
+ }
+ // del
+ if ("DEL".equalsIgnoreCase(str)) {
+ return 127;
+ }
+ // octal
+ if (str.charAt(0) == '0') {
+ return Integer.parseInt(str, 8);
+ }
+ // decimal
+ if (str.charAt(0) >= '1' && str.charAt(0) <= '9') {
+ return Integer.parseInt(str, 10);
+ }
+ // control char
+ if (str.charAt(0) == '^') {
+ if (str.charAt(1) == '?') {
+ return 127;
+ } else {
+ return str.charAt(1) - 64;
+ }
+ } else if (str.charAt(0) == 'M' && str.charAt(1) == '-') {
+ if (str.charAt(2) == '^') {
+ if (str.charAt(3) == '?') {
+ return 127 + 128;
+ } else {
+ return str.charAt(3) - 64 + 128;
+ }
+ } else {
+ return str.charAt(2) + 128;
+ }
+ } else {
+ return str.charAt(0);
+ }
+ }
+
+ static Size doGetSize(String cfg) throws IOException {
+ return new Size(doGetInt("rows", cfg), doGetInt("columns", cfg));
+ }
+
+ static int doGetInt(String name, String cfg) throws IOException {
+ String[] patterns = new String[] {
+ "\\b([0-9]+)\\s+" + name + "\\b",
+ "\\b" + name + "\\s+([0-9]+)\\b",
+ "\\b" + name + "\\s*=\\s*([0-9]+)\\b"
+ };
+ for (String pattern : patterns) {
+ Matcher matcher = Pattern.compile(pattern).matcher(cfg);
+ if (matcher.find()) {
+ return Integer.parseInt(matcher.group(1));
+ }
+ }
+ throw new IOException("Unable to parse " + name);
+ }
+
+ @Override
+ public void setSize(Size size) throws IOException {
+ exec(OSUtils.STTY_COMMAND,
+ "rows", Integer.toString(size.getHeight()),
+ "columns", Integer.toString(size.getWidth()));
+ }
+
+ private static String exec(final String... cmd) throws IOException {
+ assert cmd != null;
+ try {
+ LOGGER.log(Level.FINEST, "Running: ", cmd);
+ Process p = new ProcessBuilder(cmd).redirectInput(Redirect.INHERIT).start();
+ String result = ExecHelper.waitAndCapture(p);
+ LOGGER.log(Level.FINEST, "Result: ", result);
+ if (p.exitValue() != 0) {
+ throw new IOException("Error executing '" + String.join(" ", cmd) + "': " + result);
+ }
+ return result;
+ } catch (InterruptedException e) {
+ throw (IOException) new InterruptedIOException("Command interrupted").initCause(e);
+ }
+ }
+
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/ExecPty.java b/src/main/java/org/jboss/aesh/terminal/impl/ExecPty.java
new file mode 100644
index 000000000..0f44f41e9
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/ExecPty.java
@@ -0,0 +1,290 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.io.OutputStream;
+import java.lang.ProcessBuilder.Redirect;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.jboss.aesh.terminal.api.Attributes;
+import org.jboss.aesh.terminal.api.Attributes.ControlChar;
+import org.jboss.aesh.terminal.api.Attributes.ControlFlag;
+import org.jboss.aesh.terminal.api.Attributes.InputFlag;
+import org.jboss.aesh.terminal.api.Attributes.LocalFlag;
+import org.jboss.aesh.terminal.api.Attributes.OutputFlag;
+import org.jboss.aesh.terminal.api.Size;
+import org.jboss.aesh.terminal.utils.ExecHelper;
+import org.jboss.aesh.terminal.utils.OSUtils;
+import org.jboss.aesh.util.LoggerUtil;
+
+
+public class ExecPty implements Pty {
+
+ private static final Logger LOGGER = LoggerUtil.getLogger(CygwinPty.class.getName());
+
+ private final String name;
+
+ public static Pty current() throws IOException {
+ try {
+ Process p = new ProcessBuilder(OSUtils.TTY_COMMAND)
+ .redirectInput(Redirect.INHERIT)
+ .start();
+ String result = ExecHelper.waitAndCapture(p).trim();
+ if (p.exitValue() != 0) {
+ throw new IOException("Not a tty");
+ }
+ return new ExecPty(result);
+ } catch (InterruptedException e) {
+ throw (IOException) new InterruptedIOException("Command interrupted").initCause(e);
+ }
+ }
+
+ protected ExecPty(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public void close() throws IOException {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public InputStream getMasterInput() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public OutputStream getMasterOutput() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public InputStream getSlaveInput() throws IOException {
+ return new FileInputStream(getName());
+ }
+
+ @Override
+ public OutputStream getSlaveOutput() throws IOException {
+ return new FileOutputStream(getName());
+ }
+
+ @Override
+ public Attributes getAttr() throws IOException {
+ String cfg = doGetConfig();
+ return doGetAttr(cfg);
+ }
+
+ @Override
+ public void setAttr(Attributes attr) throws IOException {
+ Attributes current = getAttr();
+ List<String> commands = new ArrayList<>();
+ for (InputFlag flag : InputFlag.values()) {
+ if (attr.getInputFlag(flag) != current.getInputFlag(flag)) {
+ commands.add((attr.getInputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase());
+ }
+ }
+ for (OutputFlag flag : OutputFlag.values()) {
+ if (attr.getOutputFlag(flag) != current.getOutputFlag(flag)) {
+ commands.add((attr.getOutputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase());
+ }
+ }
+ for (ControlFlag flag : ControlFlag.values()) {
+ if (attr.getControlFlag(flag) != current.getControlFlag(flag)) {
+ commands.add((attr.getControlFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase());
+ }
+ }
+ for (LocalFlag flag : LocalFlag.values()) {
+ if (attr.getLocalFlag(flag) != current.getLocalFlag(flag)) {
+ commands.add((attr.getLocalFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase());
+ }
+ }
+ String undef = System.getProperty("os.name").toLowerCase().startsWith("hp") ? "^-" : "undef";
+ for (ControlChar cchar : ControlChar.values()) {
+ if (attr.getControlChar(cchar) != current.getControlChar(cchar)) {
+ String str = "";
+ int v = attr.getControlChar(cchar);
+ commands.add(cchar.name().toLowerCase().substring(1));
+ if (cchar == ControlChar.VMIN || cchar == ControlChar.VTIME) {
+ commands.add(Integer.toBinaryString(v));
+ }
+ else if (v == 0) {
+ commands.add(undef);
+ }
+ else {
+ if (v >= 128) {
+ v -= 128;
+ str += "M-";
+ }
+ if (v < 32 || v == 127) {
+ v ^= 0x40;
+ str += "^";
+ }
+ str += (char) v;
+ commands.add(str);
+ }
+ }
+ }
+ if (!commands.isEmpty()) {
+ commands.add(0, OSUtils.STTY_COMMAND);
+ commands.add(1, "-f");
+ commands.add(2, getName());
+ exec(commands.toArray(new String[commands.size()]));
+ }
+ }
+
+ @Override
+ public Size getSize() throws IOException {
+ String cfg = doGetConfig();
+ return doGetSize(cfg);
+ }
+
+ protected String doGetConfig() throws IOException {
+ return exec(OSUtils.STTY_COMMAND, "-f", getName(), "-a");
+ }
+
+ static Attributes doGetAttr(String cfg) throws IOException {
+ Attributes attributes = new Attributes();
+ for (InputFlag flag : InputFlag.values()) {
+ Boolean value = doGetFlag(cfg, flag);
+ if (value != null) {
+ attributes.setInputFlag(flag, value);
+ }
+ }
+ for (OutputFlag flag : OutputFlag.values()) {
+ Boolean value = doGetFlag(cfg, flag);
+ if (value != null) {
+ attributes.setOutputFlag(flag, value);
+ }
+ }
+ for (ControlFlag flag : ControlFlag.values()) {
+ Boolean value = doGetFlag(cfg, flag);
+ if (value != null) {
+ attributes.setControlFlag(flag, value);
+ }
+ }
+ for (LocalFlag flag : LocalFlag.values()) {
+ Boolean value = doGetFlag(cfg, flag);
+ if (value != null) {
+ attributes.setLocalFlag(flag, value);
+ }
+ }
+ for (ControlChar cchar : ControlChar.values()) {
+ String name = cchar.name().toLowerCase().substring(1);
+ if ("reprint".endsWith(name)) {
+ name = "(?:reprint|rprnt)";
+ }
+ Matcher matcher = Pattern.compile("[\\s;]" + name + "\\s*=\\s*(.+?)[\\s;]").matcher(cfg);
+ if (matcher.find()) {
+ attributes.setControlChar(cchar, parseControlChar(matcher.group(1).toUpperCase()));
+ }
+ }
+ return attributes;
+ }
+
+ private static Boolean doGetFlag(String cfg, Enum<?> flag) {
+ Matcher matcher = Pattern.compile("(?:^|[\\s;])(\\-?" + flag.name().toLowerCase() + ")(?:[\\s;]|$)").matcher(cfg);
+ return matcher.find() ? !matcher.group(1).startsWith("-") : null;
+ }
+
+ static int parseControlChar(String str) {
+ // undef
+ if ("<UNDEF>".equals(str)) {
+ return -1;
+ }
+ // del
+ if ("DEL".equalsIgnoreCase(str)) {
+ return 127;
+ }
+ // octal
+ if (str.charAt(0) == '0') {
+ return Integer.parseInt(str, 8);
+ }
+ // decimal
+ if (str.charAt(0) >= '1' && str.charAt(0) <= '9') {
+ return Integer.parseInt(str, 10);
+ }
+ // control char
+ if (str.charAt(0) == '^') {
+ if (str.charAt(1) == '?') {
+ return 127;
+ } else {
+ return str.charAt(1) - 64;
+ }
+ } else if (str.charAt(0) == 'M' && str.charAt(1) == '-') {
+ if (str.charAt(2) == '^') {
+ if (str.charAt(3) == '?') {
+ return 127 + 128;
+ } else {
+ return str.charAt(3) - 64 + 128;
+ }
+ } else {
+ return str.charAt(2) + 128;
+ }
+ } else {
+ return str.charAt(0);
+ }
+ }
+
+ static Size doGetSize(String cfg) throws IOException {
+ return new Size(doGetInt("rows", cfg), doGetInt("columns", cfg));
+ }
+
+ static int doGetInt(String name, String cfg) throws IOException {
+ String[] patterns = new String[] {
+ "\\b([0-9]+)\\s+" + name + "\\b",
+ "\\b" + name + "\\s+([0-9]+)\\b",
+ "\\b" + name + "\\s*=\\s*([0-9]+)\\b"
+ };
+ for (String pattern : patterns) {
+ Matcher matcher = Pattern.compile(pattern).matcher(cfg);
+ if (matcher.find()) {
+ return Integer.parseInt(matcher.group(1));
+ }
+ }
+ throw new IOException("Unable to parse " + name);
+ }
+
+ @Override
+ public void setSize(Size size) throws IOException {
+ exec(OSUtils.STTY_COMMAND,
+ "-f", getName(),
+ "rows", Integer.toString(size.getHeight()),
+ "columns", Integer.toString(size.getWidth()));
+ }
+
+ private static String exec(final String... cmd) throws IOException {
+ assert cmd != null;
+ try {
+ LOGGER.log(Level.FINEST, "Running: ", cmd);
+ Process p = new ProcessBuilder(cmd).start();
+ String result = ExecHelper.waitAndCapture(p);
+ LOGGER.log(Level.FINEST, "Result: ", result);
+ if (p.exitValue() != 0) {
+ throw new IOException("Error executing '" + String.join(" ", cmd) + "': " + result);
+ }
+ return result;
+ } catch (InterruptedException e) {
+ throw (IOException) new InterruptedIOException("Command interrupted").initCause(e);
+ }
+ }
+
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/ExternalConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/ExternalConsole.java
new file mode 100644
index 000000000..c07a89b02
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/ExternalConsole.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Console implementation with embedded line disciplined.
+ *
+ * This console is well-suited for supporting incoming external
+ * connections, such as from the network (through telnet, ssh,
+ * or any kind of protocol).
+ * The console will start consuming the input in a separate thread
+ * to generate interruption events.
+ *
+ * @see LineDisciplineConsole
+ */
+public class ExternalConsole extends LineDisciplineConsole {
+
+ private final AtomicBoolean closed = new AtomicBoolean();
+ private final Thread pumpThread;
+ protected final InputStream masterInput;
+
+ public ExternalConsole(String name, String type,
+ InputStream masterInput, OutputStream masterOutput,
+ String encoding) throws IOException {
+ super(name, type, masterOutput, encoding);
+ this.masterInput = masterInput;
+ this.pumpThread = new Thread(this::pump, toString() + " input pump thread");
+ this.pumpThread.start();
+ }
+
+ public void close() throws IOException {
+ if (closed.compareAndSet(false, true)) {
+ pumpThread.interrupt();
+ super.close();
+ }
+ }
+
+ public void pump() {
+ try {
+ while (true) {
+ int c = masterInput.read();
+ if (c < 0 || closed.get()) {
+ break;
+ }
+ processInputByte((char) c);
+ }
+ } catch (IOException e) {
+ try {
+ close();
+ } catch (Throwable t) {
+ e.addSuppressed(t);
+ }
+ // TODO: log
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/LineDisciplineConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/LineDisciplineConsole.java
new file mode 100644
index 000000000..77d55e561
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/LineDisciplineConsole.java
@@ -0,0 +1,257 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharsetDecoder;
+import java.util.function.IntConsumer;
+
+import org.jboss.aesh.terminal.api.Attributes;
+import org.jboss.aesh.terminal.api.Attributes.ControlChar;
+import org.jboss.aesh.terminal.api.Attributes.InputFlag;
+import org.jboss.aesh.terminal.api.Attributes.LocalFlag;
+import org.jboss.aesh.terminal.api.Attributes.OutputFlag;
+import org.jboss.aesh.terminal.api.Console;
+import org.jboss.aesh.terminal.api.Size;
+import org.jboss.aesh.terminal.utils.InputStreamReader;
+
+/**
+ * Abstract console with support for line discipline.
+ * The {@link Console} interface represents the slave
+ * side of a PTY, but implementations derived from this class
+ * will handle both the slave and master side of things.
+ *
+ * In order to correctly handle line discipline, the console
+ * needs to read the input in advance in order to raise the
+ * signals as fast as possible.
+ * For example, when the user hits Ctrl+C, we can't wait until
+ * the application consumes all the read events.
+ * The same applies to echoing, when enabled, as the echoing
+ * has to happen as soon as the user hit the keyboard, and not
+ * only when the application running in the terminal processes
+ * the input.
+ */
+public class LineDisciplineConsole extends AbstractConsole {
+
+ private static final int PIPE_SIZE = 1024;
+
+ /*
+ * Master output stream
+ */
+ protected final OutputStream masterOutput;
+
+ /*
+ * Slave input pipe write side
+ */
+ protected final OutputStream slaveInputPipe;
+
+ /*
+ * Slave streams
+ */
+ protected final InputStream slaveInput;
+ protected final Reader slaveReader;
+ protected final PrintWriter slaveWriter;
+ protected final OutputStream slaveOutput;
+
+ /**
+ * Console data
+ */
+ protected final String encoding;
+ protected final Attributes attributes;
+ protected final Size size;
+
+ /**
+ * Application
+ */
+ protected IntConsumer application;
+ protected CharsetDecoder decoder;
+ protected ByteBuffer bytes;
+ protected CharBuffer chars;
+
+ public LineDisciplineConsole(String name,
+ String type,
+ OutputStream masterOutput,
+ String encoding) throws IOException {
+ super(name, type);
+ PipedInputStream input = new PipedInputStream(PIPE_SIZE);
+ this.slaveInputPipe = new PipedOutputStream(input);
+ // This is a hack to fix a problem in gogo where closure closes
+ // streams for commands if they are instances of PipedInputStream.
+ // So we need to get around and make sure it's not an instance of
+ // that class by using a dumb FilterInputStream class to wrap it.
+ this.slaveInput = new FilterInputStream(input) {};
+ this.slaveReader = new InputStreamReader(slaveInput, encoding);
+ this.slaveOutput = new FilteringOutputStream();
+ this.slaveWriter = new PrintWriter(new OutputStreamWriter(slaveOutput, encoding));
+ this.masterOutput = masterOutput;
+ this.encoding = encoding;
+ this.attributes = new Attributes();
+ this.size = new Size(50, 160);
+ parseInfoCmp();
+ }
+
+ public Reader reader() {
+ return slaveReader;
+ }
+
+ public PrintWriter writer() {
+ return slaveWriter;
+ }
+
+ @Override
+ public InputStream input() {
+ return slaveInput;
+ }
+
+ @Override
+ public OutputStream output() {
+ return slaveOutput;
+ }
+
+ public Attributes getAttributes() {
+ Attributes attr = new Attributes();
+ attr.copy(attributes);
+ return attr;
+ }
+
+ public void setAttributes(Attributes attr) {
+ attributes.copy(attr);
+ }
+
+ public Size getSize() {
+ return new Size(size.getHeight(), size.getWidth());
+ }
+
+ public void setSize(Size sz) {
+ size.setHeight(sz.getHeight());
+ size.setWidth(sz.getWidth());
+ }
+
+ @Override
+ public void raise(Signal signal) {
+ assert signal != null;
+ // Do not call clear() atm as this can cause
+ // deadlock between reading / writing threads
+ // TODO: any way to fix that ?
+ /*
+ if (!attributes.getLocalFlag(LocalFlag.NOFLSH)) {
+ try {
+ slaveReader.clear();
+ } catch (IOException e) {
+ // Ignore
+ }
+ }
+ */
+ echoSignal(signal);
+ super.raise(signal);
+ }
+
+ /**
+ * Master input processing.
+ * All data coming to the console should be provided
+ * using this method.
+ *
+ * @param c the input byte
+ * @throws IOException
+ */
+ public void processInputByte(int c) throws IOException {
+ if (attributes.getLocalFlag(LocalFlag.ISIG)) {
+ if (c == attributes.getControlChar(ControlChar.VINTR)) {
+ raise(Signal.INT);
+ return;
+ } else if (c == attributes.getControlChar(ControlChar.VQUIT)) {
+ raise(Signal.QUIT);
+ return;
+ } else if (c == attributes.getControlChar(ControlChar.VSUSP)) {
+ raise(Signal.TSTP);
+ return;
+ } else if (c == attributes.getControlChar(ControlChar.VSTATUS)) {
+ raise(Signal.INFO);
+ }
+ }
+ if (c == '\r') {
+ if (attributes.getInputFlag(InputFlag.IGNCR)) {
+ return;
+ }
+ if (attributes.getInputFlag(InputFlag.ICRNL)) {
+ c = '\n';
+ }
+ } else if (c == '\n' && attributes.getInputFlag(InputFlag.INLCR)) {
+ c = '\r';
+ }
+ if (attributes.getLocalFlag(LocalFlag.ECHO)) {
+ processOutputByte(c);
+ masterOutput.flush();
+ }
+ slaveInputPipe.write(c);
+ slaveInputPipe.flush();
+ }
+
+ /**
+ * Master output processing.
+ * All data going to the master should be provided by this method.
+ *
+ * @param c the output byte
+ * @throws IOException
+ */
+ protected void processOutputByte(int c) throws IOException {
+ if (attributes.getOutputFlag(OutputFlag.OPOST)) {
+ if (c == '\n') {
+ if (attributes.getOutputFlag(OutputFlag.ONLCR)) {
+ masterOutput.write('\r');
+ masterOutput.write('\n');
+ return;
+ }
+ }
+ }
+ masterOutput.write(c);
+ }
+
+ public void close() throws IOException {
+ try {
+ slaveReader.close();
+ } finally {
+ try {
+ slaveInputPipe.close();
+ } finally {
+ try {
+ } finally {
+ slaveWriter.close();
+ }
+ }
+ }
+ }
+
+ private class FilteringOutputStream extends OutputStream {
+ @Override
+ public void write(int b) throws IOException {
+ processOutputByte(b);
+ }
+
+ @Override
+ public void flush() throws IOException {
+ masterOutput.flush();
+ }
+
+ @Override
+ public void close() throws IOException {
+ masterOutput.close();
+ }
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/NativeSignalHandler.java b/src/main/java/org/jboss/aesh/terminal/impl/NativeSignalHandler.java
new file mode 100644
index 000000000..603768210
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/NativeSignalHandler.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+
+import org.jboss.aesh.terminal.api.Console.Signal;
+import org.jboss.aesh.terminal.api.Console.SignalHandler;
+
+public final class NativeSignalHandler implements SignalHandler {
+
+ public static final NativeSignalHandler SIG_DFL = new NativeSignalHandler();
+
+ public static final NativeSignalHandler SIG_IGN = new NativeSignalHandler();
+
+ private NativeSignalHandler() {
+ }
+
+ public void handle(Signal signal) {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/PosixSysConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/PosixSysConsole.java
new file mode 100644
index 000000000..fc399f9c4
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/PosixSysConsole.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.jboss.aesh.terminal.utils.InputStreamReader;
+import org.jboss.aesh.terminal.utils.ShutdownHooks;
+import org.jboss.aesh.terminal.utils.ShutdownHooks.Task;
+import org.jboss.aesh.terminal.utils.Signals;
+
+public class PosixSysConsole extends AbstractPosixConsole {
+
+ protected final InputStream input;
+ protected final OutputStream output;
+ protected final Reader reader;
+ protected final PrintWriter writer;
+ protected final Map<Signal, Object> nativeHandlers = new HashMap<>();
+ protected final Task closer;
+
+ public PosixSysConsole(String name, String type, Pty pty, String encoding, boolean nativeSignals) throws IOException {
+ super(name, type, pty);
+ assert encoding != null;
+ this.input = pty.getSlaveInput();
+ this.output = pty.getSlaveOutput();
+ this.reader = new InputStreamReader(input, encoding);
+ this.writer = new PrintWriter(new OutputStreamWriter(output, encoding));
+ parseInfoCmp();
+ if (nativeSignals) {
+ for (final Signal signal : Signal.values()) {
+ nativeHandlers.put(signal, Signals.register(signal.name(), () -> raise(signal)));
+ }
+ }
+ closer = PosixSysConsole.this::close;
+ ShutdownHooks.add(closer);
+ }
+
+ public Reader reader() {
+ return reader;
+ }
+
+ public PrintWriter writer() {
+ return writer;
+ }
+
+ @Override
+ public InputStream input() {
+ return input;
+ }
+
+ @Override
+ public OutputStream output() {
+ return output;
+ }
+
+ @Override
+ public void close() throws IOException {
+ ShutdownHooks.remove(closer);
+ for (Map.Entry<Signal, Object> entry : nativeHandlers.entrySet()) {
+ Signals.unregister(entry.getKey().name(), entry.getValue());
+ }
+ super.close();
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/Pty.java b/src/main/java/org/jboss/aesh/terminal/impl/Pty.java
new file mode 100644
index 000000000..9ed0e04d1
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/Pty.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.jboss.aesh.terminal.api.Attributes;
+import org.jboss.aesh.terminal.api.Size;
+
+public interface Pty extends Closeable {
+
+ InputStream getMasterInput() throws IOException;
+
+ OutputStream getMasterOutput() throws IOException;
+
+ InputStream getSlaveInput() throws IOException;
+
+ OutputStream getSlaveOutput() throws IOException;
+
+ Attributes getAttr() throws IOException;
+
+ void setAttr(Attributes attr) throws IOException;
+
+ Size getSize() throws IOException;
+
+ void setSize(Size size) throws IOException;
+
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/impl/WinSysConsole.java b/src/main/java/org/jboss/aesh/terminal/impl/WinSysConsole.java
new file mode 100644
index 000000000..2a06e766c
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/impl/WinSysConsole.java
@@ -0,0 +1,328 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.impl;
+
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.IOError;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Level;
+
+import org.fusesource.jansi.WindowsAnsiOutputStream;
+import org.fusesource.jansi.internal.Kernel32;
+import org.fusesource.jansi.internal.Kernel32.INPUT_RECORD;
+import org.fusesource.jansi.internal.Kernel32.KEY_EVENT_RECORD;
+import org.fusesource.jansi.internal.WindowsSupport;
+import org.jboss.aesh.terminal.api.Attributes;
+import org.jboss.aesh.terminal.api.Attributes.LocalFlag;
+import org.jboss.aesh.terminal.api.Size;
+import org.jboss.aesh.terminal.utils.Curses;
+import org.jboss.aesh.terminal.utils.InfoCmp.Capability;
+import org.jboss.aesh.terminal.utils.InputStreamReader;
+import org.jboss.aesh.terminal.utils.ShutdownHooks;
+import org.jboss.aesh.terminal.utils.ShutdownHooks.Task;
+import org.jboss.aesh.terminal.utils.Signals;
+
+public class WinSysConsole extends AbstractConsole {
+
+ protected final InputStream input;
+ protected final OutputStream output;
+ protected final Reader reader;
+ protected final PrintWriter writer;
+ protected final Map<Signal, Object> nativeHandlers = new HashMap<Signal, Object>();
+ protected final Task closer;
+
+ private static final int ENABLE_PROCESSED_INPUT = 0x0001;
+ private static final int ENABLE_LINE_INPUT = 0x0002;
+ private static final int ENABLE_ECHO_INPUT = 0x0004;
+ private static final int ENABLE_WINDOW_INPUT = 0x0008;
+ private static final int ENABLE_MOUSE_INPUT = 0x0010;
+ private static final int ENABLE_INSERT_MODE = 0x0020;
+ private static final int ENABLE_QUICK_EDIT_MODE = 0x0040;
+
+
+ public WinSysConsole(String name, boolean nativeSignals) throws IOException {
+ super(name, "windows");
+ input = new DirectInputStream();
+ output = new WindowsAnsiOutputStream(new FileOutputStream(FileDescriptor.out));
+ String encoding = getConsoleEncoding();
+ if (encoding == null) {
+ encoding = Charset.defaultCharset().name();
+ }
+ this.reader = new InputStreamReader(input, encoding);
+ this.writer = new PrintWriter(new OutputStreamWriter(output, encoding));
+ parseInfoCmp();
+ // Handle signals
+ if (nativeSignals) {
+ for (final Signal signal : Signal.values()) {
+ nativeHandlers.put(signal, Signals.register(signal.name(), () -> raise(signal)));
+ }
+ }
+ closer = this::close;
+ ShutdownHooks.add(closer);
+ }
+
+ @SuppressWarnings("InjectedReferences")
+ protected static String getConsoleEncoding() {
+ int codepage = Kernel32.GetConsoleOutputCP();
+ //http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
+ String charsetMS = "ms" + codepage;
+ if (Charset.isSupported(charsetMS)) {
+ return charsetMS;
+ }
+ String charsetCP = "cp" + codepage;
+ if (Charset.isSupported(charsetCP)) {
+ return charsetCP;
+ }
+ return null;
+ }
+
+ public Reader reader() {
+ return reader;
+ }
+
+ public PrintWriter writer() {
+ return writer;
+ }
+
+ @Override
+ public InputStream input() {
+ return input;
+ }
+
+ @Override
+ public OutputStream output() {
+ return output;
+ }
+
+ public Attributes getAttributes() {
+ int mode = WindowsSupport.getConsoleMode();
+ Attributes attributes = new Attributes();
+ if ((mode & ENABLE_ECHO_INPUT) != 0) {
+ attributes.setLocalFlag(LocalFlag.ECHO, true);
+ }
+ if ((mode & ENABLE_LINE_INPUT) != 0) {
+ attributes.setLocalFlag(LocalFlag.ICANON, true);
+ }
+ return attributes;
+ }
+
+ public void setAttributes(Attributes attr) {
+ int mode = 0;
+ if (attr.getLocalFlag(LocalFlag.ECHO)) {
+ mode |= ENABLE_ECHO_INPUT;
+ }
+ if (attr.getLocalFlag(LocalFlag.ICANON)) {
+ mode |= ENABLE_LINE_INPUT;
+ }
+ WindowsSupport.setConsoleMode(mode);
+ }
+
+ public Size getSize() {
+ return new Size(WindowsSupport.getWindowsTerminalHeight(),
+ WindowsSupport.getWindowsTerminalWidth());
+ }
+
+ public void setSize(Size size) {
+ throw new UnsupportedOperationException("Can not resize windows console");
+ }
+
+ public void close() throws IOException {
+ ShutdownHooks.remove(closer);
+ for (Map.Entry<Signal, Object> entry : nativeHandlers.entrySet()) {
+ Signals.unregister(entry.getKey().name(), entry.getValue());
+ }
+ reader.close();
+ writer.close();
+ }
+
+ private byte[] readConsoleInput() {
+ // XXX does how many events to read in one call matter?
+ INPUT_RECORD[] events = null;
+ try {
+ events = WindowsSupport.readConsoleInput(1);
+ } catch (IOException e) {
+ LOGGER.log(Level.FINE, "read Windows console input error: ", e);
+ }
+ if (events == null) {
+ return new byte[0];
+ }
+ StringBuilder sb = new StringBuilder();
+ for (INPUT_RECORD event : events) {
+ KEY_EVENT_RECORD keyEvent = event.keyEvent;
+ // support some C1 control sequences: ALT + [@-_] (and [a-z]?) => ESC <ascii>
+ // http://en.wikipedia.org/wiki/C0_and_C1_control_codes#C1_set
+ final int altState = KEY_EVENT_RECORD.LEFT_ALT_PRESSED | KEY_EVENT_RECORD.RIGHT_ALT_PRESSED;
+ // Pressing "Alt Gr" is translated to Alt-Ctrl, hence it has to be checked that Ctrl is _not_ pressed,
+ // otherwise inserting of "Alt Gr" codes on non-US keyboards would yield errors
+ final int ctrlState = KEY_EVENT_RECORD.LEFT_CTRL_PRESSED | KEY_EVENT_RECORD.RIGHT_CTRL_PRESSED;
+ // Compute the overall alt state
+ boolean isAlt = ((keyEvent.controlKeyState & altState) != 0) && ((keyEvent.controlKeyState & ctrlState) == 0);
+
+ //Log.trace(keyEvent.keyDown? "KEY_DOWN" : "KEY_UP", "key code:", keyEvent.keyCode, "char:", (long)keyEvent.uchar);
+ if (keyEvent.keyDown) {
+ if (keyEvent.uchar > 0) {
+ if (isAlt) {
+ sb.append('\033');
+ }
+ sb.append(keyEvent.uchar);
+ }
+ else {
+ // virtual keycodes: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
+ // TODO: numpad keys, modifiers
+ String escapeSequence = null;
+ switch (keyEvent.keyCode) {
+ case 0x08: // VK_BACK BackSpace
+ escapeSequence = getSequence(Capability.key_backspace);
+ break;
+ case 0x21: // VK_PRIOR PageUp
+ escapeSequence = getSequence(Capability.key_ppage);
+ break;
+ case 0x22: // VK_NEXT PageDown
+ escapeSequence = getSequence(Capability.key_npage);
+ break;
+ case 0x23: // VK_END
+ escapeSequence = getSequence(Capability.key_end);
+ break;
+ case 0x24: // VK_HOME
+ escapeSequence = getSequence(Capability.key_home);
+ break;
+ case 0x25: // VK_LEFT
+ escapeSequence = getSequence(Capability.key_left);
+ break;
+ case 0x26: // VK_UP
+ escapeSequence = getSequence(Capability.key_up);
+ break;
+ case 0x27: // VK_RIGHT
+ escapeSequence = getSequence(Capability.key_right);
+ break;
+ case 0x28: // VK_DOWN
+ escapeSequence = getSequence(Capability.key_down);
+ break;
+ case 0x2D: // VK_INSERT
+ escapeSequence = getSequence(Capability.key_ic);
+ break;
+ case 0x2E: // VK_DELETE
+ escapeSequence = getSequence(Capability.key_dc);
+ break;
+ case 0x70: // VK_F1
+ escapeSequence = getSequence(Capability.key_f1);
+ break;
+ case 0x71: // VK_F2
+ escapeSequence = getSequence(Capability.key_f2);
+ break;
+ case 0x72: // VK_F3
+ escapeSequence = getSequence(Capability.key_f3);
+ break;
+ case 0x73: // VK_F4
+ escapeSequence = getSequence(Capability.key_f4);
+ break;
+ case 0x74: // VK_F5
+ escapeSequence = getSequence(Capability.key_f5);
+ break;
+ case 0x75: // VK_F6
+ escapeSequence = getSequence(Capability.key_f6);
+ break;
+ case 0x76: // VK_F7
+ escapeSequence = getSequence(Capability.key_f7);
+ break;
+ case 0x77: // VK_F8
+ escapeSequence = getSequence(Capability.key_f8);
+ break;
+ case 0x78: // VK_F9
+ escapeSequence = getSequence(Capability.key_f9);
+ break;
+ case 0x79: // VK_F10
+ escapeSequence = getSequence(Capability.key_f10);
+ break;
+ case 0x7A: // VK_F11
+ escapeSequence = getSequence(Capability.key_f11);
+ break;
+ case 0x7B: // VK_F12
+ escapeSequence = getSequence(Capability.key_f12);
+ break;
+ default:
+ break;
+ }
+ if (escapeSequence != null) {
+ for (int k = 0; k < keyEvent.repeatCount; k++) {
+ if (isAlt) {
+ sb.append('\033');
+ }
+ sb.append(escapeSequence);
+ }
+ }
+ }
+ } else {
+ // key up event
+ // support ALT+NumPad input method
+ if (keyEvent.keyCode == 0x12/*VK_MENU ALT key*/ && keyEvent.uchar > 0) {
+ sb.append(keyEvent.uchar);
+ }
+ }
+ }
+ return sb.toString().getBytes();
+ }
+
+ private String getSequence(Capability cap) {
+ String str = strings.get(cap);
+ if (str != null) {
+ StringWriter sw = new StringWriter();
+ try {
+ Curses.tputs(sw, str);
+ } catch (IOException e) {
+ throw new IOError(e);
+ }
+ return sw.toString();
+ }
+ return null;
+ }
+
+ private class DirectInputStream extends InputStream {
+ private byte[] buf = null;
+ int bufIdx = 0;
+
+ @Override
+ public int read() throws IOException {
+ while (buf == null || bufIdx == buf.length) {
+ buf = readConsoleInput();
+ bufIdx = 0;
+ }
+ int c = buf[bufIdx] & 0xFF;
+ bufIdx++;
+ return c;
+ }
+
+ public int read(byte b[], int off, int len) throws IOException {
+ if (b == null) {
+ throw new NullPointerException();
+ } else if (off < 0 || len < 0 || len > b.length - off) {
+ throw new IndexOutOfBoundsException();
+ } else if (len == 0) {
+ return 0;
+ }
+
+ int c = read();
+ if (c == -1) {
+ return -1;
+ }
+ b[off] = (byte)c;
+ return 1;
+ }
+ }
+}
diff --git a/src/main/java/org/jboss/aesh/terminal/Curses.java b/src/main/java/org/jboss/aesh/terminal/utils/Curses.java
similarity index 99%
rename from src/main/java/org/jboss/aesh/terminal/Curses.java
rename to src/main/java/org/jboss/aesh/terminal/utils/Curses.java
index 69e8f8b34..ef0cb4578 100644
--- a/src/main/java/org/jboss/aesh/terminal/Curses.java
+++ b/src/main/java/org/jboss/aesh/terminal/utils/Curses.java
@@ -6,7 +6,7 @@
*
* http://www.opensource.org/licenses/bsd-license.php
*/
-package org.jboss.aesh.terminal;
+package org.jboss.aesh.terminal.utils;
import java.io.IOException;
import java.io.Writer;
diff --git a/src/main/java/org/jboss/aesh/terminal/ExecHelper.java b/src/main/java/org/jboss/aesh/terminal/utils/ExecHelper.java
similarity index 80%
rename from src/main/java/org/jboss/aesh/terminal/ExecHelper.java
rename to src/main/java/org/jboss/aesh/terminal/utils/ExecHelper.java
index 9de83ee42..108b3d0e2 100644
--- a/src/main/java/org/jboss/aesh/terminal/ExecHelper.java
+++ b/src/main/java/org/jboss/aesh/terminal/utils/ExecHelper.java
@@ -6,7 +6,7 @@
*
* http://www.opensource.org/licenses/bsd-license.php
*/
-package org.jboss.aesh.terminal;
+package org.jboss.aesh.terminal.utils;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
@@ -15,14 +15,9 @@
import java.io.OutputStream;
/**
- * Provides access to terminal line settings via <tt>stty</tt>.
+ * Helper methods for capturing an external process output.
*
- * @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a>
- * @author <a href="mailto:[email protected]">Dale Kemp</a>
- * @author <a href="mailto:[email protected]">Jason Dillon</a>
- * @author <a href="mailto:[email protected]">Jean-Baptiste Onofré</a>
* @author <a href="mailto:[email protected]">Guillaume Nodet</a>
- * @since 2.0
*/
public final class ExecHelper
{
diff --git a/src/main/java/org/jboss/aesh/terminal/InfoCmp.java b/src/main/java/org/jboss/aesh/terminal/utils/InfoCmp.java
similarity index 99%
rename from src/main/java/org/jboss/aesh/terminal/InfoCmp.java
rename to src/main/java/org/jboss/aesh/terminal/utils/InfoCmp.java
index 4f1dc5600..603454c74 100644
--- a/src/main/java/org/jboss/aesh/terminal/InfoCmp.java
+++ b/src/main/java/org/jboss/aesh/terminal/utils/InfoCmp.java
@@ -6,7 +6,7 @@
*
* http://www.opensource.org/licenses/bsd-license.php
*/
-package org.jboss.aesh.terminal;
+package org.jboss.aesh.terminal.utils;
import java.io.IOException;
import java.util.HashMap;
diff --git a/src/main/java/org/jboss/aesh/terminal/utils/InputStreamReader.java b/src/main/java/org/jboss/aesh/terminal/utils/InputStreamReader.java
new file mode 100644
index 000000000..71686b29f
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/utils/InputStreamReader.java
@@ -0,0 +1,346 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.utils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.MalformedInputException;
+import java.nio.charset.UnmappableCharacterException;
+
+
+/**
+ *
+ * NOTE for JLine: the default InputStreamReader that comes from the JRE
+ * usually read more bytes than needed from the input stream, which
+ * is not usable in a character per character model used in the console.
+ * We thus use the harmony code which only reads the minimal number of bytes.
+ */
+
+/**
+ * A class for turning a byte stream into a character stream. Data read from the
+ * source input stream is converted into characters by either a default or a
+ * provided character converter. The default encoding is taken from the
+ * "file.encoding" system property. {@code InputStreamReader} contains a buffer
+ * of bytes read from the source stream and converts these into characters as
+ * needed. The buffer size is 8K.
+ *
+ * @see OutputStreamWriter
+ */
+public class InputStreamReader extends Reader {
+ private InputStream in;
+
+ private static final int BUFFER_SIZE = 4;
+
+ private boolean endOfInput = false;
+
+ CharsetDecoder decoder;
+
+ ByteBuffer bytes = ByteBuffer.allocate(BUFFER_SIZE);
+
+ char pending = (char) -1;
+
+ /**
+ * Constructs a new {@code InputStreamReader} on the {@link InputStream}
+ * {@code in}. This constructor sets the character converter to the encoding
+ * specified in the "file.encoding" property and falls back to ISO 8859_1
+ * (ISO-Latin-1) if the property doesn't exist.
+ *
+ * @param in
+ * the input stream from which to read characters.
+ */
+ public InputStreamReader(InputStream in) {
+ super(in);
+ this.in = in;
+ decoder = Charset.defaultCharset().newDecoder().onMalformedInput(
+ CodingErrorAction.REPLACE).onUnmappableCharacter(
+ CodingErrorAction.REPLACE);
+ bytes.limit(0);
+ }
+
+ /**
+ * Constructs a new InputStreamReader on the InputStream {@code in}. The
+ * character converter that is used to decode bytes into characters is
+ * identified by name by {@code enc}. If the encoding cannot be found, an
+ * UnsupportedEncodingException error is thrown.
+ *
+ * @param in
+ * the InputStream from which to read characters.
+ * @param enc
+ * identifies the character converter to use.
+ * @throws NullPointerException
+ * if {@code enc} is {@code null}.
+ * @throws UnsupportedEncodingException
+ * if the encoding specified by {@code enc} cannot be found.
+ */
+ public InputStreamReader(InputStream in, final String enc)
+ throws UnsupportedEncodingException {
+ super(in);
+ if (enc == null) {
+ throw new NullPointerException();
+ }
+ this.in = in;
+ try {
+ decoder = Charset.forName(enc).newDecoder().onMalformedInput(
+ CodingErrorAction.REPLACE).onUnmappableCharacter(
+ CodingErrorAction.REPLACE);
+ } catch (IllegalArgumentException e) {
+ throw (UnsupportedEncodingException)
+ new UnsupportedEncodingException(enc).initCause(e);
+ }
+ bytes.limit(0);
+ }
+
+ /**
+ * Constructs a new InputStreamReader on the InputStream {@code in} and
+ * CharsetDecoder {@code dec}.
+ *
+ * @param in
+ * the source InputStream from which to read characters.
+ * @param dec
+ * the CharsetDecoder used by the character conversion.
+ */
+ public InputStreamReader(InputStream in, CharsetDecoder dec) {
+ super(in);
+ dec.averageCharsPerByte();
+ this.in = in;
+ decoder = dec;
+ bytes.limit(0);
+ }
+
+ /**
+ * Constructs a new InputStreamReader on the InputStream {@code in} and
+ * Charset {@code charset}.
+ *
+ * @param in
+ * the source InputStream from which to read characters.
+ * @param charset
+ * the Charset that defines the character converter
+ */
+ public InputStreamReader(InputStream in, Charset charset) {
+ super(in);
+ this.in = in;
+ decoder = charset.newDecoder().onMalformedInput(
+ CodingErrorAction.REPLACE).onUnmappableCharacter(
+ CodingErrorAction.REPLACE);
+ bytes.limit(0);
+ }
+
+ /**
+ * Closes this reader. This implementation closes the source InputStream and
+ * releases all local storage.
+ *
+ * @throws IOException
+ * if an error occurs attempting to close this reader.
+ */
+ @Override
+ public void close() throws IOException {
+ synchronized (lock) {
+ decoder = null;
+ if (in != null) {
+ in.close();
+ in = null;
+ }
+ }
+ }
+
+ /**
+ * Returns the name of the encoding used to convert bytes into characters.
+ * The value {@code null} is returned if this reader has been closed.
+ *
+ * @return the name of the character converter or {@code null} if this
+ * reader is closed.
+ */
+ public String getEncoding() {
+ if (!isOpen()) {
+ return null;
+ }
+ return decoder.charset().name();
+ }
+
+ /**
+ * Reads a single character from this reader and returns it as an integer
+ * with the two higher-order bytes set to 0. Returns -1 if the end of the
+ * reader has been reached. The byte value is either obtained from
+ * converting bytes in this reader's buffer or by first filling the buffer
+ * from the source InputStream and then reading from the buffer.
+ *
+ * @return the character read or -1 if the end of the reader has been
+ * reached.
+ * @throws IOException
+ * if this reader is closed or some other I/O error occurs.
+ */
+ @Override
+ public int read() throws IOException {
+ synchronized (lock) {
+ if (!isOpen()) {
+ throw new IOException("InputStreamReader is closed.");
+ }
+
+ if (pending != (char) -1) {
+ char c = pending;
+ pending = (char) -1;
+ return c;
+ }
+ char buf[] = new char[2];
+ int nb = read(buf, 0, 2);
+ if (nb == 2) {
+ pending = buf[1];
+ }
+ if (nb > 0) {
+ return buf[0];
+ } else {
+ return -1;
+ }
+ }
+ }
+
+ /**
+ * Reads at most {@code length} characters from this reader and stores them
+ * at position {@code offset} in the character array {@code buf}. Returns
+ * the number of characters actually read or -1 if the end of the reader has
+ * been reached. The bytes are either obtained from converting bytes in this
+ * reader's buffer or by first filling the buffer from the source
+ * InputStream and then reading from the buffer.
+ *
+ * @param buf
+ * the array to store the characters read.
+ * @param offset
+ * the initial position in {@code buf} to store the characters
+ * read from this reader.
+ * @param length
+ * the maximum number of characters to read.
+ * @return the number of characters read or -1 if the end of the reader has
+ * been reached.
+ * @throws IndexOutOfBoundsException
+ * if {@code offset < 0} or {@code length < 0}, or if
+ * {@code offset + length} is greater than the length of
+ * {@code buf}.
+ * @throws IOException
+ * if this reader is closed or some other I/O error occurs.
+ */
+ @Override
+ public int read(char[] buf, int offset, int length) throws IOException {
+ synchronized (lock) {
+ if (!isOpen()) {
+ throw new IOException("InputStreamReader is closed.");
+ }
+ if (offset < 0 || offset > buf.length - length || length < 0) {
+ throw new IndexOutOfBoundsException();
+ }
+ if (length == 0) {
+ return 0;
+ }
+
+ CharBuffer out = CharBuffer.wrap(buf, offset, length);
+ CoderResult result = CoderResult.UNDERFLOW;
+
+ // bytes.remaining() indicates number of bytes in buffer
+ // when 1-st time entered, it'll be equal to zero
+ boolean needInput = !bytes.hasRemaining();
+
+ while (out.position() == offset) {
+ // fill the buffer if needed
+ if (needInput) {
+ try {
+ if ((in.available() == 0)
+ && (out.position() > offset)) {
+ // we could return the result without blocking read
+ break;
+ }
+ } catch (IOException e) {
+ // available didn't work so just try the read
+ }
+
+ int off = bytes.arrayOffset() + bytes.limit();
+ int was_red = in.read(bytes.array(), off, 1);
+
+ if (was_red == -1) {
+ endOfInput = true;
+ break;
+ } else if (was_red == 0) {
+ break;
+ }
+ bytes.limit(bytes.limit() + was_red);
+ }
+
+ // decode bytes
+ result = decoder.decode(bytes, out, false);
+
+ if (result.isUnderflow()) {
+ // compact the buffer if no space left
+ if (bytes.limit() == bytes.capacity()) {
+ bytes.compact();
+ bytes.limit(bytes.position());
+ bytes.position(0);
+ }
+ needInput = true;
+ } else {
+ break;
+ }
+ }
+
+ if (result == CoderResult.UNDERFLOW && endOfInput) {
+ result = decoder.decode(bytes, out, true);
+ decoder.flush(out);
+ decoder.reset();
+ }
+ if (result.isMalformed()) {
+ throw new MalformedInputException(result.length());
+ } else if (result.isUnmappable()) {
+ throw new UnmappableCharacterException(result.length());
+ }
+
+ return out.position() - offset == 0 ? -1 : out.position() - offset;
+ }
+ }
+
+ /*
+ * Answer a boolean indicating whether or not this InputStreamReader is
+ * open.
+ */
+ private boolean isOpen() {
+ return in != null;
+ }
+
+ /**
+ * Indicates whether this reader is ready to be read without blocking. If
+ * the result is {@code true}, the next {@code read()} will not block. If
+ * the result is {@code false} then this reader may or may not block when
+ * {@code read()} is called. This implementation returns {@code true} if
+ * there are bytes available in the buffer or the source stream has bytes
+ * available.
+ *
+ * @return {@code true} if the receiver will not block when {@code read()}
+ * is called, {@code false} if unknown or blocking will occur.
+ * @throws IOException
+ * if this reader is closed or some other I/O error occurs.
+ */
+ @Override
+ public boolean ready() throws IOException {
+ synchronized (lock) {
+ if (in == null) {
+ throw new IOException("InputStreamReader is closed.");
+ }
+ try {
+ return bytes.hasRemaining() || in.available() > 0;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/org/jboss/aesh/terminal/OSUtils.java b/src/main/java/org/jboss/aesh/terminal/utils/OSUtils.java
similarity index 83%
rename from src/main/java/org/jboss/aesh/terminal/OSUtils.java
rename to src/main/java/org/jboss/aesh/terminal/utils/OSUtils.java
index 57236e1c3..c3633a039 100644
--- a/src/main/java/org/jboss/aesh/terminal/OSUtils.java
+++ b/src/main/java/org/jboss/aesh/terminal/utils/OSUtils.java
@@ -1,10 +1,15 @@
-package org.jboss.aesh.terminal;
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.utils;
import java.io.File;
-/**
- * Created by gnodet on 01/10/15.
- */
public class OSUtils {
public static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().contains("win");
diff --git a/src/main/java/org/jboss/aesh/terminal/utils/ShutdownHooks.java b/src/main/java/org/jboss/aesh/terminal/utils/ShutdownHooks.java
new file mode 100644
index 000000000..1920c955d
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/utils/ShutdownHooks.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.jboss.aesh.util.LoggerUtil;
+
+/**
+ * Manages the JLine shutdown-hook thread and tasks to execute on shutdown.
+ *
+ * @author <a href="mailto:[email protected]">Jason Dillon</a>
+ */
+public final class ShutdownHooks
+{
+ private static final Logger LOGGER = LoggerUtil.getLogger(ShutdownHooks.class.getName());
+
+ private static final List<Task> tasks = new ArrayList<Task>();
+
+ private static Thread hook;
+
+ public static synchronized <T extends Task> T add(final T task) {
+ assert task != null;
+
+ // Install the hook thread if needed
+ if (hook == null) {
+ hook = addHook(new Thread("JLine Shutdown Hook")
+ {
+ @Override
+ public void run() {
+ runTasks();
+ }
+ });
+ }
+
+ // Track the task
+ LOGGER.log(Level.FINE, "Adding shutdown-hook task: ", task);
+ tasks.add(task);
+
+ return task;
+ }
+
+ private static synchronized void runTasks() {
+ LOGGER.log(Level.FINE, "Running all shutdown-hook tasks");
+
+ // Iterate through copy of tasks list
+ for (Task task : tasks.toArray(new Task[tasks.size()])) {
+ LOGGER.log(Level.FINE, "Running task: ", task);
+ try {
+ task.run();
+ }
+ catch (Throwable e) {
+ LOGGER.log(Level.WARNING, "Task failed", e);
+ }
+ }
+
+ tasks.clear();
+ }
+
+ private static Thread addHook(final Thread thread) {
+ LOGGER.log(Level.FINE, "Registering shutdown-hook: ", thread);
+ try {
+ Runtime.getRuntime().addShutdownHook(thread);
+ }
+ catch (AbstractMethodError e) {
+ // JDK 1.3+ only method. Bummer.
+ LOGGER.log(Level.FINE, "Failed to register shutdown-hook", e);
+ }
+ return thread;
+ }
+
+ public static synchronized void remove(final Task task) {
+ assert task != null;
+
+ // ignore if hook never installed
+ if (hook == null) {
+ return;
+ }
+
+ // Drop the task
+ tasks.remove(task);
+
+ // If there are no more tasks, then remove the hook thread
+ if (tasks.isEmpty()) {
+ removeHook(hook);
+ hook = null;
+ }
+ }
+
+ private static void removeHook(final Thread thread) {
+ LOGGER.log(Level.FINE, "Removing shutdown-hook: ", thread);
+
+ try {
+ Runtime.getRuntime().removeShutdownHook(thread);
+ }
+ catch (AbstractMethodError e) {
+ // JDK 1.3+ only method. Bummer.
+ LOGGER.log(Level.FINE, "Failed to remove shutdown-hook", e);
+ }
+ catch (IllegalStateException e) {
+ // The VM is shutting down, not a big deal; ignore
+ }
+ }
+
+ /**
+ * Essentially a {@link Runnable} which allows running to throw an exception.
+ */
+ public interface Task
+ {
+ void run() throws Exception;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/org/jboss/aesh/terminal/utils/Signals.java b/src/main/java/org/jboss/aesh/terminal/utils/Signals.java
new file mode 100644
index 000000000..39b9f87e9
--- /dev/null
+++ b/src/main/java/org/jboss/aesh/terminal/utils/Signals.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2002-2015, the original author or authors.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ *
+ * http://www.opensource.org/licenses/bsd-license.php
+ */
+package org.jboss.aesh.terminal.utils;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+/**
+ * Signals helpers.
+ *
+ * @author <a href="mailto:[email protected]">Guillaume Nodet</a>
+ */
+public final class Signals {
+
+ private Signals() {
+ }
+
+ /**
+ *
+ * @param name the signal, CONT, STOP, etc...
+ * @param handler the callback to run
+ *
+ * @return an object that needs to be passed to the {@link #unregister(String, Object)}
+ * method to unregister the handler
+ */
+ public static Object register(String name, Runnable handler) {
+ assert name != null;
+ assert handler != null;
+ return register(name, handler, handler.getClass().getClassLoader());
+ }
+
+ public static Object register(String name, final Runnable handler, ClassLoader loader) {
+ try {
+ Class<?> signalHandlerClass = Class.forName("sun.misc.SignalHandler");
+ // Implement signal handler
+ Object signalHandler = Proxy.newProxyInstance(loader,
+ new Class<?>[]{signalHandlerClass}, new InvocationHandler() {
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ // only method we are proxying is handle()
+ handler.run();
+ return null;
+ }
+ });
+ doRegister(name, signalHandler);
+ } catch (Exception e) {
+ // Ignore this one too, if the above failed, the signal API is incompatible with what we're expecting
+ }
+ return null;
+ }
+
+ public static Object registerDefault(String name) {
+ try {
+ Class<?> signalHandlerClass = Class.forName("sun.misc.SignalHandler");
+ doRegister(name, signalHandlerClass.getField("SIG_DFL").get(null));
+ } catch (Exception e) {
+ // Ignore this one too, if the above failed, the signal API is incompatible with what we're expecting
+ }
+ return null;
+ }
+
+ public static Object registerIgnore(String name) {
+ try {
+ Class<?> signalHandlerClass = Class.forName("sun.misc.SignalHandler");
+ doRegister(name, signalHandlerClass.getField("SIG_IGN").get(null));
+ } catch (Exception e) {
+ // Ignore this one too, if the above failed, the signal API is incompatible with what we're expecting
+ }
+ return null;
+ }
+
+ public static void unregister(String name, Object previous) {
+ try {
+ // We should make sure the current signal is the one we registered
+ if (previous != null) {
+ doRegister(name, previous);
+ }
+ } catch (Exception e) {
+ // Ignore
+ }
+ }
+
+ private static Object doRegister(String name, Object handler) throws Exception {
+ Class<?> signalClass = Class.forName("sun.misc.Signal");
+ Class<?> signalHandlerClass = Class.forName("sun.misc.SignalHandler");
+ Object signal = signalClass.getConstructor(String.class).newInstance(name);
+ return signalClass.getMethod("handle", signalClass, signalHandlerClass)
+ .invoke(null, signal, handler);
+ }
+
+}
diff --git a/src/test/java/org/jboss/aesh/console/terminal/CursesTest.java b/src/test/java/org/jboss/aesh/console/terminal/utils/CursesTest.java
similarity index 89%
rename from src/test/java/org/jboss/aesh/console/terminal/CursesTest.java
rename to src/test/java/org/jboss/aesh/console/terminal/utils/CursesTest.java
index 9c928d56e..f6acf8989 100644
--- a/src/test/java/org/jboss/aesh/console/terminal/CursesTest.java
+++ b/src/test/java/org/jboss/aesh/console/terminal/utils/CursesTest.java
@@ -6,11 +6,11 @@
*
* http://www.opensource.org/licenses/bsd-license.php
*/
-package org.jboss.aesh.console.terminal;
+package org.jboss.aesh.console.terminal.utils;
import java.io.StringWriter;
-import org.jboss.aesh.terminal.Curses;
+import org.jboss.aesh.terminal.utils.Curses;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
diff --git a/src/test/java/org/jboss/aesh/console/terminal/InfoCmpTest.java b/src/test/java/org/jboss/aesh/console/terminal/utils/InfoCmpTest.java
similarity index 87%
rename from src/test/java/org/jboss/aesh/console/terminal/InfoCmpTest.java
rename to src/test/java/org/jboss/aesh/console/terminal/utils/InfoCmpTest.java
index 841d87ac0..0dde640f0 100644
--- a/src/test/java/org/jboss/aesh/console/terminal/InfoCmpTest.java
+++ b/src/test/java/org/jboss/aesh/console/terminal/utils/InfoCmpTest.java
@@ -6,15 +6,15 @@
*
* http://www.opensource.org/licenses/bsd-license.php
*/
-package org.jboss.aesh.console.terminal;
+package org.jboss.aesh.console.terminal.utils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
-import org.jboss.aesh.terminal.InfoCmp;
-import org.jboss.aesh.terminal.InfoCmp.Capability;
+import org.jboss.aesh.terminal.utils.InfoCmp;
+import org.jboss.aesh.terminal.utils.InfoCmp.Capability;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
|
f0f7133a3ae5cff39e4f13643c346fe3b234a8ac
|
camel
|
CAMEL-751 fixed the spring configuration url- error--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@679379 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/config/ErrorHandlerTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/config/ErrorHandlerTest.java
index a0b3593b42a5c..1e9da2e0d1b90 100644
--- a/components/camel-spring/src/test/java/org/apache/camel/spring/config/ErrorHandlerTest.java
+++ b/components/camel-spring/src/test/java/org/apache/camel/spring/config/ErrorHandlerTest.java
@@ -30,7 +30,7 @@
public class ErrorHandlerTest extends SpringTestSupport {
protected ClassPathXmlApplicationContext createApplicationContext() {
- return new ClassPathXmlApplicationContext("org/apache/camel/spring/errorHandler.xml");
+ return new ClassPathXmlApplicationContext("org/apache/camel/spring/config/errorHandler.xml");
}
public void testEndpointConfiguration() throws Exception {
|
72d9872fffa2b8f6d534612436b1613ed062e026
|
ReactiveX-RxJava
|
updated a test and added another one
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
index 725d7781ae..53a11e0b24 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
@@ -304,7 +304,7 @@ public void testCombineLatestDifferentLengthObservableSequences1() {
/* we should have been called 4 times on the Observer */
InOrder inOrder = inOrder(w);
- inOrder.verify(w).onNext("1a2a3a");
+ inOrder.verify(w).onNext("1a2b3a");
inOrder.verify(w).onNext("1a2b3b");
inOrder.verify(w).onNext("1a2b3c");
inOrder.verify(w).onNext("1a2b3d");
@@ -348,6 +348,45 @@ public void testCombineLatestDifferentLengthObservableSequences2() {
}
+ @SuppressWarnings("unchecked")
+ /* mock calls don't do generics */
+ @Test
+ public void testCombineLatestWithInterleavingSequences() {
+ Observer<String> w = mock(Observer.class);
+
+ TestObservable w1 = new TestObservable();
+ TestObservable w2 = new TestObservable();
+ TestObservable w3 = new TestObservable();
+
+ Observable<String> combineLatestW = Observable.create(combineLatest(w1, w2, w3, getConcat3StringsCombineLatestFunction()));
+ combineLatestW.subscribe(w);
+
+ /* simulate sending data */
+ w1.Observer.onNext("1a");
+ w2.Observer.onNext("2a");
+ w2.Observer.onNext("2b");
+ w3.Observer.onNext("3a");
+
+ w1.Observer.onNext("1b");
+ w2.Observer.onNext("2c");
+ w2.Observer.onNext("2d");
+ w3.Observer.onNext("3b");
+
+ w1.Observer.onCompleted();
+ w2.Observer.onCompleted();
+ w3.Observer.onCompleted();
+
+ /* we should have been called 5 times on the Observer */
+ InOrder inOrder = inOrder(w);
+ inOrder.verify(w).onNext("1a2b3a");
+ inOrder.verify(w).onNext("1b2b3a");
+ inOrder.verify(w).onNext("1b2c3a");
+ inOrder.verify(w).onNext("1b2d3a");
+ inOrder.verify(w).onNext("1b2d3b");
+
+ inOrder.verify(w, times(1)).onCompleted();
+ }
+
/**
* Testing internal private logic due to the complexity so I want to use TDD to test as a I build it rather than relying purely on the overall functionality expected by the public methods.
*/
|
d77c6eb30ee1f173c65bedabf25f138c9a4e50f2
|
kotlin
|
Exception fix: diagnose an error for a generic- type which is a subtype of itself
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
index 0daa6285114b3..0f6bb6582b50d 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
@@ -249,6 +249,8 @@ public interface Errors {
DiagnosticFactory0<JetDeclaration> TYPE_PARAMETERS_NOT_ALLOWED
= DiagnosticFactory0.create(ERROR, TYPE_PARAMETERS_OR_DECLARATION_SIGNATURE);
+ DiagnosticFactory0<PsiElement> CYCLIC_GENERIC_UPPER_BOUND = DiagnosticFactory0.create(ERROR);
+
// Members
DiagnosticFactory0<JetModifierListOwner> PACKAGE_MEMBER_CANNOT_BE_PROTECTED =
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
index 4272678d51f73..69c0bd405ffe6 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
@@ -421,6 +421,7 @@ public String render(@NotNull JetExpression expression) {
MAP.put(TYPE_MISMATCH_IN_RANGE, "Type mismatch: incompatible types of range and element checked in it");
MAP.put(CYCLIC_INHERITANCE_HIERARCHY, "There's a cycle in the inheritance hierarchy for this type");
+ MAP.put(CYCLIC_GENERIC_UPPER_BOUND, "Type parameter has itself as an upper bound");
MAP.put(MANY_CLASSES_IN_SUPERTYPE_LIST, "Only one class may appear in a supertype list");
MAP.put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, "Only classes and interfaces may serve as supertypes");
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
index 5e23f7bef6c82..6bbac29d8f4f3 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
@@ -28,6 +28,7 @@
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.*;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory1;
+import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.lexer.JetKeywordToken;
import org.jetbrains.kotlin.lexer.JetModifierKeywordToken;
import org.jetbrains.kotlin.lexer.JetTokens;
@@ -476,6 +477,10 @@ public void resolveGenericBounds(
JetTypeReference extendsBound = jetTypeParameter.getExtendsBound();
if (extendsBound != null) {
JetType type = typeResolver.resolveType(scope, extendsBound, trace, false);
+ if (type.getConstructor().equals(typeParameterDescriptor.getTypeConstructor())) {
+ trace.report(Errors.CYCLIC_GENERIC_UPPER_BOUND.on(extendsBound));
+ type = ErrorUtils.createErrorType("Cyclic upper bound: " + type);
+ }
typeParameterDescriptor.addUpperBound(type);
deferredUpperBoundCheckerTasks.add(new UpperBoundCheckerTask(extendsBound, type));
}
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.kt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.kt
new file mode 100644
index 0000000000000..7bc7846fc26bc
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.kt
@@ -0,0 +1,3 @@
+// !DIAGNOSTICS: -MUST_BE_INITIALIZED
+fun <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> foo() {}
+val <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> prop
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.txt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.txt
new file mode 100644
index 0000000000000..e9d759332ac62
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.txt
@@ -0,0 +1,4 @@
+package
+
+internal val </*0*/ T : [ERROR : Cyclic upper bound: T?]> prop: [ERROR : No type, no body]
+internal fun </*0*/ T : [ERROR : Cyclic upper bound: T?]> foo(): kotlin.Unit
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.kt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.kt
new file mode 100644
index 0000000000000..353988510c342
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.kt
@@ -0,0 +1,4 @@
+fun bar() {
+ fun <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> foo() {}
+ foo()
+}
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.txt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.txt
new file mode 100644
index 0000000000000..b015afc1ae045
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.txt
@@ -0,0 +1,3 @@
+package
+
+internal fun bar(): kotlin.Unit
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.kt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.kt
new file mode 100644
index 0000000000000..91cc9ac8fc22d
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.kt
@@ -0,0 +1,5 @@
+// !DIAGNOSTICS: -MUST_BE_INITIALIZED_OR_BE_ABSTRACT
+class My {
+ fun <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> foo() {}
+ val <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> prop: T
+}
\ No newline at end of file
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.txt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.txt
new file mode 100644
index 0000000000000..213f4fddd6446
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.txt
@@ -0,0 +1,10 @@
+package
+
+internal final class My {
+ public constructor My()
+ internal final val </*0*/ T : [ERROR : Cyclic upper bound: T?]> prop: [ERROR : ?]
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ internal final fun </*0*/ T : [ERROR : Cyclic upper bound: T?]> foo(): kotlin.Unit
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.kt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.kt
new file mode 100644
index 0000000000000..3700e3f423698
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.kt
@@ -0,0 +1,3 @@
+// !DIAGNOSTICS: -MUST_BE_INITIALIZED
+fun <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T<!>> foo() {}
+val <T: <!CYCLIC_GENERIC_UPPER_BOUND!>T?<!>> prop: T
diff --git a/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.txt b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.txt
new file mode 100644
index 0000000000000..78109cf302724
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.txt
@@ -0,0 +1,4 @@
+package
+
+internal val </*0*/ T : [ERROR : Cyclic upper bound: T?]> prop: [ERROR : ?]
+internal fun </*0*/ T : [ERROR : Cyclic upper bound: T]> foo(): kotlin.Unit
diff --git a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
index 3d746285e0495..c3fba608824c5 100644
--- a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
@@ -10224,6 +10224,30 @@ public void testErrorsOnIbjectExpressionsAsParameters() throws Exception {
doTest(fileName);
}
+ @TestMetadata("itselfAsUpperBound.kt")
+ public void testItselfAsUpperBound() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/itselfAsUpperBound.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("itselfAsUpperBoundLocal.kt")
+ public void testItselfAsUpperBoundLocal() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundLocal.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("itselfAsUpperBoundMember.kt")
+ public void testItselfAsUpperBoundMember() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundMember.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("itselfAsUpperBoundNotNull.kt")
+ public void testItselfAsUpperBoundNotNull() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/itselfAsUpperBoundNotNull.kt");
+ doTest(fileName);
+ }
+
@TestMetadata("Jet11.kt")
public void testJet11() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/regressions/Jet11.kt");
|
a62eecc95a164415d8f924e1c88e2d144282395d
|
hbase
|
HBASE-7923 force unassign can confirm region- online on any RS to get rid of double assignments--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1464232 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
index 08358c3053a1..ea71218f3209 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
@@ -2267,11 +2267,14 @@ public UnassignRegionResponse unassignRegion(RpcController controller, UnassignR
return urr;
}
}
- if (force) {
- this.assignmentManager.regionOffline(hri);
+ LOG.debug("Close region " + hri.getRegionNameAsString()
+ + " on current location if it is online and reassign.force=" + force);
+ this.assignmentManager.unassign(hri, force);
+ if (!this.assignmentManager.getRegionStates().isRegionInTransition(hri)
+ && !this.assignmentManager.getRegionStates().isRegionAssigned(hri)) {
+ LOG.debug("Region " + hri.getRegionNameAsString()
+ + " is not online on any region server, reassigning it.");
assignRegion(hri);
- } else {
- this.assignmentManager.unassign(hri, force);
}
if (cpHost != null) {
cpHost.postUnassign(hri, force);
|
44d92d8eb39b176c23209f26a69bb1febae8e812
|
kotlin
|
Support for checking loaded descriptors agains an- expected txt file--
|
a
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/testData/lazyResolve/diagnostics/AbstractInAbstractClass.txt b/compiler/testData/lazyResolve/diagnostics/AbstractInAbstractClass.txt
new file mode 100644
index 0000000000000..6a33d58b255ad
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AbstractInAbstractClass.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+// <namespace name="abstract">
+namespace abstract
+
+internal abstract class abstract.MyAbstractClass : jet.Any {
+ public final /*constructor*/ fun <init>(): abstract.MyAbstractClass
+ internal final val a1: jet.Int
+ internal abstract val a2: jet.Int
+ internal abstract val a3: jet.Int
+ internal final val a: jet.Int
+ internal final var b1: jet.Int private set
+ internal abstract var b2: jet.Int private set
+ internal abstract var b3: jet.Int private set
+ internal final var b: jet.Int private set
+ internal final var c1: jet.Int
+ internal abstract var c2: jet.Int
+ internal abstract var c3: jet.Int
+ internal final var c: jet.Int
+ internal final val e1: jet.Int
+ internal abstract val e2: jet.Int
+ internal abstract val e3: jet.Int
+ internal final val e: jet.Int
+ internal final fun f(): jet.Tuple0
+ internal final fun g(): jet.Tuple0
+ internal abstract fun h(): jet.Tuple0
+ internal final var i1: jet.Int
+ internal final var i: jet.Int
+ internal abstract fun j(): jet.Tuple0
+ internal final var j1: jet.Int
+ internal final var j: jet.Int
+ internal final var k1: jet.Int
+ internal final var k: jet.Int
+ internal final var l1: jet.Int
+ internal final var l: jet.Int
+ internal final var n: jet.Int
+}
+// </namespace name="abstract">
diff --git a/compiler/testData/lazyResolve/diagnostics/AbstractInClass.txt b/compiler/testData/lazyResolve/diagnostics/AbstractInClass.txt
new file mode 100644
index 0000000000000..a80adecf038ff
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AbstractInClass.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+// <namespace name="abstract">
+namespace abstract
+
+internal final class abstract.MyClass : jet.Any {
+ public final /*constructor*/ fun <init>(): abstract.MyClass
+ internal final val a1: jet.Int
+ internal abstract val a2: jet.Int
+ internal abstract val a3: jet.Int
+ internal final val a: jet.Int
+ internal final var b1: jet.Int private set
+ internal abstract var b2: jet.Int private set
+ internal abstract var b3: jet.Int private set
+ internal final var b: jet.Int private set
+ internal final var c1: jet.Int
+ internal abstract var c2: jet.Int
+ internal abstract var c3: jet.Int
+ internal final var c: jet.Int
+ internal final val e1: jet.Int
+ internal abstract val e2: jet.Int
+ internal abstract val e3: jet.Int
+ internal final val e: jet.Int
+ internal final fun f(): jet.Tuple0
+ internal final fun g(): jet.Tuple0
+ internal abstract fun h(): jet.Tuple0
+ internal final var i1: jet.Int
+ internal final var i: jet.Int
+ internal abstract fun j(): jet.Tuple0
+ internal final var j1: jet.Int
+ internal final var j: jet.Int
+ internal final var k1: jet.Int
+ internal final var k: jet.Int
+ internal final var l1: jet.Int
+ internal final var l: jet.Int
+ internal final var n: jet.Int
+}
+// </namespace name="abstract">
diff --git a/compiler/testData/lazyResolve/diagnostics/AbstractInEnum.txt b/compiler/testData/lazyResolve/diagnostics/AbstractInEnum.txt
new file mode 100644
index 0000000000000..bfb4e84b3dee2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AbstractInEnum.txt
@@ -0,0 +1,41 @@
+namespace <root>
+
+// <namespace name="abstract">
+namespace abstract
+
+internal final enum class abstract.MyEnum : jet.Any {
+ public final /*constructor*/ fun <init>(): abstract.MyEnum
+ internal final val a1: jet.Int
+ internal abstract val a2: jet.Int
+ internal abstract val a3: jet.Int
+ internal final val a: jet.Int
+ internal final var b1: jet.Int private set
+ internal abstract var b2: jet.Int private set
+ internal abstract var b3: jet.Int private set
+ internal final var b: jet.Int private set
+ internal final var c1: jet.Int
+ internal abstract var c2: jet.Int
+ internal abstract var c3: jet.Int
+ internal final var c: jet.Int
+ internal final val e1: jet.Int
+ internal abstract val e2: jet.Int
+ internal abstract val e3: jet.Int
+ internal final val e: jet.Int
+ internal final fun f(): jet.Tuple0
+ internal final fun g(): jet.Tuple0
+ internal abstract fun h(): jet.Tuple0
+ internal final var i1: jet.Int
+ internal final var i: jet.Int
+ internal abstract fun j(): jet.Tuple0
+ internal final var j1: jet.Int
+ internal final var j: jet.Int
+ internal final var k1: jet.Int
+ internal final var k: jet.Int
+ internal final var l1: jet.Int
+ internal final var l: jet.Int
+ internal final var n: jet.Int
+ internal final object abstract.MyEnum.<class-object-for-MyEnum> {
+ internal final /*constructor*/ fun <init>(): abstract.MyEnum.<class-object-for-MyEnum>
+ }
+}
+// </namespace name="abstract">
diff --git a/compiler/testData/lazyResolve/diagnostics/AbstractInTrait.txt b/compiler/testData/lazyResolve/diagnostics/AbstractInTrait.txt
new file mode 100644
index 0000000000000..29cd19e059ff0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AbstractInTrait.txt
@@ -0,0 +1,37 @@
+namespace <root>
+
+// <namespace name="abstract">
+namespace abstract
+
+internal abstract trait abstract.MyTrait : jet.Any {
+ internal open val a1: jet.Int
+ internal abstract val a2: jet.Int
+ internal abstract val a3: jet.Int
+ internal abstract val a: jet.Int
+ internal open var b1: jet.Int private set
+ internal abstract var b2: jet.Int private set
+ internal abstract var b3: jet.Int private set
+ internal abstract var b: jet.Int private set
+ internal open var c1: jet.Int
+ internal abstract var c2: jet.Int
+ internal abstract var c3: jet.Int
+ internal open var c: jet.Int
+ internal open val e1: jet.Int
+ internal abstract val e2: jet.Int
+ internal abstract val e3: jet.Int
+ internal open val e: jet.Int
+ internal abstract fun f(): jet.Tuple0
+ internal open fun g(): jet.Tuple0
+ internal abstract fun h(): jet.Tuple0
+ internal open var i1: jet.Int
+ internal abstract var i: jet.Int
+ internal abstract fun j(): jet.Tuple0
+ internal open var j1: jet.Int
+ internal open var j: jet.Int
+ internal open var k1: jet.Int
+ internal abstract var k: jet.Int
+ internal open var l1: jet.Int
+ internal abstract var l: jet.Int
+ internal open var n: jet.Int
+}
+// </namespace name="abstract">
diff --git a/compiler/testData/lazyResolve/diagnostics/AnonymousInitializerVarAndConstructor.txt b/compiler/testData/lazyResolve/diagnostics/AnonymousInitializerVarAndConstructor.txt
new file mode 100644
index 0000000000000..07b40dc4936a3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AnonymousInitializerVarAndConstructor.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ w: jet.Int): A
+ internal final var c: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/AutoCreatedIt.txt b/compiler/testData/lazyResolve/diagnostics/AutoCreatedIt.txt
new file mode 100644
index 0000000000000..4a777dce0acf5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AutoCreatedIt.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal final class URI : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ body: jet.Any): URI
+ internal final val body: jet.Any
+ internal final fun to(/*0*/ dest: jet.String): jet.Tuple0
+}
+internal final fun bar(/*0*/ f: jet.Function2<jet.Int, jet.Int, jet.Int>): jet.Tuple0
+internal final fun bar1(/*0*/ f: jet.Function1<jet.Int, jet.Int>): jet.Tuple0
+internal final fun bar2(/*0*/ f: jet.Function0<jet.Int>): jet.Tuple0
+internal final fun jet.String.on(/*0*/ predicate: jet.Function1<URI, jet.Boolean>): URI
+internal final fun text(): jet.Tuple0
+internal final fun jet.String.to(/*0*/ dest: jet.String): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/AutocastAmbiguitites.txt b/compiler/testData/lazyResolve/diagnostics/AutocastAmbiguitites.txt
new file mode 100644
index 0000000000000..3994283420339
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AutocastAmbiguitites.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract trait B : jet.Any {
+ internal open fun bar(): jet.Tuple0
+}
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(): C
+ internal final fun bar(): jet.Tuple0
+}
+internal final fun test(/*0*/ a: jet.Any?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/AutocastsForStableIdentifiers.txt b/compiler/testData/lazyResolve/diagnostics/AutocastsForStableIdentifiers.txt
new file mode 100644
index 0000000000000..70a42c9ba6ced
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/AutocastsForStableIdentifiers.txt
@@ -0,0 +1,28 @@
+namespace <root>
+
+// <namespace name="example">
+namespace example
+
+// <namespace name="ns">
+namespace ns
+
+internal final val y: jet.Any?
+// </namespace name="ns">
+internal final class example.AClass : jet.Any {
+ public final /*constructor*/ fun <init>(): example.AClass
+ internal final object example.AClass.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): example.AClass.<no name provided>
+ internal final val y: jet.Any?
+ }
+}
+internal open class example.C : jet.Any {
+ public final /*constructor*/ fun <init>(): example.C
+ internal final fun foo(): jet.Tuple0
+}
+internal abstract trait example.T : jet.Any {
+}
+internal final val Obj: example.Obj
+internal final val x: jet.Any?
+internal final fun jet.Any?.foo(): jet.Int
+internal final fun jet.Any?.vars(/*0*/ a: jet.Any?): jet.Int
+// </namespace name="example">
diff --git a/compiler/testData/lazyResolve/diagnostics/Basic.txt b/compiler/testData/lazyResolve/diagnostics/Basic.txt
new file mode 100644
index 0000000000000..9462dd9d5a717
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Basic.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final val x: jet.Int
+}
+internal final fun foo(/*0*/ u: jet.Tuple0): jet.Int
+internal final fun foo1(): jet.Tuple0
+internal final fun test(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/BinaryCallsOnNullableValues.txt b/compiler/testData/lazyResolve/diagnostics/BinaryCallsOnNullableValues.txt
new file mode 100644
index 0000000000000..c2ce323156deb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/BinaryCallsOnNullableValues.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal final class B : jet.Any {
+ public final /*constructor*/ fun <init>(): B
+}
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(): C
+}
+internal final fun f(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Bounds.txt b/compiler/testData/lazyResolve/diagnostics/Bounds.txt
new file mode 100644
index 0000000000000..83f61dc32506a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Bounds.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+// <namespace name="boundsWithSubstitutors">
+namespace boundsWithSubstitutors
+
+internal open class boundsWithSubstitutors.A</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): boundsWithSubstitutors.A<T>
+}
+internal final class boundsWithSubstitutors.B</*0*/ X : boundsWithSubstitutors.A<X>> : jet.Any {
+ public final /*constructor*/ fun </*0*/ X : boundsWithSubstitutors.A<X>><init>(): boundsWithSubstitutors.B<X>
+}
+internal final class boundsWithSubstitutors.C : boundsWithSubstitutors.A<boundsWithSubstitutors.C> {
+ public final /*constructor*/ fun <init>(): boundsWithSubstitutors.C
+}
+internal final class boundsWithSubstitutors.X</*0*/ A : jet.Any?, /*1*/ B : A> : jet.Any {
+ public final /*constructor*/ fun </*0*/ A : jet.Any?, /*1*/ B : A><init>(): boundsWithSubstitutors.X<A, B>
+}
+internal final val a: boundsWithSubstitutors.B<boundsWithSubstitutors.C>
+internal final val a1: boundsWithSubstitutors.B<jet.Int>
+internal final val b: boundsWithSubstitutors.X<jet.Any, boundsWithSubstitutors.X<boundsWithSubstitutors.A<boundsWithSubstitutors.C>, boundsWithSubstitutors.C>>
+internal final val b0: boundsWithSubstitutors.X<jet.Any, jet.Any?>
+internal final val b1: boundsWithSubstitutors.X<jet.Any, boundsWithSubstitutors.X<boundsWithSubstitutors.A<boundsWithSubstitutors.C>, jet.String>>
+// </namespace name="boundsWithSubstitutors">
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal open class B</*0*/ T : A> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : A><init>(): B<T>
+}
+internal abstract class C</*0*/ T : B<jet.Int>, /*1*/ X : jet.Function1<B<jet.Char>, jet.Tuple2<out B<jet.Any>, out B<A>>>> : B<jet.Any> {
+ public final /*constructor*/ fun </*0*/ T : B<jet.Int>, /*1*/ X : jet.Function1<B<jet.Char>, jet.Tuple2<out B<jet.Any>, out B<A>>>><init>(): C<T, X>
+ internal final val a: B<jet.Char>
+ internal abstract val x: jet.Function1<B<jet.Char>, B<jet.Any>>
+}
+internal final fun </*0*/ T : jet.Int?>bar(): jet.Tuple0
+internal final fun </*0*/ T : jet.Int>jet.Int.buzz(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any>foo(): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/BreakContinue.txt b/compiler/testData/lazyResolve/diagnostics/BreakContinue.txt
new file mode 100644
index 0000000000000..fa81ecd84b4c1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/BreakContinue.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(): C
+ internal final fun containsBreak(/*0*/ a: jet.String?, /*1*/ b: jet.String?): jet.Tuple0
+ internal final fun containsBreakInsideLoopWithLabel(/*0*/ a: jet.String?, /*1*/ array: jet.Array<jet.Int>): jet.Tuple0
+ internal final fun containsBreakToOuterLoop(/*0*/ a: jet.String?, /*1*/ b: jet.String?): jet.Tuple0
+ internal final fun containsBreakWithLabel(/*0*/ a: jet.String?): jet.Tuple0
+ internal final fun containsIllegalBreak(/*0*/ a: jet.String?): jet.Tuple0
+ internal final fun f(/*0*/ a: jet.Boolean, /*1*/ b: jet.Boolean): jet.Tuple0
+ internal final fun notContainsBreak(/*0*/ a: jet.String?, /*1*/ b: jet.String?): jet.Tuple0
+ internal final fun unresolvedBreak(/*0*/ a: jet.String?, /*1*/ array: jet.Array<jet.Int>): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/Builders.txt b/compiler/testData/lazyResolve/diagnostics/Builders.txt
new file mode 100644
index 0000000000000..0644ee99f958a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Builders.txt
@@ -0,0 +1,193 @@
+namespace <root>
+
+// <namespace name="html">
+namespace html
+
+internal final class html.A : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.A
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ public final var href: jet.String?
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final class html.B : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.B
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final class html.Body : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.Body
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal abstract class html.BodyTag : html.TagWithText {
+ public final /*constructor*/ fun <init>(/*0*/ name: jet.String): html.BodyTag
+ internal final fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal abstract trait html.Element : jet.Any {
+ internal abstract fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+}
+internal final class html.H1 : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.H1
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final class html.HTML : html.TagWithText {
+ public final /*constructor*/ fun <init>(): html.HTML
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final fun body(/*0*/ init: jet.ExtensionFunction0<html.Body, jet.Tuple0>): html.Body
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final fun head(/*0*/ init: jet.ExtensionFunction0<html.Head, jet.Tuple0>): html.Head
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+}
+internal final class html.Head : html.TagWithText {
+ public final /*constructor*/ fun <init>(): html.Head
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final fun title(/*0*/ init: jet.ExtensionFunction0<html.Title, jet.Tuple0>): html.Title
+}
+internal final class html.LI : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.LI
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final class html.P : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.P
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal abstract class html.Tag : html.Element {
+ public final /*constructor*/ fun <init>(/*0*/ name: jet.String): html.Tag
+ internal final val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final val children: java.util.ArrayList<html.Element>
+ protected final fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ internal final val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ private final fun renderAttributes(): jet.String?
+}
+internal abstract class html.TagWithText : html.Tag {
+ public final /*constructor*/ fun <init>(/*0*/ name: jet.String): html.TagWithText
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+}
+internal final class html.TextElement : html.Element {
+ public final /*constructor*/ fun <init>(/*0*/ text: jet.String): html.TextElement
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final val text: jet.String
+}
+internal final class html.Title : html.TagWithText {
+ public final /*constructor*/ fun <init>(): html.Title
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final override /*1*/ val name: jet.String
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+}
+internal final class html.UL : html.BodyTag {
+ public final /*constructor*/ fun <init>(): html.UL
+ internal final override /*1*/ fun a(/*0*/ href: jet.String, /*1*/ init: jet.ExtensionFunction0<html.A, jet.Tuple0>): jet.Tuple0
+ internal final override /*1*/ val attributes: java.util.HashMap<jet.String, jet.String>
+ internal final override /*1*/ fun b(/*0*/ init: jet.ExtensionFunction0<html.B, jet.Tuple0>): html.B
+ internal final override /*1*/ val children: java.util.ArrayList<html.Element>
+ internal final override /*1*/ fun h1(/*0*/ init: jet.ExtensionFunction0<html.H1, jet.Tuple0>): html.H1
+ protected final override /*1*/ fun </*0*/ T : html.Element>initTag(/*0*/ tag: T, /*1*/ init: jet.ExtensionFunction0<T, jet.Tuple0>): T
+ invisible_fake final override /*1*/ fun renderAttributes(): jet.String?
+ internal final override /*1*/ fun jet.String.plus(): jet.Tuple0
+ internal final fun li(/*0*/ init: jet.ExtensionFunction0<html.LI, jet.Tuple0>): html.LI
+ internal final override /*1*/ val name: jet.String
+ internal final override /*1*/ fun p(/*0*/ init: jet.ExtensionFunction0<html.P, jet.Tuple0>): html.P
+ internal open override /*1*/ fun render(/*0*/ builder: java.lang.StringBuilder, /*1*/ indent: jet.String): jet.Tuple0
+ internal final override /*1*/ fun ul(/*0*/ init: jet.ExtensionFunction0<html.UL, jet.Tuple0>): html.UL
+}
+internal final fun html(/*0*/ init: jet.ExtensionFunction0<html.HTML, jet.Tuple0>): html.HTML
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun print(/*0*/ message: jet.Any?): jet.Tuple0
+internal final fun println(/*0*/ message: jet.Any?): jet.Tuple0
+internal final fun </*0*/ K : jet.Any?, /*1*/ V : jet.Any?>java.util.Map<K, V>.set(/*0*/ key: K, /*1*/ value: V): V?
+// </namespace name="html">
diff --git a/compiler/testData/lazyResolve/diagnostics/Casts.txt b/compiler/testData/lazyResolve/diagnostics/Casts.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Casts.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/CharacterLiterals.txt b/compiler/testData/lazyResolve/diagnostics/CharacterLiterals.txt
new file mode 100644
index 0000000000000..e35be5298b9a3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/CharacterLiterals.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(/*0*/ c: jet.Char): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/ClassObjectCannotAccessClassFields.txt b/compiler/testData/lazyResolve/diagnostics/ClassObjectCannotAccessClassFields.txt
new file mode 100644
index 0000000000000..74e6380542bfd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ClassObjectCannotAccessClassFields.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final val x: jet.Int
+ internal final object A.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): A.<no name provided>
+ internal final val y: [ERROR : Type for x]
+ }
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/ClassObjects.txt b/compiler/testData/lazyResolve/diagnostics/ClassObjects.txt
new file mode 100644
index 0000000000000..0c27cc88be657
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ClassObjects.txt
@@ -0,0 +1,23 @@
+namespace <root>
+
+// <namespace name="Jet86">
+namespace Jet86
+
+internal final class Jet86.A : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet86.A
+ internal final object Jet86.A.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Jet86.A.<no name provided>
+ internal final val x: jet.Int
+ }
+}
+internal final class Jet86.B : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet86.B
+ internal final val x: jet.Int
+}
+internal final val a: jet.Int
+internal final val b: Jet86.b
+internal final val c: jet.Int
+internal final val d: [ERROR : Type for b.x]
+internal final val s: java.lang.System
+internal final fun test(): jet.Tuple0
+// </namespace name="Jet86">
diff --git a/compiler/testData/lazyResolve/diagnostics/Constants.txt b/compiler/testData/lazyResolve/diagnostics/Constants.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Constants.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/CovariantOverrideType.txt b/compiler/testData/lazyResolve/diagnostics/CovariantOverrideType.txt
new file mode 100644
index 0000000000000..a8b2c6cd8ada9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/CovariantOverrideType.txt
@@ -0,0 +1,23 @@
+namespace <root>
+
+internal abstract trait A : jet.Any {
+ internal abstract val a1: jet.Int
+ internal abstract val a: jet.Int
+ internal open fun foo(): jet.Int
+ internal open fun foo1(): jet.Int
+ internal open fun foo2(): jet.Int
+ internal abstract fun </*0*/ T : jet.Any?>g(): T
+ internal abstract fun </*0*/ T : jet.Any?>g1(): T
+ internal abstract val </*0*/ T : jet.Any?> g: jet.Iterator<T>
+}
+internal abstract class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ val a1: jet.Double
+ internal open override /*1*/ val a: jet.Double
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ fun foo1(): jet.Int
+ internal open override /*1*/ fun foo2(): jet.Tuple0
+ internal abstract override /*1*/ fun </*0*/ X : jet.Any?>g(): jet.Int
+ internal abstract override /*1*/ fun </*0*/ X : jet.Any?>g1(): java.util.List<X>
+ internal abstract override /*1*/ val </*0*/ X : jet.Any?> g: jet.Iterator<jet.Int>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/DanglingFunctionLiteral.txt b/compiler/testData/lazyResolve/diagnostics/DanglingFunctionLiteral.txt
new file mode 100644
index 0000000000000..1903119e88998
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DanglingFunctionLiteral.txt
@@ -0,0 +1,18 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+ private final val builder: java.lang.StringBuilder
+}
+internal final class Foo1 : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo1
+ private final val builder: [ERROR : Type for StringBuilder("sdfsd")
+
+ {
+ }]
+}
+internal final fun foo(): jet.Function0<[ERROR : <return type>]>
+internal final fun foo1(): jet.Function0<jet.Function0<jet.Tuple0>>
+internal final fun println(): jet.Tuple0
+internal final fun println(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun println(/*0*/ s: jet.Byte): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/DeferredTypes.txt b/compiler/testData/lazyResolve/diagnostics/DeferredTypes.txt
new file mode 100644
index 0000000000000..ebfff80bc3a1b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DeferredTypes.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal abstract trait T : jet.Any {
+ internal open val a: [ERROR : <ERROR FUNCTION RETURN TYPE>]
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/DiamondFunction.txt b/compiler/testData/lazyResolve/diagnostics/DiamondFunction.txt
new file mode 100644
index 0000000000000..8dbb888ad89b3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DiamondFunction.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal open class Base : jet.Any {
+ public final /*constructor*/ fun <init>(): Base
+ internal final fun f(): jet.Int
+}
+internal final class Diamond : Left, Right {
+ public final /*constructor*/ fun <init>(): Diamond
+ internal final override /*2*/ fun f(): jet.Int
+}
+internal open class Left : Base {
+ public final /*constructor*/ fun <init>(): Left
+ internal final override /*1*/ fun f(): jet.Int
+}
+internal abstract trait Right : Base {
+ internal final override /*1*/ fun f(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/DiamondFunctionGeneric.txt b/compiler/testData/lazyResolve/diagnostics/DiamondFunctionGeneric.txt
new file mode 100644
index 0000000000000..7bc103a2e3a57
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DiamondFunctionGeneric.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal open class Base</*0*/ P : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ P : jet.Any?><init>(): Base<P>
+ internal final fun f(): jet.Int
+}
+internal final class Diamond</*0*/ P : jet.Any?> : Left<P>, Right<P> {
+ public final /*constructor*/ fun </*0*/ P : jet.Any?><init>(): Diamond<P>
+ internal final override /*2*/ fun f(): jet.Int
+}
+internal open class Left</*0*/ P : jet.Any?> : Base<P> {
+ public final /*constructor*/ fun </*0*/ P : jet.Any?><init>(): Left<P>
+ internal final override /*1*/ fun f(): jet.Int
+}
+internal abstract trait Right</*0*/ P : jet.Any?> : Base<P> {
+ internal final override /*1*/ fun f(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/DiamondProperty.txt b/compiler/testData/lazyResolve/diagnostics/DiamondProperty.txt
new file mode 100644
index 0000000000000..9481d4cb5c354
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/DiamondProperty.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal open class Base : jet.Any {
+ public final /*constructor*/ fun <init>(): Base
+ internal final var v: jet.Int
+}
+internal final class Diamond : Left, Right {
+ public final /*constructor*/ fun <init>(): Diamond
+ internal final override /*2*/ var v: jet.Int
+}
+internal open class Left : Base {
+ public final /*constructor*/ fun <init>(): Left
+ internal final override /*1*/ var v: jet.Int
+}
+internal abstract trait Right : Base {
+ internal final override /*1*/ var v: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/Dollar.txt b/compiler/testData/lazyResolve/diagnostics/Dollar.txt
new file mode 100644
index 0000000000000..4cd12fc808be5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Dollar.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="dollar">
+namespace dollar
+
+internal open class dollar.$ : jet.Any {
+ public final /*constructor*/ fun <init>(): dollar.$
+}
+internal open class dollar.$$ : dollar.$ {
+ public open fun $$$$$$(): dollar.$$$$$?
+ internal final val $$$: dollar.$$$$$?
+ public final /*constructor*/ fun <init>(/*0*/ $$$$: dollar.$$$$$?): dollar.$$
+}
+internal open class dollar.$$$$$ : jet.Any {
+ public final /*constructor*/ fun <init>(): dollar.$$$$$
+}
+// </namespace name="dollar">
diff --git a/compiler/testData/lazyResolve/diagnostics/ForRangeConventions.txt b/compiler/testData/lazyResolve/diagnostics/ForRangeConventions.txt
new file mode 100644
index 0000000000000..e159db65aeb05
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ForRangeConventions.txt
@@ -0,0 +1,76 @@
+namespace <root>
+
+internal abstract class AmbiguousHasNextIterator : jet.Any {
+ public final /*constructor*/ fun <init>(): AmbiguousHasNextIterator
+ internal abstract fun hasNext(): jet.Boolean
+ internal final val hasNext: jet.Boolean
+ internal abstract fun next(): jet.Int
+}
+internal abstract class GoodIterator : jet.Any {
+ public final /*constructor*/ fun <init>(): GoodIterator
+ internal abstract fun hasNext(): jet.Boolean
+ internal abstract fun next(): jet.Int
+}
+internal abstract class ImproperIterator1 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator1
+ internal abstract fun hasNext(): jet.Boolean
+}
+internal abstract class ImproperIterator2 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator2
+ internal abstract fun next(): jet.Boolean
+}
+internal abstract class ImproperIterator3 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator3
+ internal abstract fun hasNext(): jet.Int
+ internal abstract fun next(): jet.Int
+}
+internal abstract class ImproperIterator4 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator4
+ internal final val hasNext: jet.Int
+ internal abstract fun next(): jet.Int
+}
+internal abstract class ImproperIterator5 : jet.Any {
+ public final /*constructor*/ fun <init>(): ImproperIterator5
+ internal abstract val jet.String.hasNext: jet.Boolean
+ internal abstract fun next(): jet.Int
+}
+internal final class NotRange1 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange1
+}
+internal abstract class NotRange2 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange2
+ internal abstract fun iterator(): jet.Tuple0
+}
+internal abstract class NotRange3 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange3
+ internal abstract fun iterator(): ImproperIterator1
+}
+internal abstract class NotRange4 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange4
+ internal abstract fun iterator(): ImproperIterator2
+}
+internal abstract class NotRange5 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange5
+ internal abstract fun iterator(): ImproperIterator3
+}
+internal abstract class NotRange6 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange6
+ internal abstract fun iterator(): AmbiguousHasNextIterator
+}
+internal abstract class NotRange7 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange7
+ internal abstract fun iterator(): ImproperIterator3
+}
+internal abstract class NotRange8 : jet.Any {
+ public final /*constructor*/ fun <init>(): NotRange8
+ internal abstract fun iterator(): ImproperIterator5
+}
+internal abstract class Range0 : jet.Any {
+ public final /*constructor*/ fun <init>(): Range0
+ internal abstract fun iterator(): GoodIterator
+}
+internal abstract class Range1 : jet.Any {
+ public final /*constructor*/ fun <init>(): Range1
+ internal abstract fun iterator(): java.util.Iterator<jet.Int>
+}
+internal final fun test(/*0*/ notRange1: NotRange1, /*1*/ notRange2: NotRange2, /*2*/ notRange3: NotRange3, /*3*/ notRange4: NotRange4, /*4*/ notRange5: NotRange5, /*5*/ notRange6: NotRange6, /*6*/ notRange7: NotRange7, /*7*/ notRange8: NotRange8, /*8*/ range0: Range0, /*9*/ range1: Range1): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/FunctionCalleeExpressions.txt b/compiler/testData/lazyResolve/diagnostics/FunctionCalleeExpressions.txt
new file mode 100644
index 0000000000000..b053169382ca2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/FunctionCalleeExpressions.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="foo">
+namespace foo
+
+internal final fun f(): jet.ExtensionFunction0<jet.Int, jet.Tuple0>
+internal final fun jet.Any.foo(): jet.Function0<jet.Tuple0>
+internal final fun jet.Any.foo1(): jet.Function1<jet.Int, jet.Tuple0>
+internal final fun foo2(): jet.Function1<jet.Function0<jet.Tuple0>, jet.Tuple0>
+internal final fun </*0*/ T : jet.Any?>fooT1(/*0*/ t: T): jet.Function0<T>
+internal final fun </*0*/ T : jet.Any?>fooT2(): jet.Function1<T, T>
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun main1(): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="foo">
diff --git a/compiler/testData/lazyResolve/diagnostics/GenericArgumentConsistency.txt b/compiler/testData/lazyResolve/diagnostics/GenericArgumentConsistency.txt
new file mode 100644
index 0000000000000..d7b4f71d64177
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/GenericArgumentConsistency.txt
@@ -0,0 +1,72 @@
+namespace <root>
+
+// <namespace name="x">
+namespace x
+
+internal abstract trait x.AA1</*0*/ out T : jet.Any?> : jet.Any {
+}
+internal abstract trait x.AB1 : x.AA1<jet.Int> {
+}
+internal abstract trait x.AB2 : x.AA1<jet.Number>, x.AB1, x.AB3 {
+}
+internal abstract trait x.AB3 : x.AA1<jet.Comparable<jet.Int>> {
+}
+// </namespace name="x">
+// <namespace name="x2">
+namespace x2
+
+internal abstract trait x2.AA1</*0*/ out T : jet.Any?> : jet.Any {
+}
+internal abstract trait x2.AB1 : x2.AA1<jet.Any> {
+}
+internal abstract trait x2.AB2 : x2.AA1<jet.Number>, x2.AB1, x2.AB3 {
+}
+internal abstract trait x2.AB3 : x2.AA1<jet.Comparable<jet.Int>> {
+}
+// </namespace name="x2">
+// <namespace name="x3">
+namespace x3
+
+internal abstract trait x3.AA1</*0*/ in T : jet.Any?> : jet.Any {
+}
+internal abstract trait x3.AB1 : x3.AA1<jet.Any> {
+}
+internal abstract trait x3.AB2 : x3.AA1<jet.Number>, x3.AB1, x3.AB3 {
+}
+internal abstract trait x3.AB3 : x3.AA1<jet.Comparable<jet.Int>> {
+}
+// </namespace name="x3">
+// <namespace name="sx2">
+namespace sx2
+
+internal abstract trait sx2.AA1</*0*/ in T : jet.Any?> : jet.Any {
+}
+internal abstract trait sx2.AB1 : sx2.AA1<jet.Int> {
+}
+internal abstract trait sx2.AB2 : sx2.AA1<jet.Number>, sx2.AB1, sx2.AB3 {
+}
+internal abstract trait sx2.AB3 : sx2.AA1<jet.Comparable<jet.Int>> {
+}
+// </namespace name="sx2">
+internal abstract trait A</*0*/ in T : jet.Any?> : jet.Any {
+}
+internal abstract trait A1</*0*/ out T : jet.Any?> : jet.Any {
+}
+internal abstract trait B</*0*/ T : jet.Any?> : A<jet.Int> {
+}
+internal abstract trait B1 : A1<jet.Int> {
+}
+internal abstract trait B2 : A1<jet.Any>, B1 {
+}
+internal abstract trait BA1</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait BB1 : BA1<jet.Int> {
+}
+internal abstract trait BB2 : BA1<jet.Any>, BB1 {
+}
+internal abstract trait C</*0*/ T : jet.Any?> : B<T>, A<T> {
+}
+internal abstract trait C1</*0*/ T : jet.Any?> : B<T>, A<jet.Any> {
+}
+internal abstract trait D : C<jet.Boolean>, B<jet.Double> {
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/GenericFunctionIsLessSpecific.txt b/compiler/testData/lazyResolve/diagnostics/GenericFunctionIsLessSpecific.txt
new file mode 100644
index 0000000000000..e33defc249c35
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/GenericFunctionIsLessSpecific.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun foo(/*0*/ i: jet.Int): jet.Int
+internal final fun </*0*/ T : jet.Any?>foo(/*0*/ t: T): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/IllegalModifiers.txt b/compiler/testData/lazyResolve/diagnostics/IllegalModifiers.txt
new file mode 100644
index 0000000000000..cb266716a9b64
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/IllegalModifiers.txt
@@ -0,0 +1,21 @@
+namespace <root>
+
+// <namespace name="illegal_modifiers">
+namespace illegal_modifiers
+
+internal abstract class illegal_modifiers.A : jet.Any {
+ public final /*constructor*/ fun <init>(): illegal_modifiers.A
+ internal abstract fun f(): jet.Tuple0
+ internal abstract fun g(): jet.Tuple0
+ internal open fun h(): jet.Tuple0
+ internal open var r: jet.String protected set
+}
+internal final class illegal_modifiers.FinalClass : jet.Any {
+ public final /*constructor*/ fun <init>(): illegal_modifiers.FinalClass
+ internal open fun foo(): jet.Tuple0
+ internal final val i: jet.Int
+ internal final var j: jet.Int
+}
+internal final trait illegal_modifiers.T : jet.Any {
+}
+// </namespace name="illegal_modifiers">
diff --git a/compiler/testData/lazyResolve/diagnostics/ImportResolutionOrder.txt b/compiler/testData/lazyResolve/diagnostics/ImportResolutionOrder.txt
new file mode 100644
index 0000000000000..0619174a86c54
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ImportResolutionOrder.txt
@@ -0,0 +1,26 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final val x: b.X
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final class b.X : jet.Any {
+ public final /*constructor*/ fun <init>(): b.X
+}
+// </namespace name="b">
+// <namespace name="c">
+namespace c
+
+internal final val x: d.X
+// </namespace name="c">
+// <namespace name="d">
+namespace d
+
+internal final class d.X : jet.Any {
+ public final /*constructor*/ fun <init>(): d.X
+}
+// </namespace name="d">
diff --git a/compiler/testData/lazyResolve/diagnostics/IncDec.txt b/compiler/testData/lazyResolve/diagnostics/IncDec.txt
new file mode 100644
index 0000000000000..248cb16f4fd0d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/IncDec.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+internal final class IncDec : jet.Any {
+ public final /*constructor*/ fun <init>(): IncDec
+ internal final fun dec(): IncDec
+ internal final fun inc(): IncDec
+}
+internal final class UnitIncDec : jet.Any {
+ public final /*constructor*/ fun <init>(): UnitIncDec
+ internal final fun dec(): jet.Tuple0
+ internal final fun inc(): jet.Tuple0
+}
+internal final class WrongIncDec : jet.Any {
+ public final /*constructor*/ fun <init>(): WrongIncDec
+ internal final fun dec(): jet.Int
+ internal final fun inc(): jet.Int
+}
+internal final fun testIncDec(): jet.Tuple0
+internal final fun testUnitIncDec(): jet.Tuple0
+internal final fun testWrongIncDec(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/IncorrectCharacterLiterals.txt b/compiler/testData/lazyResolve/diagnostics/IncorrectCharacterLiterals.txt
new file mode 100644
index 0000000000000..a951870ff4ce0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/IncorrectCharacterLiterals.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun ff(): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/InferNullabilityInThenBlock.txt b/compiler/testData/lazyResolve/diagnostics/InferNullabilityInThenBlock.txt
new file mode 100644
index 0000000000000..0c15629d47ff7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/InferNullabilityInThenBlock.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun ff(/*0*/ a: jet.String): jet.Int
+internal final fun gg(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/IsExpressions.txt b/compiler/testData/lazyResolve/diagnostics/IsExpressions.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/IsExpressions.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/LValueAssignment.txt b/compiler/testData/lazyResolve/diagnostics/LValueAssignment.txt
new file mode 100644
index 0000000000000..8632f0617bc51
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/LValueAssignment.txt
@@ -0,0 +1,47 @@
+namespace <root>
+
+// <namespace name="lvalue_assignment">
+namespace lvalue_assignment
+
+internal final class lvalue_assignment.A : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.A
+ internal final var a: jet.Int
+}
+internal abstract class lvalue_assignment.Ab : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.Ab
+ internal abstract fun getArray(): jet.Array<jet.Int>
+}
+internal open class lvalue_assignment.B : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.B
+ internal final var b: jet.Int
+ internal final val c: jet.Int
+}
+internal final class lvalue_assignment.C : lvalue_assignment.B {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.C
+ internal final override /*1*/ var b: jet.Int
+ internal final fun bar(/*0*/ c: lvalue_assignment.C): jet.Tuple0
+ internal final override /*1*/ val c: jet.Int
+ internal final fun foo(/*0*/ c: lvalue_assignment.C): jet.Tuple0
+ internal final fun foo1(/*0*/ c: lvalue_assignment.C): jet.Tuple0
+ internal final var x: jet.Int
+}
+internal final class lvalue_assignment.D : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.D
+ internal final class lvalue_assignment.D.B : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.D.B
+ internal final fun foo(): jet.Tuple0
+ }
+}
+internal final class lvalue_assignment.Test : jet.Any {
+ public final /*constructor*/ fun <init>(): lvalue_assignment.Test
+ internal final fun testArrays(/*0*/ a: jet.Array<jet.Int>, /*1*/ ab: lvalue_assignment.Ab): jet.Tuple0
+ internal final fun testIllegalValues(): jet.Tuple0
+ internal final fun testVariables(): jet.Tuple0
+ internal final fun testVariables1(): jet.Tuple0
+}
+internal final fun canBe(/*0*/ i: jet.Int, /*1*/ j: jet.Int): jet.Tuple0
+internal final fun canBe2(/*0*/ j: jet.Int): jet.Tuple0
+internal final fun cannotBe(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun jet.Array<jet.Int>.checkThis(): jet.Tuple0
+internal final fun getInt(): jet.Int
+// </namespace name="lvalue_assignment">
diff --git a/compiler/testData/lazyResolve/diagnostics/MergePackagesWithJava.txt b/compiler/testData/lazyResolve/diagnostics/MergePackagesWithJava.txt
new file mode 100644
index 0000000000000..3c0a25e9c0e45
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/MergePackagesWithJava.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="java">
+namespace java
+
+internal final val c: java.lang.Class<out jet.Any?>?
+internal final val </*0*/ T : jet.Any?> jet.Array<T>?.length: jet.Int
+// </namespace name="java">
diff --git a/compiler/testData/lazyResolve/diagnostics/MultilineStringTemplates.txt b/compiler/testData/lazyResolve/diagnostics/MultilineStringTemplates.txt
new file mode 100644
index 0000000000000..00b44512421d5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/MultilineStringTemplates.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun box(): jet.String
+internal final fun new(): jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/MultipleBounds.txt b/compiler/testData/lazyResolve/diagnostics/MultipleBounds.txt
new file mode 100644
index 0000000000000..cce7292b9c8e3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/MultipleBounds.txt
@@ -0,0 +1,54 @@
+namespace <root>
+
+// <namespace name="Jet87">
+namespace Jet87
+
+internal open class Jet87.A : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet87.A
+ internal final fun foo(): jet.Int
+}
+internal abstract trait Jet87.B : jet.Any {
+ internal open fun bar(): jet.Double
+}
+internal final class Jet87.Bar</*0*/ T : Jet87.Foo> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.Foo><init>(): Jet87.Bar<T>
+}
+internal final class Jet87.Buzz</*0*/ T : Jet87.Bar<jet.Int> & [ERROR : nioho]> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.Bar<jet.Int> & [ERROR : nioho]><init>(): Jet87.Buzz<T>
+}
+internal final class Jet87.C : Jet87.A, Jet87.B {
+ public final /*constructor*/ fun <init>(): Jet87.C
+ internal open override /*1*/ fun bar(): jet.Double
+ internal final override /*1*/ fun foo(): jet.Int
+}
+internal final class Jet87.D : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet87.D
+ internal final object Jet87.D.<no name provided> : Jet87.A, Jet87.B {
+ internal final /*constructor*/ fun <init>(): Jet87.D.<no name provided>
+ internal open override /*1*/ fun bar(): jet.Double
+ internal final override /*1*/ fun foo(): jet.Int
+ }
+}
+internal final class Jet87.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Jet87.Foo
+}
+internal final class Jet87.Test</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): Jet87.Test<T>
+}
+internal final class Jet87.Test1</*0*/ T : Jet87.A & Jet87.B> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.A & Jet87.B><init>(): Jet87.Test1<T>
+ internal final fun test(/*0*/ t: T): jet.Tuple0
+}
+internal final class Jet87.X</*0*/ T : Jet87.Foo> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.Foo><init>(): Jet87.X<T>
+}
+internal final class Jet87.Y</*0*/ T : Jet87.Bar<Jet87.Foo> & Jet87.Foo> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : Jet87.Bar<Jet87.Foo> & Jet87.Foo><init>(): Jet87.Y<T>
+}
+internal final val t1: jet.Tuple0
+internal final val t2: jet.Tuple0
+internal final val t3: jet.Tuple0
+internal final val </*0*/ T : jet.Any?, /*1*/ B : T> x: jet.Int
+internal final fun test(): jet.Tuple0
+internal final fun </*0*/ T : Jet87.A & Jet87.B>test2(/*0*/ t: T): jet.Tuple0
+// </namespace name="Jet87">
diff --git a/compiler/testData/lazyResolve/diagnostics/NamedArgumentsAndDefaultValues.txt b/compiler/testData/lazyResolve/diagnostics/NamedArgumentsAndDefaultValues.txt
new file mode 100644
index 0000000000000..a69eda6ffd427
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/NamedArgumentsAndDefaultValues.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int = ?, /*1*/ y: jet.Int = ?, /*2*/ z: jet.String): jet.Tuple0
+internal final fun foo(/*0*/ a: jet.Int = ?, /*1*/ b: jet.String = ?): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/NamespaceInExpressionPosition.txt b/compiler/testData/lazyResolve/diagnostics/NamespaceInExpressionPosition.txt
new file mode 100644
index 0000000000000..a4f7602345f66
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/NamespaceInExpressionPosition.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="foo">
+namespace foo
+
+internal final class foo.X : jet.Any {
+ public final /*constructor*/ fun <init>(): foo.X
+}
+internal final val s: [ERROR : Type for java]
+internal final val ss: java.lang.System
+internal final val sss: foo.X
+internal final val xs: [ERROR : Type for lang]
+internal final val xss: java.lang.System
+internal final val xsss: foo.X
+internal final val xssss: [ERROR : Type for foo]
+// </namespace name="foo">
diff --git a/compiler/testData/lazyResolve/diagnostics/NamespaceQualified.txt b/compiler/testData/lazyResolve/diagnostics/NamespaceQualified.txt
new file mode 100644
index 0000000000000..933451333f87c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/NamespaceQualified.txt
@@ -0,0 +1,48 @@
+namespace <root>
+
+// <namespace name="foobar">
+namespace foobar
+
+// <namespace name="a">
+namespace a
+
+internal final val a: java.util.List<jet.Int>?
+internal final val a1: [ERROR : List<Int>]
+internal final val b: java.util.List<jet.Int>?
+internal final val b1: [ERROR : util.List<Int>]
+// </namespace name="a">
+internal abstract class foobar.Collection</*0*/ E : jet.Any?> : jet.Iterable<E> {
+ public final /*constructor*/ fun </*0*/ E : jet.Any?><init>(): foobar.Collection<E>
+ internal final fun </*0*/ O : jet.Any?>iterate(/*0*/ iteratee: foobar.Iteratee<E, O>): O
+ public abstract override /*1*/ fun iterator(): jet.Iterator<E>
+}
+internal abstract class foobar.Foo</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): foobar.Foo<T>
+ internal abstract val x: T
+}
+internal abstract class foobar.Iteratee</*0*/ in I : jet.Any?, /*1*/ out O : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ in I : jet.Any?, /*1*/ out O : jet.Any?><init>(): foobar.Iteratee<I, O>
+ internal abstract fun done(): O
+ internal abstract val isDone: jet.Boolean
+ internal abstract fun process(/*0*/ item: I): foobar.Iteratee<I, O>
+ internal abstract val result: O
+}
+internal final class foobar.StrangeIterateeImpl</*0*/ in I : jet.Any?, /*1*/ out O : jet.Any?> : foobar.Iteratee<I, O> {
+ public final /*constructor*/ fun </*0*/ in I : jet.Any?, /*1*/ out O : jet.Any?><init>(/*0*/ obj: O): foobar.StrangeIterateeImpl<I, O>
+ internal open override /*1*/ fun done(): O
+ internal open override /*1*/ val isDone: jet.Boolean
+ internal final val obj: O
+ internal open override /*1*/ fun process(/*0*/ item: I): foobar.Iteratee<I, O>
+ internal open override /*1*/ val result: O
+}
+internal abstract class foobar.Sum : foobar.Iteratee<jet.Int, jet.Int> {
+ public final /*constructor*/ fun <init>(): foobar.Sum
+ internal abstract override /*1*/ fun done(): jet.Int
+ internal abstract override /*1*/ val isDone: jet.Boolean
+ internal open override /*1*/ fun process(/*0*/ item: jet.Int): foobar.Iteratee<jet.Int, jet.Int>
+ internal abstract override /*1*/ val result: jet.Int
+}
+internal final val x1: java.util.List<jet.Int>?
+internal final val y1: java.util.List<jet.Int>?
+internal final fun </*0*/ O : jet.Any?>done(/*0*/ result: O): foobar.Iteratee<jet.Any?, O>
+// </namespace name="foobar">
diff --git a/compiler/testData/lazyResolve/diagnostics/Nullability.txt b/compiler/testData/lazyResolve/diagnostics/Nullability.txt
new file mode 100644
index 0000000000000..3b056c1c63314
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Nullability.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal final fun f(/*0*/ out: jet.String?): jet.Tuple0
+internal final fun f1(/*0*/ out: jet.String?): jet.Tuple0
+internal final fun f2(/*0*/ out: jet.String?): jet.Tuple0
+internal final fun f3(/*0*/ out: jet.String?): jet.Tuple0
+internal final fun f4(/*0*/ s: jet.String?): jet.Tuple0
+internal final fun f5(/*0*/ s: jet.String?): jet.Tuple0
+internal final fun f6(/*0*/ s: jet.String?): jet.Tuple0
+internal final fun f7(/*0*/ s: jet.String?, /*1*/ t: jet.String?): jet.Tuple0
+internal final fun f8(/*0*/ b: jet.String?, /*1*/ a: jet.String): jet.Tuple0
+internal final fun f9(/*0*/ a: jet.Int?): jet.Int
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/OverrideFunctionWithParamDefaultValue.txt b/compiler/testData/lazyResolve/diagnostics/OverrideFunctionWithParamDefaultValue.txt
new file mode 100644
index 0000000000000..913fa03a2342b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/OverrideFunctionWithParamDefaultValue.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal abstract class B : jet.Any {
+ public final /*constructor*/ fun <init>(): B
+ internal abstract fun foo2(/*0*/ arg: jet.Int = ?): jet.Int
+}
+internal final class C : B {
+ public final /*constructor*/ fun <init>(): C
+ internal open override /*1*/ fun foo2(/*0*/ arg: jet.Int = ?): jet.Int
+}
+internal final fun invokeIt(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/OverridenFunctionAndSpecifiedTypeParameter.txt b/compiler/testData/lazyResolve/diagnostics/OverridenFunctionAndSpecifiedTypeParameter.txt
new file mode 100644
index 0000000000000..92342e417610d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/OverridenFunctionAndSpecifiedTypeParameter.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract trait Aaa</*0*/ T : jet.Any?> : jet.Any {
+ internal abstract fun zzz(/*0*/ value: T): jet.Tuple0
+}
+internal final class Bbb</*0*/ T : jet.Any?> : Aaa<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): Bbb<T>
+ internal open override /*1*/ fun zzz(/*0*/ value: T): jet.Tuple0
+}
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/OverridingVarByVal.txt b/compiler/testData/lazyResolve/diagnostics/OverridingVarByVal.txt
new file mode 100644
index 0000000000000..0c5baea4d586e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/OverridingVarByVal.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal final class Val : Var, VarT {
+ public final /*constructor*/ fun <init>(): Val
+ internal open override /*2*/ val v: jet.Int
+}
+internal open class Var : jet.Any {
+ public final /*constructor*/ fun <init>(): Var
+ internal open var v: jet.Int
+}
+internal final class Var2 : Var {
+ public final /*constructor*/ fun <init>(): Var2
+ internal open override /*1*/ var v: jet.Int
+}
+internal abstract trait VarT : jet.Any {
+ internal abstract var v: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/PrimaryConstructors.txt b/compiler/testData/lazyResolve/diagnostics/PrimaryConstructors.txt
new file mode 100644
index 0000000000000..2b0d8518cc1c0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/PrimaryConstructors.txt
@@ -0,0 +1,27 @@
+namespace <root>
+
+internal final class MyIterable</*0*/ T : jet.Any?> : jet.Iterable<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): MyIterable<T>
+ internal final class MyIterable.MyIterator : jet.Iterator<T> {
+ public final /*constructor*/ fun <init>(): MyIterable.MyIterator
+ public open override /*1*/ val hasNext: jet.Boolean
+ public open override /*1*/ fun next(): T
+ }
+ public open override /*1*/ fun iterator(): jet.Iterator<T>
+}
+internal final class X : jet.Any {
+ public final /*constructor*/ fun <init>(): X
+ internal final val x: jet.Int
+}
+internal open class Y : jet.Any {
+ public final /*constructor*/ fun <init>(): Y
+ internal final val x: jet.Int
+}
+internal final class Y1 : jet.Any {
+ public final /*constructor*/ fun <init>(): Y1
+ internal final val x: jet.Int
+}
+internal final class Z : Y {
+ public final /*constructor*/ fun <init>(): Z
+ internal final override /*1*/ val x: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/ProcessingEmptyImport.txt b/compiler/testData/lazyResolve/diagnostics/ProcessingEmptyImport.txt
new file mode 100644
index 0000000000000..e6dce1f6909d2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ProcessingEmptyImport.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun firstFun(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/ProjectionOnFunctionArgumentErrror.txt b/compiler/testData/lazyResolve/diagnostics/ProjectionOnFunctionArgumentErrror.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ProjectionOnFunctionArgumentErrror.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/ProjectionsInSupertypes.txt b/compiler/testData/lazyResolve/diagnostics/ProjectionsInSupertypes.txt
new file mode 100644
index 0000000000000..9c693405742dd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ProjectionsInSupertypes.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal abstract trait A</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait B</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait C</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait D</*0*/ T : jet.Any?> : jet.Any {
+}
+internal abstract trait Test : A<in jet.Int>, B<out jet.Int>, C<out jet.Any?>?, D<jet.Int> {
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/QualifiedExpressions.txt b/compiler/testData/lazyResolve/diagnostics/QualifiedExpressions.txt
new file mode 100644
index 0000000000000..d2f0498cb2632
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/QualifiedExpressions.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="qualified_expressions">
+namespace qualified_expressions
+
+internal final fun jet.String.startsWith(/*0*/ s: jet.String): jet.Boolean
+internal final fun test(/*0*/ s: jet.String?): jet.Tuple0
+// </namespace name="qualified_expressions">
diff --git a/compiler/testData/lazyResolve/diagnostics/RecursiveTypeInference.txt b/compiler/testData/lazyResolve/diagnostics/RecursiveTypeInference.txt
new file mode 100644
index 0000000000000..1553f6e4d5261
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/RecursiveTypeInference.txt
@@ -0,0 +1,44 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final val foo: [ERROR : Error function type]
+internal final fun bar(): [ERROR : Error function type]
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final fun bar(): [ERROR : Error function type]
+internal final fun foo(): [ERROR : Error function type]
+// </namespace name="b">
+// <namespace name="c">
+namespace c
+
+internal final fun bar(): [ERROR : Error function type]
+internal final fun bazz(): [ERROR : Error function type]
+internal final fun foo(): [ERROR : Error function type]
+// </namespace name="c">
+// <namespace name="ok">
+namespace ok
+
+// <namespace name="a">
+namespace a
+
+internal final val foo: jet.Int
+internal final fun bar(): jet.Int
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final fun bar(): jet.Int
+internal final fun foo(): jet.Int
+// </namespace name="b">
+// <namespace name="c">
+namespace c
+
+internal final fun bar(): jet.Int
+internal final fun bazz(): jet.Int
+internal final fun foo(): jet.Int
+// </namespace name="c">
+// </namespace name="ok">
diff --git a/compiler/testData/lazyResolve/diagnostics/ResolveOfJavaGenerics.txt b/compiler/testData/lazyResolve/diagnostics/ResolveOfJavaGenerics.txt
new file mode 100644
index 0000000000000..bed0e4ddbd870
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ResolveOfJavaGenerics.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
+internal final fun test(/*0*/ a: java.lang.Class<jet.Int>): jet.Tuple0
+internal final fun test(/*0*/ a: java.lang.Comparable<jet.Int>): jet.Tuple0
+internal final fun test(/*0*/ a: java.lang.annotation.RetentionPolicy): jet.Tuple0
+internal final fun test(/*0*/ a: java.util.ArrayList<jet.Int>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Return.txt b/compiler/testData/lazyResolve/diagnostics/Return.txt
new file mode 100644
index 0000000000000..efed81cc38cf1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Return.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun outer(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiver.txt b/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiver.txt
new file mode 100644
index 0000000000000..4b34c64649ab4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiver.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiverReturnNull.txt b/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiverReturnNull.txt
new file mode 100644
index 0000000000000..110b47cb0c189
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/SafeCallNonNullReceiverReturnNull.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun ff(): jet.Tuple0
+internal final fun jet.Int.gg(): jet.Nothing?
diff --git a/compiler/testData/lazyResolve/diagnostics/ShiftFunctionTypes.txt b/compiler/testData/lazyResolve/diagnostics/ShiftFunctionTypes.txt
new file mode 100644
index 0000000000000..581d4dbd0e762
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ShiftFunctionTypes.txt
@@ -0,0 +1,50 @@
+namespace <root>
+
+// <namespace name="n">
+namespace n
+
+internal final class n.B : jet.Any {
+ public final /*constructor*/ fun <init>(): n.B
+}
+// </namespace name="n">
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal abstract class XXX : jet.Any {
+ public final /*constructor*/ fun <init>(): XXX
+ internal final val a11: jet.Function1<jet.Int, jet.Int>?
+ internal final val a12: jet.Function1<jet.Int, jet.Int>?
+ internal abstract val a13: jet.ExtensionFunction1<jet.Int, jet.Int, jet.Int>
+ internal abstract val a14: jet.ExtensionFunction1<n.B, jet.Int, jet.Int>
+ internal abstract val a152: jet.ExtensionFunction1<jet.Int?, jet.Int, jet.Int>
+ internal abstract val a15: jet.ExtensionFunction1<jet.Int?, jet.Int, jet.Int>
+ internal abstract val a16: jet.Function1<jet.Int, jet.Function1<jet.Int, jet.Int>>
+ internal abstract val a17: jet.ExtensionFunction1<jet.Function1<jet.Int, jet.Int>, jet.Int, jet.Int>
+ internal abstract val a18: jet.Function1<jet.Int, jet.Function1<jet.Int, jet.Int>>
+ internal abstract val a19: jet.Function1<jet.Function1<jet.Int, jet.Int>, jet.Int>
+ internal abstract val a1: [ERROR : package.Int]
+ internal abstract val a2: n.B
+ internal abstract val a31: n.B
+ internal abstract val a3: A
+ internal abstract val a4: A?
+ internal abstract val a5: A?
+ internal abstract val a6: A?
+ internal abstract val a7: jet.Function1<A, n.B>
+ internal abstract val a8: jet.Function2<A, n.B, n.B>
+ internal abstract val a: jet.Int
+}
+internal abstract class YYY : jet.Any {
+ public final /*constructor*/ fun <init>(): YYY
+ internal final val a11: jet.Function1<jet.Int, jet.Int>?
+ internal final val a12: jet.Function1<jet.Int, jet.Int>?
+ internal abstract val a13: jet.ExtensionFunction1<jet.Int, jet.Int, jet.Int>
+ internal abstract val a14: jet.ExtensionFunction1<n.B, jet.Int, jet.Int>
+ internal abstract val a152: jet.ExtensionFunction1<jet.Int?, jet.Int, jet.Int>
+ internal abstract val a15: jet.ExtensionFunction1<jet.Int?, jet.Int, jet.Int>
+ internal abstract val a16: jet.Function1<jet.Int, jet.Function1<jet.Int, jet.Int>>
+ internal abstract val a17: jet.ExtensionFunction1<jet.Function1<jet.Int, jet.Int>, jet.Int, jet.Int>
+ internal abstract val a18: jet.Function1<jet.Int, jet.Function1<jet.Int, jet.Int>>
+ internal abstract val a19: jet.Function1<jet.Function1<jet.Int, jet.Int>, jet.Int>
+ internal abstract val a7: jet.Function1<A, n.B>
+ internal abstract val a8: jet.Function2<A, n.B, n.B>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/StarsInFunctionCalls.txt b/compiler/testData/lazyResolve/diagnostics/StarsInFunctionCalls.txt
new file mode 100644
index 0000000000000..4d09b4d1d98bc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/StarsInFunctionCalls.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final fun foo(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>getT(): jet.Tuple0
+internal final fun </*0*/ A : jet.Any?, /*1*/ B : jet.Any?>getTT(): jet.Tuple0
+internal final fun </*0*/ A : jet.Any?, /*1*/ B : jet.Any?, /*2*/ C : jet.Any?>getTTT(/*0*/ x: jet.Any): jet.Tuple0
+internal open fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/StringTemplates.txt b/compiler/testData/lazyResolve/diagnostics/StringTemplates.txt
new file mode 100644
index 0000000000000..9649148c965fc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/StringTemplates.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun demo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Super.txt b/compiler/testData/lazyResolve/diagnostics/Super.txt
new file mode 100644
index 0000000000000..df3fcb4d8eb77
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Super.txt
@@ -0,0 +1,43 @@
+namespace <root>
+
+// <namespace name="example">
+namespace example
+
+internal final class example.A</*0*/ E : jet.Any?> : example.C, example.T {
+ public final /*constructor*/ fun </*0*/ E : jet.Any?><init>(): example.A<E>
+ internal final override /*1*/ fun bar(): jet.Tuple0
+ internal final class example.A.B : example.T {
+ public final /*constructor*/ fun <init>(): example.A.B
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final fun test(): jet.Tuple0
+ }
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final fun test(): jet.Tuple0
+}
+internal final class example.A1 : jet.Any {
+ public final /*constructor*/ fun <init>(): example.A1
+ internal final fun test(): jet.Tuple0
+}
+internal open class example.C : jet.Any {
+ public final /*constructor*/ fun <init>(): example.C
+ internal final fun bar(): jet.Tuple0
+}
+internal final class example.CG : example.G<jet.Int> {
+ public final /*constructor*/ fun <init>(): example.CG
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final fun test(): jet.Tuple0
+}
+internal final class example.ERROR</*0*/ E : jet.Any?> {
+ public final /*constructor*/ fun </*0*/ E : jet.Any?><init>(): example.ERROR<E>
+ internal final fun test(): jet.Tuple0
+}
+internal abstract trait example.G</*0*/ T : jet.Any?> : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+internal abstract trait example.T : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+internal final fun any(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+internal final fun notAnExpression(): jet.Tuple0
+// </namespace name="example">
diff --git a/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlighting.txt b/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlighting.txt
new file mode 100644
index 0000000000000..9e5beb4ac5740
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlighting.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun get(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlightingEof.txt b/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlightingEof.txt
new file mode 100644
index 0000000000000..1604dc621422a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/SyntaxErrorInTestHighlightingEof.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/TypeInference.txt b/compiler/testData/lazyResolve/diagnostics/TypeInference.txt
new file mode 100644
index 0000000000000..14c7a9d2f8986
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/TypeInference.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class C</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): C<T>
+ internal final fun foo(): T
+}
+internal final fun </*0*/ T : jet.Any?>bar(): C<T>
+internal final fun foo(/*0*/ c: C<jet.Int>): jet.Tuple0
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/UnitByDefaultForFunctionTypes.txt b/compiler/testData/lazyResolve/diagnostics/UnitByDefaultForFunctionTypes.txt
new file mode 100644
index 0000000000000..bf498336f240c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/UnitByDefaultForFunctionTypes.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun foo(/*0*/ f: jet.Function0<jet.Tuple0>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/UnreachableCode.txt b/compiler/testData/lazyResolve/diagnostics/UnreachableCode.txt
new file mode 100644
index 0000000000000..75755fdd9b953
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/UnreachableCode.txt
@@ -0,0 +1,25 @@
+namespace <root>
+
+internal final fun blockAndAndMismatch(): jet.Boolean
+internal final fun fail(): jet.Nothing
+internal final fun failtest(/*0*/ a: jet.Int): jet.Int
+internal final fun foo(/*0*/ a: jet.Nothing): jet.Tuple0
+internal final fun nullIsNotNothing(): jet.Tuple0
+internal final fun returnInWhile(/*0*/ a: jet.Int): jet.Tuple0
+internal final fun t1(): jet.Int
+internal final fun t1a(): jet.Int
+internal final fun t1b(): jet.Int
+internal final fun t1c(): jet.Int
+internal final fun t2(): jet.Int
+internal final fun t2a(): jet.Int
+internal final fun t3(): jet.Any
+internal final fun t4(/*0*/ a: jet.Boolean): jet.Int
+internal final fun t4break(/*0*/ a: jet.Boolean): jet.Int
+internal final fun t5(): jet.Int
+internal final fun t6(): jet.Int
+internal final fun t6break(): jet.Int
+internal final fun t7(): jet.Int
+internal final fun t7(/*0*/ b: jet.Int): jet.Int
+internal final fun t7break(/*0*/ b: jet.Int): jet.Int
+internal final fun t8(): jet.Int
+internal final fun tf(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/Unresolved.txt b/compiler/testData/lazyResolve/diagnostics/Unresolved.txt
new file mode 100644
index 0000000000000..321166bec2707
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Unresolved.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="unresolved">
+namespace unresolved
+
+internal final fun foo1(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun testGenericArgumentsCount(): jet.Tuple0
+internal final fun testUnresolved(): jet.Tuple0
+// </namespace name="unresolved">
diff --git a/compiler/testData/lazyResolve/diagnostics/UnusedVariables.txt b/compiler/testData/lazyResolve/diagnostics/UnusedVariables.txt
new file mode 100644
index 0000000000000..3a8d49385e4a3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/UnusedVariables.txt
@@ -0,0 +1,31 @@
+namespace <root>
+
+// <namespace name="unused_variables">
+namespace unused_variables
+
+internal final class unused_variables.IncDec : jet.Any {
+ public final /*constructor*/ fun <init>(): unused_variables.IncDec
+ internal final fun dec(): unused_variables.IncDec
+ internal final fun inc(): unused_variables.IncDec
+}
+internal final class unused_variables.MyTest : jet.Any {
+ public final /*constructor*/ fun <init>(): unused_variables.MyTest
+ internal final var a: jet.String
+ internal final fun doSmth(/*0*/ a: jet.Any): jet.Tuple0
+ internal final fun doSmth(/*0*/ s: jet.String): jet.Tuple0
+ internal final fun testFor(): jet.Tuple0
+ internal final fun testIf(): jet.Tuple0
+ internal final fun testIncDec(): jet.Tuple0
+ internal final fun testSimple(): jet.Tuple0
+ internal final fun testWhile(): jet.Tuple0
+}
+internal abstract trait unused_variables.Trait : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+}
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun testBackingFieldsNotMarked(): jet.Tuple0
+internal final fun testFunctionLiterals(): jet.Tuple0
+internal final fun testInnerFunctions(): jet.Tuple0
+internal final fun testObject(): unused_variables.Trait
+internal final fun testSimpleCases(): jet.Tuple0
+// </namespace name="unused_variables">
diff --git a/compiler/testData/lazyResolve/diagnostics/ValAndFunOverrideCompatibilityClash.txt b/compiler/testData/lazyResolve/diagnostics/ValAndFunOverrideCompatibilityClash.txt
new file mode 100644
index 0000000000000..fee77e3333484
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/ValAndFunOverrideCompatibilityClash.txt
@@ -0,0 +1,42 @@
+namespace <root>
+
+internal open class Bar : jet.Any {
+ public final /*constructor*/ fun <init>(): Bar
+ internal final fun v(): jet.Int
+ internal final val v: jet.Int
+}
+internal final class Barr : Bar {
+ public final /*constructor*/ fun <init>(): Barr
+ internal final override /*1*/ fun v(): jet.Int
+ internal final override /*1*/ val v: jet.Int
+}
+internal final class Foo1 : java.util.ArrayList<jet.Int> {
+ public final /*constructor*/ fun <init>(): Foo1
+ public open override /*1*/ fun add(/*0*/ p0: jet.Int): jet.Boolean
+ public open override /*1*/ fun add(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0
+ public open override /*1*/ fun addAll(/*0*/ p0: java.util.Collection<out jet.Int>): jet.Boolean
+ public open override /*1*/ fun addAll(/*0*/ p0: jet.Int, /*1*/ p1: java.util.Collection<out jet.Int>): jet.Boolean
+ public open override /*1*/ fun clear(): jet.Tuple0
+ public open override /*1*/ fun contains(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun containsAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun ensureCapacity(/*0*/ p0: jet.Int): jet.Tuple0
+ public open override /*1*/ fun get(/*0*/ p0: jet.Int): jet.Int
+ public open override /*1*/ fun indexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun isEmpty(): jet.Boolean
+ public open override /*1*/ fun iterator(): java.util.Iterator<jet.Int>
+ public open override /*1*/ fun lastIndexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun listIterator(): java.util.ListIterator<jet.Int>
+ public open override /*1*/ fun listIterator(/*0*/ p0: jet.Int): java.util.ListIterator<jet.Int>
+ protected final override /*1*/ var modCount: jet.Int
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Int): jet.Int
+ public open override /*1*/ fun removeAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ protected open override /*1*/ fun removeRange(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0
+ public open override /*1*/ fun retainAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun set(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Int
+ public open override /*1*/ fun size(): jet.Int
+ public open override /*1*/ fun subList(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): java.util.List<jet.Int>
+ public open override /*1*/ fun toArray(): jet.Array<jet.Any?>
+ public open override /*1*/ fun </*0*/ T : jet.Any?>toArray(/*0*/ p0: jet.Array<T>): jet.Array<T>
+ public open override /*1*/ fun trimToSize(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/VarargTypes.txt b/compiler/testData/lazyResolve/diagnostics/VarargTypes.txt
new file mode 100644
index 0000000000000..d90e2180771ec
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/VarargTypes.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal final fun foob(/*0*/ vararg a: jet.Boolean /*jet.BooleanArray*/): jet.BooleanArray
+internal final fun foob(/*0*/ vararg a: jet.Byte /*jet.ByteArray*/): jet.ByteArray
+internal final fun fooc(/*0*/ vararg a: jet.Char /*jet.CharArray*/): jet.CharArray
+internal final fun food(/*0*/ vararg a: jet.Double /*jet.DoubleArray*/): jet.DoubleArray
+internal final fun foof(/*0*/ vararg a: jet.Float /*jet.FloatArray*/): jet.FloatArray
+internal final fun fooi(/*0*/ vararg a: jet.Int /*jet.IntArray*/): jet.IntArray
+internal final fun fool(/*0*/ vararg a: jet.Long /*jet.LongArray*/): jet.LongArray
+internal final fun foos(/*0*/ vararg a: jet.Short /*jet.ShortArray*/): jet.ShortArray
+internal final fun foos(/*0*/ vararg a: jet.String /*jet.Array<jet.String>*/): jet.Array<jet.String>
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Varargs.txt b/compiler/testData/lazyResolve/diagnostics/Varargs.txt
new file mode 100644
index 0000000000000..457d4575615d9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Varargs.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
+internal final fun v(/*0*/ x: jet.Int, /*1*/ y: jet.String, /*2*/ vararg f: jet.Long /*jet.LongArray*/): jet.Tuple0
+internal final fun v1(/*0*/ vararg f: jet.Function1<jet.Int, jet.Tuple0> /*jet.Array<jet.Function1<jet.Int, jet.Tuple0>>*/): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/Variance.txt b/compiler/testData/lazyResolve/diagnostics/Variance.txt
new file mode 100644
index 0000000000000..95659be921597
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/Variance.txt
@@ -0,0 +1,28 @@
+namespace <root>
+
+// <namespace name="variance">
+namespace variance
+
+internal final class variance.Array</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ length: jet.Int, /*1*/ t: T): variance.Array<T>
+ internal final fun get(/*0*/ index: jet.Int): T
+ internal final val length: jet.Int
+ internal final fun set(/*0*/ index: jet.Int, /*1*/ value: T): jet.Tuple0
+ internal final val t: T
+}
+internal abstract class variance.Consumer</*0*/ in T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ in T : jet.Any?><init>(): variance.Consumer<T>
+}
+internal abstract class variance.Producer</*0*/ out T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ out T : jet.Any?><init>(): variance.Producer<T>
+}
+internal abstract class variance.Usual</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): variance.Usual<T>
+}
+internal final fun copy1(/*0*/ from: variance.Array<jet.Any>, /*1*/ to: variance.Array<jet.Any>): jet.Tuple0
+internal final fun copy2(/*0*/ from: variance.Array<out jet.Any>, /*1*/ to: variance.Array<in jet.Any>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>copy3(/*0*/ from: variance.Array<out T>, /*1*/ to: variance.Array<in T>): jet.Tuple0
+internal final fun copy4(/*0*/ from: variance.Array<out jet.Number>, /*1*/ to: variance.Array<in jet.Int>): jet.Tuple0
+internal final fun f(/*0*/ ints: variance.Array<jet.Int>, /*1*/ any: variance.Array<jet.Any>, /*2*/ numbers: variance.Array<jet.Number>): jet.Tuple0
+internal final fun foo(/*0*/ c: variance.Consumer<jet.Int>, /*1*/ p: variance.Producer<jet.Int>, /*2*/ u: variance.Usual<jet.Int>): jet.Tuple0
+// </namespace name="variance">
diff --git a/compiler/testData/lazyResolve/diagnostics/When.txt b/compiler/testData/lazyResolve/diagnostics/When.txt
new file mode 100644
index 0000000000000..a1ad99df2f40c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/When.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final val _type_test: jet.Int
+internal final val jet.Tuple2<out jet.Int, out jet.Int>.boo: jet.Tuple3<out jet.Int, out jet.Int, out jet.Int>
+internal final fun foo(): jet.Int
+internal final fun jet.Int.foo(): jet.Boolean
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/AnnotatedConstructorParams.txt b/compiler/testData/lazyResolve/diagnostics/annotations/AnnotatedConstructorParams.txt
new file mode 100644
index 0000000000000..83c777808a905
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/AnnotatedConstructorParams.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final class a.Test : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ s: jet.String, /*1*/ x: jet.Int): a.Test
+ internal final java.lang.Deprecated() val s: jet.String
+ internal final java.lang.SuppressWarnings() val x: jet.Int
+}
+internal final java.lang.Deprecated() java.lang.SuppressWarnings() val s: jet.String
+internal final java.lang.Deprecated() java.lang.SuppressWarnings() fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/AnnotationsForClasses.txt b/compiler/testData/lazyResolve/diagnostics/annotations/AnnotationsForClasses.txt
new file mode 100644
index 0000000000000..18ad41ac19506
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/AnnotationsForClasses.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+java.lang.Deprecated() internal final annotation class my : jet.Any {
+ public final /*constructor*/ fun <init>(): my
+}
+java.lang.Deprecated() internal final annotation class my1 : jet.Any {
+ public final /*constructor*/ fun <init>(): my1
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/Deprecated.txt b/compiler/testData/lazyResolve/diagnostics/annotations/Deprecated.txt
new file mode 100644
index 0000000000000..24000a5e05586
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/Deprecated.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final java.lang.Deprecated() fun foo(): jet.Tuple0
+internal final java.lang.Deprecated() fun foo1(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/NonAnnotationClass.txt b/compiler/testData/lazyResolve/diagnostics/annotations/NonAnnotationClass.txt
new file mode 100644
index 0000000000000..8bca4d4d609c5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/NonAnnotationClass.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+Foo() internal final class Bar : jet.Any {
+ public final /*constructor*/ fun <init>(): Bar
+}
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-negative.txt b/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-negative.txt
new file mode 100644
index 0000000000000..d2076c739d397
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-negative.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class Hello : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ args: jet.Any): Hello
+}
+internal final var bar: jet.Int
+internal final val x: jet.Function1<jet.Int, jet.Int>
+internal final fun foo(/*0*/ f: jet.Int): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-positive.txt b/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-positive.txt
new file mode 100644
index 0000000000000..dddd8b16fdfcb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/annotations/kt1860-positive.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal final class Hello : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ args: jet.Any): Hello
+}
+internal final annotation class test : jet.Any {
+ public final /*constructor*/ fun <init>(): test
+}
+internal final var bar: jet.Int
+internal final val x: jet.Function1<jet.Int, jet.Int>
+internal final fun foo(/*0*/ f: jet.Int): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetSet.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetSet.txt
new file mode 100644
index 0000000000000..025b5c5673870
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetSet.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Flower : jet.Any {
+ public final /*constructor*/ fun <init>(): Flower
+ internal final var minusOne: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVal.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVal.txt
new file mode 100644
index 0000000000000..52d4a9fa35e3c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVal.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class CustomGetVal : jet.Any {
+ public final /*constructor*/ fun <init>(): CustomGetVal
+ internal final val zz: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetValGlobal.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetValGlobal.txt
new file mode 100644
index 0000000000000..8ad18bb2c26ab
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetValGlobal.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="customGetValGlobal">
+namespace customGetValGlobal
+
+internal final val zz: jet.Int
+// </namespace name="customGetValGlobal">
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVar.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVar.txt
new file mode 100644
index 0000000000000..17212ccffec56
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomGetVar.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Raise : jet.Any {
+ public final /*constructor*/ fun <init>(): Raise
+ internal final var zz: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CustomSet.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CustomSet.txt
new file mode 100644
index 0000000000000..17212ccffec56
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CustomSet.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Raise : jet.Any {
+ public final /*constructor*/ fun <init>(): Raise
+ internal final var zz: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/CyclicReferenceInitializer.txt b/compiler/testData/lazyResolve/diagnostics/backingField/CyclicReferenceInitializer.txt
new file mode 100644
index 0000000000000..cb1b1edaa39fd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/CyclicReferenceInitializer.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Cyclic : jet.Any {
+ public final /*constructor*/ fun <init>(): Cyclic
+ internal final val a: [ERROR : Type for $a]
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInAnonymous.txt
new file mode 100644
index 0000000000000..9c76cad0dbf21
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInAnonymous.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class ReadForward : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadForward
+ internal final val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInPropertyInitializer.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInPropertyInitializer.txt
new file mode 100644
index 0000000000000..65e929a806352
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadForwardInPropertyInitializer.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class ReadForward : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadForward
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnonymous.txt
new file mode 100644
index 0000000000000..a2ed75745f0ca
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnonymous.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class ReadByAnotherPropertyInitializer : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadByAnotherPropertyInitializer
+ internal final val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnotherPropertyIntializer.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnotherPropertyIntializer.txt
new file mode 100644
index 0000000000000..4b1223d1f7f9b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInAnotherPropertyIntializer.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class ReadByAnotherPropertyInitializer : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadByAnotherPropertyInitializer
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadInFunction.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInFunction.txt
new file mode 100644
index 0000000000000..f87e66d9ed7fe
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadInFunction.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class ReadByAnotherPropertyInitializer : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadByAnotherPropertyInitializer
+ internal final val a: jet.Int
+ internal final fun ff(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInAnonymous.txt
new file mode 100644
index 0000000000000..c10d13a95d7c2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInAnonymous.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal abstract class ReadNonexistent : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadNonexistent
+ internal abstract val aa: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInFunction.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInFunction.txt
new file mode 100644
index 0000000000000..7e0c411af0c12
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentAbstractPropertyInFunction.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal abstract class ReadNonexistent : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadNonexistent
+ internal abstract val aa: jet.Int
+ internal final fun ff(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnonymous.txt
new file mode 100644
index 0000000000000..05b6b85d81656
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnonymous.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class ReadNonexistent : jet.Any {
+ public final /*constructor*/ fun <init>(): ReadNonexistent
+ internal final val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnotherInitializer.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnotherInitializer.txt
new file mode 100644
index 0000000000000..5ef8889422ca3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentCustomGetInAnotherInitializer.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class CustomValNoBackingField : jet.Any {
+ public final /*constructor*/ fun <init>(): CustomValNoBackingField
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentDeclaredInHigher.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentDeclaredInHigher.txt
new file mode 100644
index 0000000000000..5ef8889422ca3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentDeclaredInHigher.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class CustomValNoBackingField : jet.Any {
+ public final /*constructor*/ fun <init>(): CustomValNoBackingField
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentPropertyInAnonymous.txt b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentPropertyInAnonymous.txt
new file mode 100644
index 0000000000000..f5e51236dd169
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/ReadNonexistentPropertyInAnonymous.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class Cl : jet.Any {
+ public final /*constructor*/ fun <init>(): Cl
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/WriteNonexistentDeclaredInHigher.txt b/compiler/testData/lazyResolve/diagnostics/backingField/WriteNonexistentDeclaredInHigher.txt
new file mode 100644
index 0000000000000..a6ff6ca2ea4f7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/WriteNonexistentDeclaredInHigher.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal final val y: jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/backingField/kt782namespaceLevel.txt b/compiler/testData/lazyResolve/diagnostics/backingField/kt782namespaceLevel.txt
new file mode 100644
index 0000000000000..d9515e7f06817
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/backingField/kt782namespaceLevel.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt782">
+namespace kt782
+
+internal final val w: jet.Int
+internal final val x: jet.Int
+internal final val y: jet.Int
+internal final val z: jet.Int
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt782">
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/AsErasedError.txt b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedError.txt
new file mode 100644
index 0000000000000..e233c5d10460f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedError.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ c: java.util.Collection<jet.String>): java.util.List<jet.Int>
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/AsErasedFine.txt b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedFine.txt
new file mode 100644
index 0000000000000..ee02aa3c317ba
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedFine.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ c: java.util.Collection<jet.String>): java.util.List<jet.String>
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/AsErasedStar.txt b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedStar.txt
new file mode 100644
index 0000000000000..d874bb393cb18
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedStar.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: jet.Any): java.util.List<out jet.Any?>
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/AsErasedWarning.txt b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedWarning.txt
new file mode 100644
index 0000000000000..1e2d05dd9b65e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/AsErasedWarning.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ a: jet.Any): java.util.List<jet.String>
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowParameterSubtype.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowParameterSubtype.txt
new file mode 100644
index 0000000000000..f1bdab4041f12
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowParameterSubtype.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+}
+internal final fun ff(/*0*/ l: java.util.Collection<B>): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameClassParameter.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameClassParameter.txt
new file mode 100644
index 0000000000000..7b4c0b36f09ee
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameClassParameter.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: java.util.Collection<jet.String>): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameParameterParameter.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameParameterParameter.txt
new file mode 100644
index 0000000000000..ba3c7fcfdbb4f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedAllowSameParameterParameter.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>ff(/*0*/ l: java.util.Collection<T>): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromAny.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromAny.txt
new file mode 100644
index 0000000000000..4341165e10b6e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromAny.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: jet.Any): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromOut.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromOut.txt
new file mode 100644
index 0000000000000..3f948ac78062c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedDisallowFromOut.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(/*0*/ a: java.util.List<out jet.Any>): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsErasedStar.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedStar.txt
new file mode 100644
index 0000000000000..4341165e10b6e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsErasedStar.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: jet.Any): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsReified.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsReified.txt
new file mode 100644
index 0000000000000..2eb32c27524e9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsReified.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class MyList</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): MyList<T>
+}
+internal final fun ff(/*0*/ a: jet.Any): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/IsTraits.txt b/compiler/testData/lazyResolve/diagnostics/cast/IsTraits.txt
new file mode 100644
index 0000000000000..cfc744366f722
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/IsTraits.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal abstract trait Aaa : jet.Any {
+}
+internal abstract trait Bbb : jet.Any {
+}
+internal final fun f(/*0*/ a: Aaa): jet.Boolean
diff --git a/compiler/testData/lazyResolve/diagnostics/cast/WhenErasedDisallowFromAny.txt b/compiler/testData/lazyResolve/diagnostics/cast/WhenErasedDisallowFromAny.txt
new file mode 100644
index 0000000000000..41ac5a9791844
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/cast/WhenErasedDisallowFromAny.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(/*0*/ l: jet.Any): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/checkArguments/SpreadVarargs.txt b/compiler/testData/lazyResolve/diagnostics/checkArguments/SpreadVarargs.txt
new file mode 100644
index 0000000000000..2aede08d6c1eb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/checkArguments/SpreadVarargs.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>array1(/*0*/ vararg a: T /*jet.Array<T>*/): jet.Array<T>
+internal final fun join(/*0*/ x: jet.Int, /*1*/ vararg a: jet.String /*jet.Array<jet.String>*/): jet.String
+internal final fun </*0*/ T : jet.Any?>joinG(/*0*/ x: jet.Int, /*1*/ vararg a: T /*jet.Array<T>*/): jet.String
+internal final fun </*0*/ T : jet.Any?>joinT(/*0*/ x: jet.Int, /*1*/ vararg a: T /*jet.Array<T>*/): T?
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1897_diagnostic_part.txt b/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1897_diagnostic_part.txt
new file mode 100644
index 0000000000000..4dfebf0a558c1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1897_diagnostic_part.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun bar(): jet.Tuple0
+internal final fun foo(/*0*/ i: jet.Int, /*1*/ s: jet.String): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1940.txt b/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1940.txt
new file mode 100644
index 0000000000000..15fdda13490c4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/checkArguments/kt1940.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt1940">
+namespace kt1940
+
+internal final fun foo(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="kt1940">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/checkInnerLocalDeclarations.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/checkInnerLocalDeclarations.txt
new file mode 100644
index 0000000000000..d80464c4c00d1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/checkInnerLocalDeclarations.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final fun test(): jet.Tuple0
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1001.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1001.txt
new file mode 100644
index 0000000000000..9e3be45470a1f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1001.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="kt1001">
+namespace kt1001
+
+internal final fun doSmth(): jet.Tuple0
+internal final fun foo(/*0*/ c: jet.Array<jet.Int>): jet.Tuple0
+internal final fun t1(): jet.Int
+internal final fun t2(): jet.Int
+// </namespace name="kt1001">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1027.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1027.txt
new file mode 100644
index 0000000000000..19eaec93e3f2c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1027.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt1027">
+namespace kt1027
+
+internal final fun doSmth(): jet.Tuple0
+internal final fun foo(/*0*/ c: java.util.List<jet.Int>): jet.Tuple0
+internal final fun t1(): jet.Tuple0
+internal final fun t2(): jet.Tuple0
+internal final fun t3(): jet.Tuple0
+internal final fun t4(): jet.Tuple0
+// </namespace name="kt1027">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1066.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1066.txt
new file mode 100644
index 0000000000000..48d46dc10628f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1066.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt1066">
+namespace kt1066
+
+internal final fun foo(/*0*/ excluded: java.util.Set<jet.Char>): jet.Tuple0
+internal final fun randomDigit(): jet.Char
+internal final fun test(): jet.Tuple0
+// </namespace name="kt1066">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1156.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1156.txt
new file mode 100644
index 0000000000000..126bba5106df4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1156.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun foo(/*0*/ maybe: jet.Int?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1189.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1189.txt
new file mode 100644
index 0000000000000..9b42c984facbc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1189.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt1189">
+namespace kt1189
+
+internal final fun foo(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>java.util.concurrent.locks.ReentrantReadWriteLock.write(/*0*/ action: jet.Function0<T>): T
+// </namespace name="kt1189">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1191.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1191.txt
new file mode 100644
index 0000000000000..a2866ed58ebff
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1191.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt1191">
+namespace kt1191
+
+internal abstract trait kt1191.FunctionalList</*0*/ T : jet.Any?> : jet.Any {
+ internal abstract val head: T
+ internal abstract val size: jet.Int
+ internal abstract val tail: kt1191.FunctionalList<T>
+}
+internal final fun foo(/*0*/ unused: jet.Int): kt1191.foo.<no name provided>
+internal final fun </*0*/ T : jet.Any?>kt1191.FunctionalList<T>.plus(/*0*/ element: T): kt1191.FunctionalList<T>
+// </namespace name="kt1191">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1219.1301.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1219.1301.txt
new file mode 100644
index 0000000000000..c31ca127afced
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1219.1301.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt1219">
+namespace kt1219
+
+internal final fun </*0*/ T : jet.Any?, /*1*/ R : jet.Any?>jet.Iterable<T>.fold(/*0*/ r: R, /*1*/ op: jet.Function2<T, R, R>): R
+internal final fun foo(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>jet.Iterable<T>.foreach(/*0*/ operation: jet.Function1<T, jet.Tuple0>): jet.Tuple0
+// </namespace name="kt1219">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1571.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1571.txt
new file mode 100644
index 0000000000000..6692c4cefc94a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1571.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="kt1571">
+namespace kt1571
+
+internal final class kt1571.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1571.A
+ internal final fun divAssign(/*0*/ a: jet.Int): jet.Tuple0
+ internal final var p: jet.Int
+ internal final fun times(/*0*/ a: jet.Int): kt1571.A
+}
+internal final val a: kt1571.A
+internal final var c0: jet.Int
+internal final var c1: jet.Int
+internal final var c2: jet.Int
+internal final fun box(): jet.String
+// </namespace name="kt1571">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1977.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1977.txt
new file mode 100644
index 0000000000000..83e25d8c5b42e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt1977.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt1977">
+namespace kt1977
+
+internal final fun bar(): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+internal final fun strToInt(/*0*/ s: jet.String): jet.Int?
+internal final fun test1(/*0*/ s: jet.String): jet.Int?
+internal final fun test2(/*0*/ s: jet.String): jet.Int?
+// </namespace name="kt1977">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2166_kt2103.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2166_kt2103.txt
new file mode 100644
index 0000000000000..7fa5bdcf469a0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2166_kt2103.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun bar(): jet.Boolean
+internal final fun foo(): jet.Int
+internal final fun foo1(): jet.Boolean
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2226.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2226.txt
new file mode 100644
index 0000000000000..8bb79a4d58fd5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt2226.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal abstract trait a.A : jet.Any {
+ internal abstract fun foo(): jet.Int
+}
+internal final class a.B : a.A {
+ public final /*constructor*/ fun <init>(): a.B
+ internal open override /*1*/ fun foo(): jet.Int
+}
+internal final fun foo(/*0*/ b: a.B): jet.Int
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt510.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt510.txt
new file mode 100644
index 0000000000000..fb0fa3888bc8b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt510.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="kt510">
+namespace kt510
+
+public open class kt510.Identifier1 : jet.Any {
+ public final /*constructor*/ fun <init>(): kt510.Identifier1
+ internal final var field: jet.Boolean
+}
+public open class kt510.Identifier2 : jet.Any {
+ public final /*constructor*/ fun <init>(): kt510.Identifier2
+ internal final var field: jet.Boolean
+}
+// </namespace name="kt510">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt607.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt607.txt
new file mode 100644
index 0000000000000..9515d48ad61a9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt607.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt607">
+namespace kt607
+
+internal final class kt607.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt607.A
+ internal final val z: jet.Int
+}
+internal final fun foo(/*0*/ a: kt607.A): jet.Tuple0
+// </namespace name="kt607">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt609.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt609.txt
new file mode 100644
index 0000000000000..1b4744bef6847
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt609.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="kt609">
+namespace kt609
+
+internal open class kt609.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt609.A
+ internal open fun foo(/*0*/ s: jet.String): jet.Tuple0
+}
+internal final class kt609.B : kt609.A {
+ public final /*constructor*/ fun <init>(): kt609.B
+ internal final override /*1*/ fun foo(/*0*/ s: jet.String): jet.Tuple0
+}
+internal final class kt609.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt609.C
+ internal final fun foo(/*0*/ s: jet.String): jet.Tuple0
+}
+internal final fun test(/*0*/ a: jet.Int): jet.Tuple0
+// </namespace name="kt609">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt610.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt610.txt
new file mode 100644
index 0000000000000..7a6b92e126d7f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt610.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt610">
+namespace kt610
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt610">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt776.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt776.txt
new file mode 100644
index 0000000000000..71633ff4143c0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt776.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt776">
+namespace kt776
+
+internal final fun doSmth(): jet.Tuple0
+internal final fun test1(): jet.Int
+internal final fun test5(): jet.Int
+// </namespace name="kt776">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt843.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt843.txt
new file mode 100644
index 0000000000000..87c51c79675d0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt843.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt843">
+namespace kt843
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt843">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt897.txt b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt897.txt
new file mode 100644
index 0000000000000..1976dac959d5a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlFlowAnalysis/kt897.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt897">
+namespace kt897
+
+internal final class kt897.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt897.A
+ internal final val i: jet.Int?
+ internal final var j: jet.Int
+ internal final val k: jet.Int
+}
+// </namespace name="kt897">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/ForWithoutBraces.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/ForWithoutBraces.txt
new file mode 100644
index 0000000000000..4b34c64649ab4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/ForWithoutBraces.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt1075.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt1075.txt
new file mode 100644
index 0000000000000..c2f1c60e2241d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt1075.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt1075">
+namespace kt1075
+
+internal final fun foo(/*0*/ b: jet.String): jet.Tuple0
+// </namespace name="kt1075">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt657.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt657.txt
new file mode 100644
index 0000000000000..c6f81f06bd6fa
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt657.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt657">
+namespace kt657
+
+internal final fun cond1(): jet.Boolean
+internal final fun cond2(): jet.Boolean
+internal final fun foo(): jet.Int
+// </namespace name="kt657">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt770.kt351.kt735_StatementType.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt770.kt351.kt735_StatementType.txt
new file mode 100644
index 0000000000000..7558477069c93
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt770.kt351.kt735_StatementType.txt
@@ -0,0 +1,18 @@
+namespace <root>
+
+// <namespace name="kt770_351_735">
+namespace kt770_351_735
+
+internal final val w: [ERROR : Type for while (true) {}]
+internal final fun bar(/*0*/ a: jet.Tuple0): jet.Tuple0
+internal final fun box(): jet.Int
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun test1(): jet.Tuple0
+internal final fun test2(): jet.Tuple0
+internal final fun testCoercionToUnit(): jet.Tuple0
+internal final fun testImplicitCoercion(): jet.Tuple0
+internal final fun testStatementInExpressionContext(): jet.Tuple0
+internal final fun testStatementInExpressionContext2(): jet.Tuple0
+// </namespace name="kt770_351_735">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt786.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt786.txt
new file mode 100644
index 0000000000000..d8b1d7b1252b4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt786.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt786">
+namespace kt786
+
+internal final fun bar(): jet.Int
+internal final fun fff(): jet.Int
+internal final fun foo(): jet.Int
+// </namespace name="kt786">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/kt799.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt799.txt
new file mode 100644
index 0000000000000..5fc1c2a661e79
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/kt799.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt799">
+namespace kt799
+
+internal final val a: jet.Nothing
+internal final val b: jet.Nothing
+internal final val c: jet.Tuple0
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun f(/*0*/ mi: jet.Int = ?): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="kt799">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/tryReturnType.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/tryReturnType.txt
new file mode 100644
index 0000000000000..a251051b5f200
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/tryReturnType.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun bar(): jet.Int
+internal final fun doSmth(): jet.Tuple0
+internal final fun foo(): jet.Int
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/controlStructures/when.kt234.kt973.txt b/compiler/testData/lazyResolve/diagnostics/controlStructures/when.kt234.kt973.txt
new file mode 100644
index 0000000000000..ee3bfcd083797
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/controlStructures/when.kt234.kt973.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="kt234_kt973">
+namespace kt234_kt973
+
+internal final fun foo3(/*0*/ x: jet.Int): jet.Int
+internal final fun foo4(/*0*/ x: jet.Int): jet.Int
+internal final fun t1(/*0*/ x: jet.Int): jet.Int
+internal final fun t2(/*0*/ x: jet.Int): jet.Int
+internal final fun t3(/*0*/ x: jet.Int): jet.Int
+internal final fun t4(/*0*/ x: jet.Int): jet.Int
+internal final fun t5(/*0*/ x: jet.Int): jet.Int
+internal final fun test(/*0*/ t: jet.Tuple2<out jet.Int, out jet.Int>): jet.Int
+internal final fun test1(/*0*/ t: jet.Tuple2<out jet.Int, out jet.Int>): jet.Int
+// </namespace name="kt234_kt973">
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlow/CalleeExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlow/CalleeExpression.txt
new file mode 100644
index 0000000000000..ce49ca5e9f829
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlow/CalleeExpression.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ f: jet.Function0<jet.Tuple0>): C
+ internal final val f: jet.Function0<jet.Tuple0>
+}
+internal final fun test(/*0*/ e: jet.Any): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlow/TupleExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlow/TupleExpression.txt
new file mode 100644
index 0000000000000..793a6551f3e1d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlow/TupleExpression.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ f: jet.Int): C
+ internal final val f: jet.Int
+}
+internal final fun test(/*0*/ e: jet.Any): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlow/WhenSubject.txt b/compiler/testData/lazyResolve/diagnostics/dataFlow/WhenSubject.txt
new file mode 100644
index 0000000000000..1f96cc7fb1d72
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlow/WhenSubject.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class BinOp : Expr {
+ public final /*constructor*/ fun <init>(/*0*/ operator: jet.String): BinOp
+ internal final val operator: jet.String
+}
+internal abstract trait Expr : jet.Any {
+}
+internal final fun test(/*0*/ e: Expr): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/AndOr.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/AndOr.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/AndOr.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ArrayAccess.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ArrayAccess.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ArrayAccess.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/BinaryExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/BinaryExpression.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/BinaryExpression.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DeepIf.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DeepIf.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DeepIf.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DoWhile.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DoWhile.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/DoWhile.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Elvis.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Elvis.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Elvis.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ExclExcl.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ExclExcl.txt
new file mode 100644
index 0000000000000..9af818d67606b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ExclExcl.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun f1(/*0*/ x: jet.Int?): jet.Tuple0
+internal final fun f2(/*0*/ x: jet.Int?): jet.Tuple0
+internal final fun f3(/*0*/ x: jet.Int?): jet.Tuple0
+internal final fun f4(/*0*/ x: jet.Int?): jet.Tuple0
+internal final fun f5(/*0*/ x: jet.Int?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/For.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/For.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/For.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/FunctionLiteral.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/FunctionLiteral.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/FunctionLiteral.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElse.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElse.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElse.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElseBothInvalid.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElseBothInvalid.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/IfThenElseBothInvalid.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ObjectExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ObjectExpression.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ObjectExpression.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/QualifiedExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/QualifiedExpression.txt
new file mode 100644
index 0000000000000..1794133d26608
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/QualifiedExpression.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun bar(/*0*/ x: jet.Int): jet.Int
+}
+internal final fun baz(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Return.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Return.txt
new file mode 100644
index 0000000000000..b1c73ed1c32df
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Return.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ThisSuper.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ThisSuper.txt
new file mode 100644
index 0000000000000..314550ba790ea
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/ThisSuper.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal open class Base : jet.Any {
+ public final /*constructor*/ fun <init>(): Base
+ internal final fun bar(/*0*/ x: jet.Int): jet.Int
+}
+internal final class Derived : Base {
+ public final /*constructor*/ fun <init>(): Derived
+ internal final override /*1*/ fun bar(/*0*/ x: jet.Int): jet.Int
+ internal final fun baz(/*0*/ x: jet.Int): jet.Int
+ internal final fun foo(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Throw.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Throw.txt
new file mode 100644
index 0000000000000..12260238f47c4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/Throw.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): java.lang.RuntimeException
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/TryCatch.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/TryCatch.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/TryCatch.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/UnaryExpression.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/UnaryExpression.txt
new file mode 100644
index 0000000000000..11a348b2d0177
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/UnaryExpression.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun baz(/*0*/ b: jet.Boolean): jet.Boolean
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/When.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/When.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/When.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/While.txt b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/While.txt
new file mode 100644
index 0000000000000..d9da81d482b1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/dataFlowInfoTraversal/While.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun bar(/*0*/ x: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt1141.txt b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt1141.txt
new file mode 100644
index 0000000000000..ac30d56821411
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt1141.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="kt1141">
+namespace kt1141
+
+internal final class kt1141.C : kt1141.SomeTrait {
+ public final /*constructor*/ fun <init>(): kt1141.C
+ internal abstract override /*1*/ fun foo(): jet.Tuple0
+}
+public abstract trait kt1141.SomeTrait : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+}
+internal final val Rr: kt1141.Rr
+internal final fun foo(): jet.Tuple0
+internal final fun foo2(): jet.Tuple0
+// </namespace name="kt1141">
diff --git a/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2096.txt b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2096.txt
new file mode 100644
index 0000000000000..ad7d211adaa89
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2096.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal abstract class c.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): c.Foo
+ protected abstract val prop: [ERROR : No type, no body]
+}
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2142.txt b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2142.txt
new file mode 100644
index 0000000000000..f09c4dce1a220
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt2142.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt559.txt b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt559.txt
new file mode 100644
index 0000000000000..0426640aa1697
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/declarationChecks/kt559.txt
@@ -0,0 +1,31 @@
+namespace <root>
+
+// <namespace name="kt559">
+namespace kt559
+
+internal abstract class kt559.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt559.A
+ internal final fun fff(): jet.Tuple0
+ internal abstract fun foo(): jet.Int
+ internal abstract val i: jet.Int
+}
+internal final class kt559.B : kt559.A {
+ public final /*constructor*/ fun <init>(): kt559.B
+ internal final override /*1*/ fun fff(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Int
+ internal abstract override /*1*/ val i: jet.Int
+}
+internal final class kt559.C : kt559.D {
+ public final /*constructor*/ fun <init>(): kt559.C
+ internal final override /*1*/ fun fff(): jet.Tuple0
+ internal abstract override /*1*/ fun foo(): jet.Int
+ internal open override /*1*/ val i: jet.Int
+ internal final fun test(): jet.Tuple0
+}
+internal abstract class kt559.D : kt559.A {
+ public final /*constructor*/ fun <init>(): kt559.D
+ internal final override /*1*/ fun fff(): jet.Tuple0
+ internal abstract override /*1*/ fun foo(): jet.Int
+ internal open override /*1*/ val i: jet.Int
+}
+// </namespace name="kt559">
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionFunctions.txt b/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionFunctions.txt
new file mode 100644
index 0000000000000..d65323c776003
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionFunctions.txt
@@ -0,0 +1,32 @@
+namespace <root>
+
+// <namespace name="outer">
+namespace outer
+
+internal final class outer.A : jet.Any {
+ public final /*constructor*/ fun <init>(): outer.A
+}
+internal final val jet.Int.abs: jet.Int
+internal final val </*0*/ T : jet.Any?> T.foo: T
+internal final val jet.Int?.optval: jet.Tuple0
+internal final fun </*0*/ T : jet.Any?, /*1*/ E : jet.Any?>T.foo(/*0*/ x: E, /*1*/ y: outer.A): T
+internal final fun jet.Int.foo(): jet.Int
+internal final fun </*0*/ T : jet.Any?>T.minus(/*0*/ t: T): jet.Int
+internal final fun jet.Int?.optint(): jet.Tuple0
+internal final fun outer.A.plus(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun outer.A.plus(/*0*/ a: jet.Int): jet.Tuple0
+internal final fun test(): jet.Tuple0
+// </namespace name="outer">
+// <namespace name="null_safety">
+namespace null_safety
+
+internal final class null_safety.Command : jet.Any {
+ public final /*constructor*/ fun <init>(): null_safety.Command
+ internal final val foo: jet.Int
+}
+internal final fun jet.Any.equals(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun jet.Any?.equals1(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun jet.Any.equals2(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun parse(/*0*/ cmd: jet.String): null_safety.Command?
+// </namespace name="null_safety">
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionsCalledOnSuper.txt b/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionsCalledOnSuper.txt
new file mode 100644
index 0000000000000..3650673a33a29
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/ExtensionsCalledOnSuper.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal final class C : T {
+ public final /*constructor*/ fun <init>(): C
+ internal open override /*1*/ fun buzz(): jet.Tuple0
+ internal open override /*1*/ fun buzz1(/*0*/ i: jet.Int): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final fun test(): jet.Tuple0
+}
+internal abstract trait T : jet.Any {
+ internal open fun buzz(): jet.Tuple0
+ internal open fun buzz1(/*0*/ i: jet.Int): jet.Tuple0
+ internal open fun foo(): jet.Tuple0
+}
+internal final fun T.bar(): jet.Tuple0
+internal final fun T.buzz(): jet.Tuple0
+internal final fun T.buzz1(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator.txt b/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator.txt
new file mode 100644
index 0000000000000..f173ad02b8f87
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any>T?.iterator(): iterator.<no name provided>
+internal final fun </*0*/ T : jet.Any?>java.util.Enumeration<T>.iterator(): iterator.<no name provided>
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator2.txt b/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator2.txt
new file mode 100644
index 0000000000000..b4ec6b67f35e9
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/GenericIterator2.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun a(/*0*/ e: java.util.Enumeration<jet.Int>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>java.util.Enumeration<T>.iterator(): iterator.<no name provided>
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/kt1875.txt b/compiler/testData/lazyResolve/diagnostics/extensions/kt1875.txt
new file mode 100644
index 0000000000000..2e03bdb4152cc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/kt1875.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt1875">
+namespace kt1875
+
+internal abstract trait kt1875.T : jet.Any {
+ internal abstract val f: jet.Function1<jet.Int, jet.Tuple0>?
+}
+internal final fun f(/*0*/ a: jet.Int?, /*1*/ b: jet.ExtensionFunction1<jet.Int, jet.Int, jet.Int>): jet.Int?
+internal final fun test(/*0*/ t: kt1875.T): jet.Tuple0
+internal final fun test1(/*0*/ t: kt1875.T?): jet.Tuple0
+// </namespace name="kt1875">
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/kt2317.txt b/compiler/testData/lazyResolve/diagnostics/extensions/kt2317.txt
new file mode 100644
index 0000000000000..f73a9f2c24f3d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/kt2317.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="kt2317">
+namespace kt2317
+
+internal final fun jet.Any?.bar(): jet.Tuple0
+internal final fun jet.Any?.baz(): jet.Int
+internal final fun foo(/*0*/ l: jet.Long?): jet.Int?
+internal final fun quux(/*0*/ x: jet.Int?): jet.Tuple0
+// </namespace name="kt2317">
diff --git a/compiler/testData/lazyResolve/diagnostics/extensions/kt819ExtensionProperties.txt b/compiler/testData/lazyResolve/diagnostics/extensions/kt819ExtensionProperties.txt
new file mode 100644
index 0000000000000..877ed049f4dab
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/extensions/kt819ExtensionProperties.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal open fun jet.Int.foo(): jet.Tuple0
+ internal open val jet.Int.foo: jet.Int
+ internal open fun jet.String.foo(): jet.Tuple0
+ internal open val jet.String.foo: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ fun jet.Int.foo(): jet.Tuple0
+ internal open override /*1*/ val jet.Int.foo: jet.Int
+ internal open override /*1*/ fun jet.String.foo(): jet.Tuple0
+ internal open override /*1*/ val jet.String.foo: jet.Int
+ internal final fun use(/*0*/ s: jet.String): jet.Tuple0
+}
+internal final val java.io.InputStream.buffered: java.io.BufferedInputStream
+internal final val java.io.Reader.buffered: java.io.BufferedReader
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/Projections.txt b/compiler/testData/lazyResolve/diagnostics/generics/Projections.txt
new file mode 100644
index 0000000000000..a323465fdb0ce
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/Projections.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+internal final class In</*0*/ in T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ in T : jet.Any?><init>(): In<T>
+ internal final fun f(/*0*/ t: T): jet.Tuple0
+ internal final fun f(/*0*/ t: jet.Int): jet.Int
+ internal final fun f1(/*0*/ t: T): jet.Tuple0
+}
+internal final class Inv</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): Inv<T>
+ internal final fun f(/*0*/ t: T): T
+ internal final fun inf(/*0*/ t: T): jet.Tuple0
+ internal final fun outf(): T
+}
+internal final class Out</*0*/ out T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ out T : jet.Any?><init>(): Out<T>
+ internal final fun f(): T
+ internal final fun f(/*0*/ a: jet.Int): jet.Int
+}
+internal final fun testInOut(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundCheck.txt b/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundCheck.txt
new file mode 100644
index 0000000000000..a6c9123ef914a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundCheck.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class C</*0*/ T : C<T>> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : C<T>><init>(): C<T>
+}
+internal final class TestFail : C<C<TestFail>> {
+ public final /*constructor*/ fun <init>(): TestFail
+}
+internal final class TestOK : C<TestOK> {
+ public final /*constructor*/ fun <init>(): TestOK
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundWithTwoArguments.txt b/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundWithTwoArguments.txt
new file mode 100644
index 0000000000000..94876dfa4ca1b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/RecursiveUpperBoundWithTwoArguments.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class D</*0*/ A : D<A, jet.String>, /*1*/ B : D<A, B>> : jet.Any {
+ public final /*constructor*/ fun </*0*/ A : D<A, jet.String>, /*1*/ B : D<A, B>><init>(): D<A, B>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Class.txt b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Class.txt
new file mode 100644
index 0000000000000..f6f869157ef13
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Class.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class C</*0*/ T : C<T>> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : C<T>><init>(): C<T>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/kt1575-ClassObject.txt b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-ClassObject.txt
new file mode 100644
index 0000000000000..5afc6944ac6e6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-ClassObject.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class CO</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): CO<T>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Function.txt b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Function.txt
new file mode 100644
index 0000000000000..42516ea3bdc97
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/generics/kt1575-Function.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class C</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): C<T>
+}
+internal final fun </*0*/ T : C<T>>foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/arrayBracketsRange.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/arrayBracketsRange.txt
new file mode 100644
index 0000000000000..95c1f1a60ff5e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/arrayBracketsRange.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="b">
+namespace b
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="b">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/checkBackingFieldException.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/checkBackingFieldException.txt
new file mode 100644
index 0000000000000..267fa8fd9bcc3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/checkBackingFieldException.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="h">
+namespace h
+
+internal final class h.Square : jet.Any {
+ public final /*constructor*/ fun <init>(): h.Square
+ internal final var area: jet.Double private set
+ internal final var size: jet.Double
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="h">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/funEquals.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/funEquals.txt
new file mode 100644
index 0000000000000..3ed5be51eb58d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/funEquals.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun foo(): [ERROR : No type, no body]
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteVal.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteVal.txt
new file mode 100644
index 0000000000000..e0371f27491df
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteVal.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final val i: [ERROR : No type, no body]
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteValWithAccessor.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteValWithAccessor.txt
new file mode 100644
index 0000000000000..151368993ca6d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteValWithAccessor.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final val i: jet.String
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteWhen.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteWhen.txt
new file mode 100644
index 0000000000000..bc2eac646d41d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/incompleteWhen.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(/*0*/ a: jet.Any): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/namedFun.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/namedFun.txt
new file mode 100644
index 0000000000000..6789f8ae8f80f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/diagnosticWithSyntaxError/namedFun.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun bar(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/incompleteAssignment.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/incompleteAssignment.txt
new file mode 100644
index 0000000000000..07e455fd78a4a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/incompleteAssignment.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="sum">
+namespace sum
+
+internal final fun </*0*/ T : jet.Any?>assertEquals(/*0*/ actual: T?, /*1*/ expected: T?, /*2*/ message: jet.Any? = ?): jet.Tuple0
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun sum(/*0*/ a: jet.IntArray): jet.Int
+internal final fun test(/*0*/ expectedSum: jet.Int, /*1*/ vararg data: jet.Int /*jet.IntArray*/): jet.Tuple0
+// </namespace name="sum">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt1955.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt1955.txt
new file mode 100644
index 0000000000000..ca6901ec7cba0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt1955.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="b">
+namespace b
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="b">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt2014.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt2014.txt
new file mode 100644
index 0000000000000..3b79ea2e6dc75
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/kt2014.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final class c.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): c.Foo
+ internal final val a: jet.Int
+ internal final fun bar(/*0*/ i: jet.Int): jet.Int
+ internal final fun prop(): jet.Int
+}
+internal final val R: c.R
+internal final fun x(/*0*/ f: c.Foo): jet.Tuple0
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/plusOnTheRight.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/plusOnTheRight.txt
new file mode 100644
index 0000000000000..3a36d1927325f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/plusOnTheRight.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final class a.MyClass1 : jet.Any {
+ public final /*constructor*/ fun <init>(): a.MyClass1
+ public final fun plus(): jet.Tuple0
+}
+internal final fun main(/*0*/ arg: a.MyClass1): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/pseudocodeTraverseNextInstructions.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/pseudocodeTraverseNextInstructions.txt
new file mode 100644
index 0000000000000..ca6901ec7cba0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/pseudocodeTraverseNextInstructions.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="b">
+namespace b
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="b">
diff --git a/compiler/testData/lazyResolve/diagnostics/incompleteCode/senselessComparisonWithNull.txt b/compiler/testData/lazyResolve/diagnostics/incompleteCode/senselessComparisonWithNull.txt
new file mode 100644
index 0000000000000..0bcc99a0c816e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/incompleteCode/senselessComparisonWithNull.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="d">
+namespace d
+
+internal final fun foo(/*0*/ a: jet.IntArray): jet.Tuple0
+// </namespace name="d">
diff --git a/compiler/testData/lazyResolve/diagnostics/inference/NoInferenceFromDeclaredBounds.txt b/compiler/testData/lazyResolve/diagnostics/inference/NoInferenceFromDeclaredBounds.txt
new file mode 100644
index 0000000000000..3ee17563fd3fb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/inference/NoInferenceFromDeclaredBounds.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final val n: jet.Nothing
+internal final fun foo1(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>fooT22(): T?
diff --git a/compiler/testData/lazyResolve/diagnostics/inference/kt1293.txt b/compiler/testData/lazyResolve/diagnostics/inference/kt1293.txt
new file mode 100644
index 0000000000000..53a80612617f8
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/inference/kt1293.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt1293">
+namespace kt1293
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun requiresInt(/*0*/ i: jet.Int): jet.Tuple0
+// </namespace name="kt1293">
diff --git a/compiler/testData/lazyResolve/diagnostics/infos/Autocasts.txt b/compiler/testData/lazyResolve/diagnostics/infos/Autocasts.txt
new file mode 100644
index 0000000000000..cb71a027ad8e5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/infos/Autocasts.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun foo(): jet.Tuple0
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal final fun bar(): jet.Tuple0
+ internal final override /*1*/ fun foo(): jet.Tuple0
+}
+internal final class C : A {
+ public final /*constructor*/ fun <init>(): C
+ internal final fun bar(): jet.Tuple0
+ internal final override /*1*/ fun foo(): jet.Tuple0
+}
+internal final fun declarationInsidePattern(/*0*/ x: jet.Tuple2<out jet.Any, out jet.Any>): jet.String
+internal final fun declarations(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun f(): jet.String
+internal final fun f10(/*0*/ init: A?): jet.Tuple0
+internal final fun f101(/*0*/ a: A?): jet.Tuple0
+internal final fun f11(/*0*/ a: A?): jet.Tuple0
+internal final fun f12(/*0*/ a: A?): jet.Tuple0
+internal final fun f13(/*0*/ a: A?): jet.Tuple0
+internal final fun f14(/*0*/ a: A?): jet.Tuple0
+internal final fun f15(/*0*/ a: A?): jet.Tuple0
+internal final fun f9(/*0*/ init: A?): jet.Tuple0
+internal final fun foo(/*0*/ a: jet.Any): jet.Int
+internal final fun getStringLength(/*0*/ obj: jet.Any): jet.Char?
+internal final fun illegalTupleReturnType(/*0*/ a: jet.Any): jet.Tuple2<out jet.Any, out jet.String>
+internal final fun illegalWhenBlock(/*0*/ a: jet.Any): jet.Int
+internal final fun illegalWhenBody(/*0*/ a: jet.Any): jet.Int
+internal final fun mergeAutocasts(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun returnFunctionLiteral(/*0*/ a: jet.Any?): jet.Function0<jet.Int>
+internal final fun returnFunctionLiteralBlock(/*0*/ a: jet.Any?): jet.Function0<jet.Int>
+internal final fun toInt(/*0*/ i: jet.Int?): jet.Int
+internal final fun tuples(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun vars(/*0*/ a: jet.Any?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/infos/PropertiesWithBackingFields.txt b/compiler/testData/lazyResolve/diagnostics/infos/PropertiesWithBackingFields.txt
new file mode 100644
index 0000000000000..d1c732f4f13e0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/infos/PropertiesWithBackingFields.txt
@@ -0,0 +1,46 @@
+namespace <root>
+
+internal open class Super : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ i: jet.Int): Super
+}
+internal abstract class Test : jet.Any {
+ public final /*constructor*/ fun <init>(): Test
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+ internal final val c1: jet.Int
+ internal final val c2: jet.Int
+ internal final val c3: jet.Int
+ internal final val c4: jet.Int
+ internal final val c5: jet.Int
+ internal final val c: jet.Int
+ internal final var v10: jet.Int
+ internal abstract val v11: jet.Int
+ internal abstract var v12: jet.Int
+ internal final var v1: jet.Int
+ internal final var v2: jet.Int
+ internal final var v3: jet.Int
+ internal final var v4: jet.Int
+ internal final var v5: jet.Int
+ internal final var v6: jet.Int
+ internal abstract val v7: jet.Int
+ internal abstract var v8: jet.Int
+ internal final var v9: jet.Int
+ internal final var v: jet.Int
+ internal abstract val x1: jet.Int
+ internal abstract val x2: jet.Int
+ internal abstract val x: jet.Int
+ internal abstract var y1: jet.Int
+ internal abstract var y2: jet.Int
+ internal abstract var y3: jet.Int
+ internal abstract var y4: jet.Int
+ internal abstract var y5: jet.Int
+ internal abstract var y6: jet.Int
+ internal abstract var y: jet.Int
+}
+internal final class TestPCParameters : Super {
+ public final /*constructor*/ fun <init>(/*0*/ w: jet.Int, /*1*/ x: jet.Int, /*2*/ y: jet.Int, /*3*/ z: jet.Int): TestPCParameters
+ internal final fun foo(): [ERROR : Error function type]
+ internal final val xx: jet.Int
+ internal final val y: jet.Int
+ internal final var z: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/OverrideVararg.txt b/compiler/testData/lazyResolve/diagnostics/j+k/OverrideVararg.txt
new file mode 100644
index 0000000000000..189d3c78eadc7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/OverrideVararg.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+public abstract class Aaa : java.lang.Object {
+ public final /*constructor*/ fun <init>(): Aaa
+ public abstract fun foo(/*0*/ vararg args: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+}
+internal final class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+ public open override /*1*/ fun foo(/*0*/ vararg args: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/StaticMembersFromSuperclasses.txt b/compiler/testData/lazyResolve/diagnostics/j+k/StaticMembersFromSuperclasses.txt
new file mode 100644
index 0000000000000..57726bf42fcf7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/StaticMembersFromSuperclasses.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+public open class Aaa : java.lang.Object {
+ public final /*constructor*/ fun <init>(): Aaa
+}
+public open class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+}
+internal final fun foo(): jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-SpecialTypes.txt b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-SpecialTypes.txt
new file mode 100644
index 0000000000000..e6e67c4233ef3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-SpecialTypes.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+public open class A : java.lang.Object {
+ public final /*constructor*/ fun <init>(): A
+}
+public open class X</*0*/ T : jet.Any?> : java.lang.Object {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ package open fun barN(/*0*/ a: T): jet.Tuple0
+ package open fun fooN(): T
+}
+public open class Y : X<jet.String> {
+ public final /*constructor*/ fun <init>(): Y
+ package open override /*1*/ fun barN(/*0*/ a: jet.String): jet.Tuple0
+ package open override /*1*/ fun fooN(): jet.String
+}
+internal final fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-UserTypes.txt b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-UserTypes.txt
new file mode 100644
index 0000000000000..22612bdce8418
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-NotNull-UserTypes.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+public open class A : java.lang.Object {
+ public final /*constructor*/ fun <init>(): A
+}
+public open class X</*0*/ T : jet.Any?> : java.lang.Object {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ package open fun barN(/*0*/ a: T): jet.Tuple0
+ package open fun fooN(): T
+}
+public open class Y : X<A> {
+ public final /*constructor*/ fun <init>(): Y
+ package open override /*1*/ fun barN(/*0*/ a: A): jet.Tuple0
+ package open override /*1*/ fun fooN(): A
+}
+internal final fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-SpecialTypes.txt b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-SpecialTypes.txt
new file mode 100644
index 0000000000000..06d09f0466b3d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-SpecialTypes.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+public open class A : java.lang.Object {
+ public final /*constructor*/ fun <init>(): A
+}
+public open class X</*0*/ T : jet.Any?> : java.lang.Object {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ package open fun bar(/*0*/ a: T?): jet.Tuple0
+ package open fun foo(): T?
+}
+public open class Y : X<jet.String> {
+ public final /*constructor*/ fun <init>(): Y
+ package open override /*1*/ fun bar(/*0*/ a: jet.String?): jet.Tuple0
+ package open override /*1*/ fun foo(): jet.String?
+}
+internal final fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-UserTypes.txt b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-UserTypes.txt
new file mode 100644
index 0000000000000..c0645c7f2224a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/j+k/SupertypeArgumentsNullability-UserTypes.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+public open class A : java.lang.Object {
+ public final /*constructor*/ fun <init>(): A
+}
+public open class X</*0*/ T : jet.Any?> : java.lang.Object {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ package open fun bar(/*0*/ a: T?): jet.Tuple0
+ package open fun foo(): T?
+}
+public open class Y : X<A> {
+ public final /*constructor*/ fun <init>(): Y
+ package open override /*1*/ fun bar(/*0*/ a: A?): jet.Tuple0
+ package open override /*1*/ fun foo(): A?
+}
+internal final fun main(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListAndMap.txt b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListAndMap.txt
new file mode 100644
index 0000000000000..0aad809dfb8b1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListAndMap.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kotlin1">
+namespace kotlin1
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun test(/*0*/ a: java.util.List<jet.Int>, /*1*/ m: java.util.Map<jet.String, jet.Int>): jet.Tuple0
+// </namespace name="kotlin1">
diff --git a/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListClone.txt b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListClone.txt
new file mode 100644
index 0000000000000..1bc597a31a8d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListClone.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kotlin1">
+namespace kotlin1
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kotlin1">
diff --git a/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListToArray.txt b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListToArray.txt
new file mode 100644
index 0000000000000..1bc597a31a8d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/jdk-annotations/ArrayListToArray.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kotlin1">
+namespace kotlin1
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kotlin1">
diff --git a/compiler/testData/lazyResolve/diagnostics/library/kt828.txt b/compiler/testData/lazyResolve/diagnostics/library/kt828.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/library/kt828.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/AssertNotNull.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/AssertNotNull.txt
new file mode 100644
index 0000000000000..dc622bf14c5ed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/AssertNotNull.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/InfixCallNullability.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/InfixCallNullability.txt
new file mode 100644
index 0000000000000..8e877cf97c3bc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/InfixCallNullability.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun contains(/*0*/ a: jet.Any?): jet.Boolean
+ internal final fun minus(): jet.Tuple0
+ internal final fun plus(/*0*/ i: jet.Int): jet.Tuple0
+}
+internal final fun A.div(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun test(/*0*/ x: jet.Int?, /*1*/ a: A?): jet.Tuple0
+internal final fun A?.times(/*0*/ i: jet.Int): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/NullableNothingIsExactlyNull.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/NullableNothingIsExactlyNull.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/NullableNothingIsExactlyNull.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/PreferExtensionsOnNullableReceiver.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/PreferExtensionsOnNullableReceiver.txt
new file mode 100644
index 0000000000000..fbae1cecec9be
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/PreferExtensionsOnNullableReceiver.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+ internal final fun foo(): jet.Tuple0
+}
+internal final fun jet.Any?.foo(): jet.Tuple0
+internal final fun test(/*0*/ f: Foo?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/QualifiedExpressionNullability.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/QualifiedExpressionNullability.txt
new file mode 100644
index 0000000000000..6eb0e520c461f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/QualifiedExpressionNullability.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+ internal final fun foo(/*0*/ a: Foo): Foo
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/ReceiverNullability.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/ReceiverNullability.txt
new file mode 100644
index 0000000000000..1e7b0cb167619
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/ReceiverNullability.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun foo(): jet.Tuple0
+}
+internal final fun A.bar(): jet.Tuple0
+internal final fun A?.buzz(): jet.Tuple0
+internal final fun test(/*0*/ a: A?): jet.Tuple0
+internal final fun A.test2(): jet.Tuple0
+internal final fun A?.test3(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/funcLiteralArgsInsideUnresolvedFunction.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/funcLiteralArgsInsideUnresolvedFunction.txt
new file mode 100644
index 0000000000000..f09c4dce1a220
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/funcLiteralArgsInsideUnresolvedFunction.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1270.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1270.txt
new file mode 100644
index 0000000000000..0987b0c6178c7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1270.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt1270">
+namespace kt1270
+
+private final class kt1270.SomeClass : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1270.SomeClass
+ internal final val value: jet.Int
+}
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt1270">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1680.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1680.txt
new file mode 100644
index 0000000000000..c02b697d9c723
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1680.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt1680">
+namespace kt1680
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt1680">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1778.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1778.txt
new file mode 100644
index 0000000000000..0051c85e82945
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt1778.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt1778">
+namespace kt1778
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt1778">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2109.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2109.txt
new file mode 100644
index 0000000000000..fbd0b5234342f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2109.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt2109">
+namespace kt2109
+
+internal final class kt2109.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt2109.A
+ internal final fun foo(): jet.Tuple0
+}
+internal final fun kt2109.A?.bar(): jet.Tuple0
+internal final fun kt2109.A.baz(): jet.Tuple0
+// </namespace name="kt2109">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2125.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2125.txt
new file mode 100644
index 0000000000000..517ad563608db
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2125.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="e">
+namespace e
+
+internal final fun main(): jet.Tuple0
+// </namespace name="e">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2146.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2146.txt
new file mode 100644
index 0000000000000..c23acec5508a7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2146.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt2146">
+namespace kt2146
+
+internal final fun f1(/*0*/ s: jet.Int?): jet.Int
+internal final fun f2(/*0*/ s: jet.Int?): jet.Int
+internal final fun f3(/*0*/ s: jet.Int?): jet.Int
+internal final fun f4(/*0*/ s: jet.Int?): jet.Int
+internal final fun f5(/*0*/ s: jet.Int?): jet.Int
+internal final fun f6(/*0*/ s: jet.Int?): jet.Int
+internal final fun f7(/*0*/ s: jet.Int?): jet.Int
+// </namespace name="kt2146">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2164.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2164.txt
new file mode 100644
index 0000000000000..781130097a8de
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2164.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt2164">
+namespace kt2164
+
+internal final fun foo(/*0*/ x: jet.Int): jet.Int
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt2164">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2176.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2176.txt
new file mode 100644
index 0000000000000..7ec2e1d1bd499
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2176.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt2176">
+namespace kt2176
+
+internal final fun f1(/*0*/ a: jet.String?): jet.Tuple0
+internal final fun f2(/*0*/ a: jet.String): jet.Tuple0
+internal final fun f3(/*0*/ a: jet.Any?): jet.Tuple0
+internal final fun f4(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun f5(/*0*/ a: jet.String): jet.Tuple0
+// </namespace name="kt2176">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2195.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2195.txt
new file mode 100644
index 0000000000000..ff237fac1cf17
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2195.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="foo">
+namespace foo
+
+private final fun </*0*/ T : jet.Any?>sendCommand(/*0*/ errorCallback: jet.Function0<jet.Tuple0>? = ?): jet.Tuple0
+// </namespace name="foo">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2212.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2212.txt
new file mode 100644
index 0000000000000..5f80ce6a9e57f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2212.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt2212">
+namespace kt2212
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt2212">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2216.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2216.txt
new file mode 100644
index 0000000000000..cd5bbc37a1c2f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2216.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="kt2216">
+namespace kt2216
+
+internal final fun bar(/*0*/ y: jet.Int, /*1*/ z: jet.Int): jet.Int
+internal final fun baz(/*0*/ a: jet.Int, /*1*/ b: jet.Int, /*2*/ c: jet.Int, /*3*/ d: jet.Int): jet.Int
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt2216">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2223.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2223.txt
new file mode 100644
index 0000000000000..4064d3443d8d5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2223.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="kt2223">
+namespace kt2223
+
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt2223">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2234.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2234.txt
new file mode 100644
index 0000000000000..bd37813b0997b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt2234.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun foo(): jet.Tuple0
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt244.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt244.txt
new file mode 100644
index 0000000000000..5934e1aa9b488
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt244.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt244">
+namespace kt244
+
+internal final class kt244.A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ a: jet.String?): kt244.A
+ internal final val b: jet.Int
+ internal final val i: jet.Int
+}
+internal final fun f(/*0*/ s: jet.String?): jet.Tuple0
+// </namespace name="kt244">
diff --git a/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt362.txt b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt362.txt
new file mode 100644
index 0000000000000..f852a63f2f04e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/nullabilityAndAutoCasts/kt362.txt
@@ -0,0 +1,23 @@
+namespace <root>
+
+// <namespace name="example">
+namespace example
+
+internal final fun test(): jet.Tuple0
+// </namespace name="example">
+// <namespace name="test">
+namespace test
+
+internal final class test.Internal : jet.Any {
+ public final val public: jet.Int?
+ protected final val protected: jet.Int?
+ internal final val internal: jet.Int?
+ public final /*constructor*/ fun <init>(): test.Internal
+}
+public final class test.Public : jet.Any {
+ public final val public: jet.Int?
+ protected final val protected: jet.Int?
+ internal final val internal: jet.Int?
+ public final /*constructor*/ fun <init>(): test.Public
+}
+// </namespace name="test">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/Objects.txt b/compiler/testData/lazyResolve/diagnostics/objects/Objects.txt
new file mode 100644
index 0000000000000..4439d3ed6cdf0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/Objects.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="toplevelObjectDeclarations">
+namespace toplevelObjectDeclarations
+
+internal open class toplevelObjectDeclarations.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ y: jet.Int): toplevelObjectDeclarations.Foo
+ internal open fun foo(): jet.Int
+}
+internal final class toplevelObjectDeclarations.T : toplevelObjectDeclarations.Foo {
+ public final /*constructor*/ fun <init>(): toplevelObjectDeclarations.T
+ internal open override /*1*/ fun foo(): jet.Int
+}
+internal final val A: toplevelObjectDeclarations.A
+internal final val B: toplevelObjectDeclarations.B
+internal final val x: jet.Int
+internal final val y: toplevelObjectDeclarations.<no name provided>
+internal final val z: jet.Int
+// </namespace name="toplevelObjectDeclarations">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/ObjectsInheritance.txt b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsInheritance.txt
new file mode 100644
index 0000000000000..55f2510996fcf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsInheritance.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="toplevelObjectDeclarations">
+namespace toplevelObjectDeclarations
+
+internal final val CObj: toplevelObjectDeclarations.CObj
+internal final val DOjb: toplevelObjectDeclarations.DOjb
+// </namespace name="toplevelObjectDeclarations">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/ObjectsLocal.txt b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsLocal.txt
new file mode 100644
index 0000000000000..a3d8c4efaf419
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsLocal.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="localObjects">
+namespace localObjects
+
+internal open class localObjects.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): localObjects.Foo
+ internal final fun foo(): jet.Int
+}
+internal final val A: localObjects.A
+internal final val bb: [ERROR : <ERROR FUNCTION RETURN TYPE>]
+internal final fun test(): jet.Tuple0
+// </namespace name="localObjects">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/ObjectsNested.txt b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsNested.txt
new file mode 100644
index 0000000000000..8bbf7d09cd85c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/ObjectsNested.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="nestedObejcts">
+namespace nestedObejcts
+
+internal final val A: nestedObejcts.A
+internal final val B: nestedObejcts.B
+internal final val a: nestedObejcts.A
+internal final val b: nestedObejcts.B
+internal final val c: nestedObejcts.A.B
+internal final val d: nestedObejcts.A.B.A
+internal final val e: [ERROR : <ERROR PROPERTY TYPE>]
+// </namespace name="nestedObejcts">
diff --git a/compiler/testData/lazyResolve/diagnostics/objects/kt2240.txt b/compiler/testData/lazyResolve/diagnostics/objects/kt2240.txt
new file mode 100644
index 0000000000000..880ac59f2ce1a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/objects/kt2240.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final class a.A : jet.Any {
+ public final /*constructor*/ fun <init>(): a.A
+}
+internal final val o: a.<no name provided>
+internal final fun </*0*/ T : jet.Any?>a.A.foo(/*0*/ f: T): jet.Tuple0
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/AssignOperatorAmbiguity.txt b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/AssignOperatorAmbiguity.txt
new file mode 100644
index 0000000000000..7ad0e047ef8cf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/AssignOperatorAmbiguity.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt1820">
+namespace kt1820
+
+internal final class kt1820.MyInt : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ i: jet.Int): kt1820.MyInt
+ internal final val i: jet.Int
+ internal final fun plus(/*0*/ m: kt1820.MyInt): kt1820.MyInt
+}
+internal final fun jet.Any.plusAssign(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun test(/*0*/ m: kt1820.MyInt): jet.Tuple0
+// </namespace name="kt1820">
diff --git a/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/IteratorAmbiguity.txt b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/IteratorAmbiguity.txt
new file mode 100644
index 0000000000000..c6615a95f13fe
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/IteratorAmbiguity.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+internal abstract trait MyAnotherCollectionInterface : jet.Any {
+}
+internal final class MyCollection : MyCollectionInterface, MyAnotherCollectionInterface {
+ public final /*constructor*/ fun <init>(): MyCollection
+}
+internal abstract trait MyCollectionInterface : jet.Any {
+}
+internal final class MyElement : jet.Any {
+ public final /*constructor*/ fun <init>(): MyElement
+}
+internal final class MyIterator : jet.Any {
+ public final /*constructor*/ fun <init>(): MyIterator
+ internal final fun hasNext(): jet.Boolean
+ internal final fun next(): MyElement
+}
+internal final fun MyAnotherCollectionInterface.iterator(): MyIterator
+internal final fun MyCollectionInterface.iterator(): MyIterator
+internal final fun test1(/*0*/ collection: MyCollection): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/kt1028.txt b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/kt1028.txt
new file mode 100644
index 0000000000000..c0d78048d7742
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/operatorsOverloading/kt1028.txt
@@ -0,0 +1,26 @@
+namespace <root>
+
+// <namespace name="kt1028">
+namespace kt1028
+
+internal final class kt1028.Control : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1028.Control
+ public final val MouseMoved: kt1028.event<kt1028.MouseMovedEventArgs>
+ internal final fun MoveMouse(): jet.Tuple0
+}
+internal final class kt1028.MouseMovedEventArgs : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1028.MouseMovedEventArgs
+ public final val X: jet.Int
+}
+internal final class kt1028.Test : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1028.Test
+ internal final fun test(): jet.Tuple0
+}
+internal final class kt1028.event</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): kt1028.event<T>
+ internal final fun call(/*0*/ value: T): jet.Tuple0
+ internal final val callbacks: java.util.ArrayList<jet.Function1<T, jet.Tuple0>>
+ internal final fun minusAssign(/*0*/ f: jet.Function1<T, jet.Tuple0>): jet.Boolean
+ internal final fun plusAssign(/*0*/ f: jet.Function1<T, jet.Tuple0>): jet.Boolean
+}
+// </namespace name="kt1028">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInClass.txt
new file mode 100644
index 0000000000000..7023b439ed12e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun a(/*0*/ a: jet.Int): jet.Int
+ internal final fun a(/*0*/ a: jet.Int): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInPackage.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInPackage.txt
new file mode 100644
index 0000000000000..b0f26b10ac738
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsFunsDifferentReturnInPackage.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="qwertyuiop">
+namespace qwertyuiop
+
+internal final fun c(/*0*/ s: jet.String): jet.Tuple0
+internal final fun c(/*0*/ s: jet.String): jet.Tuple0
+// </namespace name="qwertyuiop">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalExtFunsInPackage.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalExtFunsInPackage.txt
new file mode 100644
index 0000000000000..2bee10793dd14
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalExtFunsInPackage.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="extensionFunctions">
+namespace extensionFunctions
+
+internal final fun jet.Int.qwe(/*0*/ a: jet.Float): jet.Int
+internal final fun jet.Int.qwe(/*0*/ a: jet.Float): jet.Int
+// </namespace name="extensionFunctions">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalFunsInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalFunsInClass.txt
new file mode 100644
index 0000000000000..fe0cebc975091
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalFunsInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun b(): jet.Tuple0
+ internal final fun b(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalValsInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalValsInClass.txt
new file mode 100644
index 0000000000000..35e6be0f99a50
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsIdenticalValsInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal final val a: jet.Int
+ internal final val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsValsDifferentTypeInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsValsDifferentTypeInClass.txt
new file mode 100644
index 0000000000000..e516646a23fe2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConflictingOverloadsValsDifferentTypeInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal final val a: jet.Int
+ internal final val a: jet.String
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ConstructorVsFunOverload.txt b/compiler/testData/lazyResolve/diagnostics/overload/ConstructorVsFunOverload.txt
new file mode 100644
index 0000000000000..c93803b7356e5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ConstructorVsFunOverload.txt
@@ -0,0 +1,37 @@
+namespace <root>
+
+// <namespace name="constructorVsFun">
+namespace constructorVsFun
+
+internal final class constructorVsFun.Rtyu : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Rtyu
+ internal final fun ololo(): jet.Tuple0
+ internal final object constructorVsFun.Rtyu.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): constructorVsFun.Rtyu.<no name provided>
+ internal final class constructorVsFun.Rtyu.<no name provided>.ololo : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Rtyu.<no name provided>.ololo
+ }
+ }
+}
+internal final class constructorVsFun.Tram : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Tram
+ internal final class constructorVsFun.Tram.f : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Tram.f
+ }
+ internal final fun f(): jet.Tuple0
+}
+internal final class constructorVsFun.Yvayva : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Yvayva
+ internal final object constructorVsFun.Yvayva.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): constructorVsFun.Yvayva.<no name provided>
+ internal final class constructorVsFun.Yvayva.<no name provided>.fghj : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.Yvayva.<no name provided>.fghj
+ }
+ internal final fun fghj(): jet.Tuple0
+ }
+}
+internal final class constructorVsFun.a : jet.Any {
+ public final /*constructor*/ fun <init>(): constructorVsFun.a
+}
+internal final fun a(): jet.Int
+// </namespace name="constructorVsFun">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/ExtFunDifferentReceiver.txt b/compiler/testData/lazyResolve/diagnostics/overload/ExtFunDifferentReceiver.txt
new file mode 100644
index 0000000000000..118f0018e4a3c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/ExtFunDifferentReceiver.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun jet.Int.rty(): jet.Int
+internal final fun jet.String.rty(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/FunNoConflictInDifferentPackages.txt b/compiler/testData/lazyResolve/diagnostics/overload/FunNoConflictInDifferentPackages.txt
new file mode 100644
index 0000000000000..98c8f1da7cb1c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/FunNoConflictInDifferentPackages.txt
@@ -0,0 +1,21 @@
+namespace <root>
+
+// <namespace name="ns1">
+namespace ns1
+
+internal final fun e(): jet.Int
+// </namespace name="ns1">
+// <namespace name="ns2">
+namespace ns2
+
+internal final fun e(): jet.Int
+// </namespace name="ns2">
+// <namespace name="ns3">
+namespace ns3
+
+// <namespace name="ns1">
+namespace ns1
+
+internal final fun e(): jet.Int
+// </namespace name="ns1">
+// </namespace name="ns3">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/OverloadFunRegularAndExt.txt b/compiler/testData/lazyResolve/diagnostics/overload/OverloadFunRegularAndExt.txt
new file mode 100644
index 0000000000000..3749e9defb86f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/OverloadFunRegularAndExt.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="extensionAndRegular">
+namespace extensionAndRegular
+
+internal final fun jet.Int.who(): jet.Int
+internal final fun who(): jet.Int
+// </namespace name="extensionAndRegular">
diff --git a/compiler/testData/lazyResolve/diagnostics/overload/OverloadVarAndFunInClass.txt b/compiler/testData/lazyResolve/diagnostics/overload/OverloadVarAndFunInClass.txt
new file mode 100644
index 0000000000000..fe115c4686577
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/overload/OverloadVarAndFunInClass.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class Aaaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaaa
+ internal final fun bb(): jet.Int
+ internal final val bb: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractFunImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractFunImplemented.txt
new file mode 100644
index 0000000000000..67bfc5cdc2c74
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractFunImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract fun foo(): jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractFunNotImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractFunNotImplemented.txt
new file mode 100644
index 0000000000000..f0a8e4aed57c2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractFunNotImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract fun foo(): jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal abstract override /*1*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractValImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractValImplemented.txt
new file mode 100644
index 0000000000000..1b5c2d0c8f0df
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractValImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract val i: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ val i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractValNotImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractValNotImplemented.txt
new file mode 100644
index 0000000000000..19f4c8a8db3d1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractValNotImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract val i: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal abstract override /*1*/ val i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractVarImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractVarImplemented.txt
new file mode 100644
index 0000000000000..a880e410bb584
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractVarImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract var i: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ var i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/AbstractVarNotImplemented.txt b/compiler/testData/lazyResolve/diagnostics/override/AbstractVarNotImplemented.txt
new file mode 100644
index 0000000000000..aabba56d2f9cc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/AbstractVarNotImplemented.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal abstract class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal abstract var i: jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal abstract override /*1*/ var i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ComplexValRedeclaration.txt b/compiler/testData/lazyResolve/diagnostics/override/ComplexValRedeclaration.txt
new file mode 100644
index 0000000000000..0472c8a3f8cb0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ComplexValRedeclaration.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="override">
+namespace override
+
+// <namespace name="generics">
+namespace generics
+
+internal abstract class override.generics.MyAbstractClass</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): override.generics.MyAbstractClass<T>
+ internal abstract val pr: T
+}
+internal abstract class override.generics.MyLegalAbstractClass2</*0*/ T : jet.Any?> : override.generics.MyAbstractClass<jet.Int> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyLegalAbstractClass2<T>
+ internal final val </*0*/ R : jet.Any?> pr: T
+ internal abstract override /*1*/ val pr: jet.Int
+}
+// </namespace name="generics">
+// </namespace name="override">
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ConflictingFunctionSignatureFromSuperclass.txt b/compiler/testData/lazyResolve/diagnostics/override/ConflictingFunctionSignatureFromSuperclass.txt
new file mode 100644
index 0000000000000..08ea7cab9d645
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ConflictingFunctionSignatureFromSuperclass.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal final fun foo(): jet.Int
+}
+internal open class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+ internal final fun </*0*/ T : jet.Any?>foo(): jet.Int
+ internal final override /*1*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames-MultipleSupertypes.txt b/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames-MultipleSupertypes.txt
new file mode 100644
index 0000000000000..1b56bc4f73b6a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames-MultipleSupertypes.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+internal abstract trait C : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal abstract trait D : jet.Any {
+ internal abstract fun foo(/*0*/ b: jet.Int): jet.Tuple0
+}
+internal abstract trait E : C, D {
+ internal abstract override /*2*/ fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal abstract trait F : C, D {
+ internal open override /*2*/ fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames.txt b/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames.txt
new file mode 100644
index 0000000000000..f9d5dc79fe945
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ConflictingParameterNames.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+internal abstract trait A : jet.Any {
+ internal abstract fun b(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal abstract trait B : A {
+ internal abstract override /*1*/ fun b(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal final class C1 : A {
+ public final /*constructor*/ fun <init>(): C1
+ internal open override /*1*/ fun b(/*0*/ b: jet.Int): jet.Tuple0
+}
+internal final class C2 : B {
+ public final /*constructor*/ fun <init>(): C2
+ internal open override /*1*/ fun b(/*0*/ b: jet.Int): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ConflictingPropertySignatureFromSuperclass.txt b/compiler/testData/lazyResolve/diagnostics/override/ConflictingPropertySignatureFromSuperclass.txt
new file mode 100644
index 0000000000000..d7f55dd3917d5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ConflictingPropertySignatureFromSuperclass.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal final val bar: jet.Int
+}
+internal open class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+ internal final override /*1*/ val bar: jet.Int
+ internal final val </*0*/ T : jet.Any?> bar: jet.String
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValueInOverride.txt b/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValueInOverride.txt
new file mode 100644
index 0000000000000..a86972510e2f2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValueInOverride.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal open fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal final class C : A {
+ public final /*constructor*/ fun <init>(): C
+ internal open override /*1*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class D : A {
+ public final /*constructor*/ fun <init>(): D
+ internal open override /*1*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValues-NoErrorsWhenInheritingFromOneTypeTwice.txt b/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValues-NoErrorsWhenInheritingFromOneTypeTwice.txt
new file mode 100644
index 0000000000000..3c03f6051983e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/DefaultParameterValues-NoErrorsWhenInheritingFromOneTypeTwice.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait YSub : Y {
+ internal abstract override /*1*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class Z2 : Y, YSub {
+ public final /*constructor*/ fun <init>(): Z2
+ internal open override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final val Z2O: Z2O
diff --git a/compiler/testData/lazyResolve/diagnostics/override/EqualityOfIntersectionTypes.txt b/compiler/testData/lazyResolve/diagnostics/override/EqualityOfIntersectionTypes.txt
new file mode 100644
index 0000000000000..7cf9693ba6415
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/EqualityOfIntersectionTypes.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait A : jet.Any {
+ internal open fun </*0*/ T : Bar & Foo>foo(): jet.Tuple0
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ fun </*0*/ T : Bar & Foo>foo(): jet.Tuple0
+}
+internal abstract trait Bar : jet.Any {
+}
+internal abstract trait Foo : jet.Any {
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ExtendFunctionClass.txt b/compiler/testData/lazyResolve/diagnostics/override/ExtendFunctionClass.txt
new file mode 100644
index 0000000000000..eac9e004e33f6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ExtendFunctionClass.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="extendFunctionClass">
+namespace extendFunctionClass
+
+internal final class extendFunctionClass.A : jet.Function1<jet.Int, jet.Int> {
+ public final /*constructor*/ fun <init>(): extendFunctionClass.A
+ public abstract override /*1*/ fun invoke(/*0*/ p1: jet.Int): jet.Int
+}
+internal final class extendFunctionClass.B : jet.Function1<jet.Int, jet.Int> {
+ public final /*constructor*/ fun <init>(): extendFunctionClass.B
+ public open override /*1*/ fun invoke(/*0*/ p1: jet.Int): jet.Int
+}
+// </namespace name="extendFunctionClass">
diff --git a/compiler/testData/lazyResolve/diagnostics/override/FakeOverrideAbstractAndNonAbstractFun.txt b/compiler/testData/lazyResolve/diagnostics/override/FakeOverrideAbstractAndNonAbstractFun.txt
new file mode 100644
index 0000000000000..6c2c32fc25212
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/FakeOverrideAbstractAndNonAbstractFun.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal open class Ccc : jet.Any {
+ public final /*constructor*/ fun <init>(): Ccc
+ internal final fun foo(): jet.Int
+}
+internal abstract trait Ttt : jet.Any {
+ internal abstract fun foo(): jet.Int
+}
+internal final class Zzz : Ccc, Ttt {
+ public final /*constructor*/ fun <init>(): Zzz
+ internal final override /*2*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/Generics.txt b/compiler/testData/lazyResolve/diagnostics/override/Generics.txt
new file mode 100644
index 0000000000000..244bcf1a9eca3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/Generics.txt
@@ -0,0 +1,105 @@
+namespace <root>
+
+// <namespace name="override">
+namespace override
+
+// <namespace name="generics">
+namespace generics
+
+internal abstract class override.generics.MyAbstractClass</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): override.generics.MyAbstractClass<T>
+ internal abstract fun bar(/*0*/ t: T): T
+ internal abstract val pr: T
+}
+internal abstract class override.generics.MyAbstractClass1 : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.String> {
+ public final /*constructor*/ fun <init>(): override.generics.MyAbstractClass1
+ internal open override /*1*/ fun bar(/*0*/ t: jet.String): jet.String
+ internal open override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal abstract override /*1*/ val pr: jet.String
+}
+internal final class override.generics.MyChildClass : override.generics.MyGenericClass<jet.Int> {
+ public final /*constructor*/ fun <init>(): override.generics.MyChildClass
+ internal open override /*1*/ fun bar(/*0*/ t: jet.Int): jet.Int
+ internal open override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal open override /*1*/ val p: jet.Int
+ internal open override /*1*/ val pr: jet.Int
+}
+internal final class override.generics.MyChildClass1</*0*/ T : jet.Any?> : override.generics.MyGenericClass<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyChildClass1<T>
+ internal open override /*1*/ fun bar(/*0*/ t: T): T
+ internal open override /*1*/ fun foo(/*0*/ t: T): T
+ internal open override /*1*/ val p: T
+ internal open override /*1*/ val pr: T
+}
+internal final class override.generics.MyChildClass2</*0*/ T : jet.Any?> : override.generics.MyGenericClass<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyChildClass2<T>
+ internal open override /*1*/ fun bar(/*0*/ t: T): T
+ internal final override /*1*/ fun foo(/*0*/ t: T): T
+ internal open override /*1*/ val p: T
+ internal final override /*1*/ val pr: T
+}
+internal open class override.generics.MyClass : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.String> {
+ public final /*constructor*/ fun <init>(): override.generics.MyClass
+ internal open override /*1*/ fun bar(/*0*/ t: jet.String): jet.String
+ internal open override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal open override /*1*/ val pr: jet.String
+}
+internal open class override.generics.MyGenericClass</*0*/ T : jet.Any?> : override.generics.MyTrait<T>, override.generics.MyAbstractClass<T>, override.generics.MyProps<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyGenericClass<T>
+ internal open override /*1*/ fun bar(/*0*/ t: T): T
+ internal open override /*1*/ fun foo(/*0*/ t: T): T
+ internal open override /*1*/ val p: T
+ internal open override /*1*/ val pr: T
+}
+internal final class override.generics.MyIllegalClass1 : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.String> {
+ public final /*constructor*/ fun <init>(): override.generics.MyIllegalClass1
+ internal abstract override /*1*/ fun bar(/*0*/ t: jet.String): jet.String
+ internal abstract override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal abstract override /*1*/ val pr: jet.String
+}
+internal final class override.generics.MyIllegalClass2</*0*/ T : jet.Any?> : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.Int> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyIllegalClass2<T>
+ internal final fun bar(/*0*/ t: T): T
+ internal abstract override /*1*/ fun bar(/*0*/ t: jet.Int): jet.Int
+ internal final fun foo(/*0*/ t: T): T
+ internal abstract override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal final val </*0*/ R : jet.Any?> pr: T
+ internal abstract override /*1*/ val pr: jet.Int
+}
+internal final class override.generics.MyIllegalGenericClass1</*0*/ T : jet.Any?> : override.generics.MyTrait<T>, override.generics.MyAbstractClass<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): override.generics.MyIllegalGenericClass1<T>
+ internal abstract override /*1*/ fun bar(/*0*/ t: T): T
+ internal abstract override /*1*/ fun foo(/*0*/ t: T): T
+ internal abstract override /*1*/ val pr: T
+}
+internal final class override.generics.MyIllegalGenericClass2</*0*/ T : jet.Any?, /*1*/ R : jet.Any?> : override.generics.MyTrait<T>, override.generics.MyAbstractClass<R> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?, /*1*/ R : jet.Any?><init>(/*0*/ r: R): override.generics.MyIllegalGenericClass2<T, R>
+ internal abstract override /*1*/ fun bar(/*0*/ t: R): R
+ internal open fun foo(/*0*/ r: R): R
+ internal abstract override /*1*/ fun foo(/*0*/ t: T): T
+ internal abstract override /*1*/ val pr: R
+ internal open val </*0*/ T : jet.Any?> pr: R
+}
+internal abstract class override.generics.MyLegalAbstractClass1 : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.String> {
+ public final /*constructor*/ fun <init>(): override.generics.MyLegalAbstractClass1
+ internal abstract override /*1*/ fun bar(/*0*/ t: jet.String): jet.String
+ internal abstract override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal abstract override /*1*/ val pr: jet.String
+}
+internal abstract class override.generics.MyLegalAbstractClass2</*0*/ T : jet.Any?> : override.generics.MyTrait<jet.Int>, override.generics.MyAbstractClass<jet.Int> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ t: T): override.generics.MyLegalAbstractClass2<T>
+ internal final fun bar(/*0*/ t: T): T
+ internal abstract override /*1*/ fun bar(/*0*/ t: jet.Int): jet.Int
+ internal final fun foo(/*0*/ t: T): T
+ internal abstract override /*1*/ fun foo(/*0*/ t: jet.Int): jet.Int
+ internal final val </*0*/ R : jet.Any?> pr: T
+ internal abstract override /*1*/ val pr: jet.Int
+}
+internal abstract trait override.generics.MyProps</*0*/ T : jet.Any?> : jet.Any {
+ internal abstract val p: T
+}
+internal abstract trait override.generics.MyTrait</*0*/ T : jet.Any?> : jet.Any {
+ internal abstract fun foo(/*0*/ t: T): T
+}
+// </namespace name="generics">
+// </namespace name="override">
diff --git a/compiler/testData/lazyResolve/diagnostics/override/InvisiblePotentialOverride.txt b/compiler/testData/lazyResolve/diagnostics/override/InvisiblePotentialOverride.txt
new file mode 100644
index 0000000000000..5858324151f82
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/InvisiblePotentialOverride.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ private final fun foo(): jet.Int
+}
+internal final class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal final fun foo(): jet.String
+ invisible_fake final override /*1*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypes.txt b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypes.txt
new file mode 100644
index 0000000000000..939fe6bbb7d91
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypes.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait X : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class Z : X, Y {
+ public final /*constructor*/ fun <init>(): Z
+ internal open override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final val ZO: ZO
diff --git a/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypesNoOverride.txt b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypesNoOverride.txt
new file mode 100644
index 0000000000000..95958c0285e0f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultParametersInSupertypesNoOverride.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait X : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class Z : X, Y {
+ public final /*constructor*/ fun <init>(): Z
+ internal final override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final val ZO: ZO
diff --git a/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultsInSupertypesNoExplicitOverride.txt b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultsInSupertypesNoExplicitOverride.txt
new file mode 100644
index 0000000000000..58077d1cddbdf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/MultipleDefaultsInSupertypesNoExplicitOverride.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait X : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final class Z1 : X, Y {
+ public final /*constructor*/ fun <init>(): Z1
+ internal abstract override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal final val Z1O: Z1O
diff --git a/compiler/testData/lazyResolve/diagnostics/override/NonGenerics.txt b/compiler/testData/lazyResolve/diagnostics/override/NonGenerics.txt
new file mode 100644
index 0000000000000..fa125f197f73a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/NonGenerics.txt
@@ -0,0 +1,70 @@
+namespace <root>
+
+// <namespace name="override">
+namespace override
+
+// <namespace name="normal">
+namespace normal
+
+internal abstract class override.normal.MyAbstractClass : jet.Any {
+ public final /*constructor*/ fun <init>(): override.normal.MyAbstractClass
+ internal abstract fun bar(): jet.Tuple0
+ internal abstract val prr: jet.Tuple0
+}
+internal final class override.normal.MyChildClass : override.normal.MyClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyChildClass
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyChildClass1 : override.normal.MyClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyChildClass1
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal final override /*1*/ fun foo(): jet.Tuple0
+ internal final override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal open class override.normal.MyClass : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyClass
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyIllegalClass : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyIllegalClass
+ internal abstract override /*1*/ fun bar(): jet.Tuple0
+ internal abstract override /*1*/ fun foo(): jet.Tuple0
+ internal abstract override /*1*/ val pr: jet.Tuple0
+ internal abstract override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyIllegalClass2 : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyIllegalClass2
+ internal abstract override /*1*/ fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyIllegalClass3 : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyIllegalClass3
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal abstract override /*1*/ fun foo(): jet.Tuple0
+ internal open override /*1*/ val pr: jet.Tuple0
+ internal open override /*1*/ val prr: jet.Tuple0
+}
+internal final class override.normal.MyIllegalClass4 : override.normal.MyTrait, override.normal.MyAbstractClass {
+ public final /*constructor*/ fun <init>(): override.normal.MyIllegalClass4
+ internal abstract override /*1*/ fun bar(): jet.Tuple0
+ internal final override /*1*/ fun foo(): jet.Tuple0
+ internal open fun other(): jet.Tuple0
+ internal open val otherPr: jet.Int
+ internal final override /*1*/ val pr: jet.Tuple0
+ internal abstract override /*1*/ val prr: jet.Tuple0
+}
+internal abstract trait override.normal.MyTrait : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+ internal abstract val pr: jet.Tuple0
+}
+// </namespace name="normal">
+// </namespace name="override">
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ParameterDefaultValues-DefaultValueFromOnlyOneSupertype.txt b/compiler/testData/lazyResolve/diagnostics/override/ParameterDefaultValues-DefaultValueFromOnlyOneSupertype.txt
new file mode 100644
index 0000000000000..9c6fb4c0e60d8
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ParameterDefaultValues-DefaultValueFromOnlyOneSupertype.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal abstract trait X : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
+internal abstract trait Y : jet.Any {
+ internal abstract fun foo(/*0*/ a: jet.Int): jet.Tuple0
+}
+internal final class Z : X, Y {
+ public final /*constructor*/ fun <init>(): Z
+ internal open override /*2*/ fun foo(/*0*/ a: jet.Int = ?): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/SuspiciousCase1.txt b/compiler/testData/lazyResolve/diagnostics/override/SuspiciousCase1.txt
new file mode 100644
index 0000000000000..e70daad2e0fce
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/SuspiciousCase1.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal abstract trait Bar</*0*/ Q : jet.Any?> : Foo<Q> {
+ internal open override /*1*/ fun quux(/*0*/ p: Q, /*1*/ q: jet.Int = ?): jet.Int
+}
+internal abstract class Baz : Bar<jet.String> {
+ public final /*constructor*/ fun <init>(): Baz
+ internal open override /*1*/ fun quux(/*0*/ p: jet.String, /*1*/ q: jet.Int = ?): jet.Int
+}
+internal abstract trait Foo</*0*/ P : jet.Any?> : jet.Any {
+ internal open fun quux(/*0*/ p: P, /*1*/ q: jet.Int = ?): jet.Int
+}
+internal final fun zz(/*0*/ b: Baz): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/override/ToAbstractMembersFromSuper-kt1996.txt b/compiler/testData/lazyResolve/diagnostics/override/ToAbstractMembersFromSuper-kt1996.txt
new file mode 100644
index 0000000000000..c02180a656c3c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/ToAbstractMembersFromSuper-kt1996.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal abstract trait Bar : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+}
+internal final class Baz : Foo, Bar {
+ public final /*constructor*/ fun <init>(): Baz
+ internal abstract override /*2*/ fun foo(): jet.Tuple0
+}
+internal abstract trait Foo : jet.Any {
+ internal abstract fun foo(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/override/kt1862.txt b/compiler/testData/lazyResolve/diagnostics/override/kt1862.txt
new file mode 100644
index 0000000000000..96cc596b29d0b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/override/kt1862.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+internal open class Aaa : jet.Any {
+ public final /*constructor*/ fun <init>(): Aaa
+ internal open fun foo(): jet.Int
+}
+internal open class Bbb : Aaa {
+ public final /*constructor*/ fun <init>(): Bbb
+ internal open override /*1*/ fun foo(): jet.Int
+}
+internal abstract trait Ccc : Aaa {
+ internal open override /*1*/ fun foo(): jet.Int
+}
+internal final class Ddd : Bbb, Ccc {
+ public final /*constructor*/ fun <init>(): Ddd
+ internal open override /*2*/ fun foo(): jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/AmbiguityOnLazyTypeComputation.txt b/compiler/testData/lazyResolve/diagnostics/regressions/AmbiguityOnLazyTypeComputation.txt
new file mode 100644
index 0000000000000..5e9050c2b602d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/AmbiguityOnLazyTypeComputation.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="x">
+namespace x
+
+internal final class x.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): x.Foo
+ internal final fun compareTo(/*0*/ other: jet.Byte): jet.Int
+ internal final fun compareTo(/*0*/ other: jet.Char): jet.Int
+}
+internal final val a1: jet.Int
+internal final val b: x.Foo
+// </namespace name="x">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/AssignmentsUnderOperators.txt b/compiler/testData/lazyResolve/diagnostics/regressions/AssignmentsUnderOperators.txt
new file mode 100644
index 0000000000000..8a9f72ae98682
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/AssignmentsUnderOperators.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/CoercionToUnit.txt b/compiler/testData/lazyResolve/diagnostics/regressions/CoercionToUnit.txt
new file mode 100644
index 0000000000000..400f87e4f3efa
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/CoercionToUnit.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun foo(/*0*/ u: jet.Tuple0): jet.Int
+internal final fun test(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/DoubleDefine.txt b/compiler/testData/lazyResolve/diagnostics/regressions/DoubleDefine.txt
new file mode 100644
index 0000000000000..d4f60be446474
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/DoubleDefine.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final fun evaluate(/*0*/ expr: java.lang.StringBuilder, /*1*/ numbers: java.util.ArrayList<jet.Int>): jet.Int
+internal final fun evaluateAdd(/*0*/ expr: java.lang.StringBuilder, /*1*/ numbers: java.util.ArrayList<jet.Int>): jet.Int
+internal final fun evaluateArg(/*0*/ expr: jet.CharSequence, /*1*/ numbers: java.util.ArrayList<jet.Int>): jet.Int
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun takeFirst(/*0*/ expr: java.lang.StringBuilder): jet.Char
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/ErrorsOnIbjectExpressionsAsParameters.txt b/compiler/testData/lazyResolve/diagnostics/regressions/ErrorsOnIbjectExpressionsAsParameters.txt
new file mode 100644
index 0000000000000..20d98c49f5b1b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/ErrorsOnIbjectExpressionsAsParameters.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun foo(/*0*/ a: jet.Any): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet11.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet11.txt
new file mode 100644
index 0000000000000..70d2d58f77ad5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet11.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal open class NoC : jet.Any {
+ public final /*constructor*/ fun <init>(): NoC
+}
+internal final class NoC1 : NoC {
+ public final /*constructor*/ fun <init>(): NoC1
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet121.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet121.txt
new file mode 100644
index 0000000000000..40656e5f7f5ce
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet121.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="jet121">
+namespace jet121
+
+internal final fun apply(/*0*/ arg: jet.String, /*1*/ f: jet.ExtensionFunction0<jet.String, jet.Int>): jet.Int
+internal final fun box(): jet.String
+// </namespace name="jet121">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet124.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet124.txt
new file mode 100644
index 0000000000000..906406dc8cfb5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet124.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun foo(): jet.Tuple0
+internal final fun foo1(): jet.Function1<jet.Int, jet.Int>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet169.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet169.txt
new file mode 100644
index 0000000000000..485284328720a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet169.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun set(/*0*/ key: jet.String, /*1*/ value: jet.String): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet17.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet17.txt
new file mode 100644
index 0000000000000..4368a0787f0a0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet17.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class WithC : jet.Any {
+ public final /*constructor*/ fun <init>(): WithC
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet53.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet53.txt
new file mode 100644
index 0000000000000..277fb8d2562fe
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet53.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final val ab: java.util.List<jet.Int>?
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet67.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet67.txt
new file mode 100644
index 0000000000000..2afd760a213ce
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet67.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal abstract class XXX : jet.Any {
+ public final /*constructor*/ fun <init>(): XXX
+ internal abstract val a: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet68.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet68.txt
new file mode 100644
index 0000000000000..e28689cf4ae0f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet68.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+}
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet69.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet69.txt
new file mode 100644
index 0000000000000..54d2f7f98be72
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet69.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class Command : jet.Any {
+ public final /*constructor*/ fun <init>(): Command
+}
+internal final fun jet.Any.equals(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun parse(/*0*/ cmd: jet.String): Command?
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet72.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet72.txt
new file mode 100644
index 0000000000000..0d868ac29e52b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet72.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal abstract class Item : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ room: java.lang.Object): Item
+ internal abstract val name: jet.String
+ internal final val room: java.lang.Object
+}
+internal final val items: java.util.ArrayList<Item>
+internal final fun test(/*0*/ room: java.lang.Object): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/Jet81.txt b/compiler/testData/lazyResolve/diagnostics/regressions/Jet81.txt
new file mode 100644
index 0000000000000..4a8d5b1db0dc4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/Jet81.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final val A: A
+internal final val a: <no name provided>
+internal final val b: [ERROR : <ERROR PROPERTY TYPE>]
+internal final val c: jet.Int
+internal final val y: <no name provided>
+internal final val z: [ERROR : Type for y]
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/OrphanStarProjection.txt b/compiler/testData/lazyResolve/diagnostics/regressions/OrphanStarProjection.txt
new file mode 100644
index 0000000000000..b5ae30814e185
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/OrphanStarProjection.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class B : jet.Any {
+ public final /*constructor*/ fun <init>(): B
+}
+internal final val b: [ERROR : B<*>]
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/OutProjections.txt b/compiler/testData/lazyResolve/diagnostics/regressions/OutProjections.txt
new file mode 100644
index 0000000000000..0e734f7d29c10
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/OutProjections.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+internal final class G</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): G<T>
+}
+internal final class Out</*0*/ out T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ out T : jet.Any?><init>(): Out<T>
+}
+internal final class Point : jet.Any {
+ public final /*constructor*/ fun <init>(): Point
+}
+internal final fun </*0*/ T : jet.Any?>f(/*0*/ expression: T): G<out T>
+internal final fun foo(): G<Point>
+internal final fun fooout(): Out<Point>
+internal final fun </*0*/ T : jet.Any?>fout(/*0*/ expression: T): Out<out T>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/OverrideResolution.txt b/compiler/testData/lazyResolve/diagnostics/regressions/OverrideResolution.txt
new file mode 100644
index 0000000000000..fa981b347d6d7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/OverrideResolution.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal open fun foo(): jet.Tuple0
+}
+internal open class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal open override /*1*/ fun foo(): jet.Tuple0
+}
+internal open class C : B {
+ public final /*constructor*/ fun <init>(): C
+ internal open override /*1*/ fun foo(): jet.Tuple0
+}
+internal final fun box(/*0*/ c: C): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/SpecififcityByReceiver.txt b/compiler/testData/lazyResolve/diagnostics/regressions/SpecififcityByReceiver.txt
new file mode 100644
index 0000000000000..4cd7eebe6393b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/SpecififcityByReceiver.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun jet.Any.equals(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/TypeMismatchOnUnaryOperations.txt b/compiler/testData/lazyResolve/diagnostics/regressions/TypeMismatchOnUnaryOperations.txt
new file mode 100644
index 0000000000000..dc622bf14c5ed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/TypeMismatchOnUnaryOperations.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/TypeParameterAsASupertype.txt b/compiler/testData/lazyResolve/diagnostics/regressions/TypeParameterAsASupertype.txt
new file mode 100644
index 0000000000000..2861640864159
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/TypeParameterAsASupertype.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class A</*0*/ T : jet.Any?> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): A<T>
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/UnavaliableQualifiedThis.txt b/compiler/testData/lazyResolve/diagnostics/regressions/UnavaliableQualifiedThis.txt
new file mode 100644
index 0000000000000..2a808d697c821
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/UnavaliableQualifiedThis.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal abstract trait Iterator</*0*/ out T : jet.Any?> : jet.Any {
+ internal abstract val hasNext: jet.Boolean
+ internal open fun </*0*/ R : jet.Any?>map(/*0*/ transform: jet.Function1<T, R>): Iterator<R>
+ internal abstract fun next(): T
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/WrongTraceInCallResolver.txt b/compiler/testData/lazyResolve/diagnostics/regressions/WrongTraceInCallResolver.txt
new file mode 100644
index 0000000000000..b0b8e8d9c68cc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/WrongTraceInCallResolver.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class Bar : jet.Any {
+ public final /*constructor*/ fun <init>(): Bar
+}
+internal open class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+}
+internal final fun f(): jet.Tuple0
+internal final fun </*0*/ T : Bar, /*1*/ T1 : jet.Any?>foo(/*0*/ x: jet.Int): jet.Tuple0
+internal final fun </*0*/ T1 : jet.Any?, /*1*/ T : Foo>foo(/*0*/ x: jet.Long): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt127.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt127.txt
new file mode 100644
index 0000000000000..52f7e7f8b5d33
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt127.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+}
+internal final fun jet.Any.equals(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun jet.Any?.equals1(/*0*/ other: jet.Any?): jet.Boolean
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt128.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt128.txt
new file mode 100644
index 0000000000000..35ffbe62f0f23
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt128.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun div(/*0*/ c: jet.String = ?, /*1*/ f: jet.Function0<jet.Tuple0>): jet.Tuple0
+internal final fun f(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt1489_1728.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt1489_1728.txt
new file mode 100644
index 0000000000000..ee4feff2a8e1e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt1489_1728.txt
@@ -0,0 +1,21 @@
+namespace <root>
+
+// <namespace name="kt606_dependents">
+namespace kt606_dependents
+
+internal abstract trait kt606_dependents.AutoCloseable : jet.Any {
+ internal abstract fun close(): jet.Tuple0
+}
+internal final class kt606_dependents.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt606_dependents.C
+ internal final fun bar(): jet.Tuple0
+ internal final class kt606_dependents.C.Resource : kt606_dependents.AutoCloseable {
+ public final /*constructor*/ fun <init>(): kt606_dependents.C.Resource
+ internal open override /*1*/ fun close(): jet.Tuple0
+ }
+ internal final fun </*0*/ X : kt606_dependents.AutoCloseable>foo(/*0*/ x: X, /*1*/ body: jet.Function1<X, jet.Tuple0>): jet.Tuple0
+ internal final fun p(): kt606_dependents.C.Resource?
+}
+internal final val jet.Int.ext: jet.Function0<jet.Int>
+internal final val x: jet.Int
+// </namespace name="kt606_dependents">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt1550.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt1550.txt
new file mode 100644
index 0000000000000..5ed3f291218f7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt1550.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="foo">
+namespace foo
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="foo">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt1647.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt1647.txt
new file mode 100644
index 0000000000000..f1b4f3a8b7cb2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt1647.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal open class Abs : jet.Any {
+ public final /*constructor*/ fun <init>(): Abs
+}
+internal final class Bar : Abs {
+ public final /*constructor*/ fun <init>(): Bar
+}
+internal final fun </*0*/ F : Abs>patternMatchingAndGenerics(/*0*/ arg: F): jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt1736.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt1736.txt
new file mode 100644
index 0000000000000..a986a0328df57
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt1736.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt1736">
+namespace kt1736
+
+internal final val Obj: kt1736.Obj
+internal final val x: jet.Tuple0
+// </namespace name="kt1736">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt174.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt174.txt
new file mode 100644
index 0000000000000..047a3793ab71c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt174.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal abstract trait Tree : jet.Any {
+}
+internal final fun jet.Any?.TreeValue(): Tree
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt201.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt201.txt
new file mode 100644
index 0000000000000..282c60847816d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt201.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun foo(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any>T?.npe(): T
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt235.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt235.txt
new file mode 100644
index 0000000000000..3e1f8c1ff935f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt235.txt
@@ -0,0 +1,21 @@
+namespace <root>
+
+// <namespace name="kt235">
+namespace kt235
+
+internal final class kt235.MyArray : jet.Any {
+ public final /*constructor*/ fun <init>(): kt235.MyArray
+ internal final fun get(/*0*/ i: jet.Int): jet.Int
+ internal final fun set(/*0*/ i: jet.Int, /*1*/ value: jet.Int): jet.Int
+}
+internal final class kt235.MyArray1 : jet.Any {
+ public final /*constructor*/ fun <init>(): kt235.MyArray1
+ internal final fun get(/*0*/ i: jet.Int): jet.Int
+ internal final fun set(/*0*/ i: jet.Int, /*1*/ value: jet.Int): jet.Tuple0
+}
+internal final class kt235.MyNumber : jet.Any {
+ public final /*constructor*/ fun <init>(): kt235.MyNumber
+ internal final fun inc(): kt235.MyNumber
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="kt235">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt2376.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt2376.txt
new file mode 100644
index 0000000000000..d1101ee41311c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt2376.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+public open class Test : java.lang.Object {
+ public final /*constructor*/ fun <init>(): Test
+ package open fun number(/*0*/ n: jet.Number?): jet.Tuple0
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt251.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt251.txt
new file mode 100644
index 0000000000000..d508ebfcc28cf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt251.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final var a: jet.Any
+ internal final val b: jet.Int
+ internal final val c: jet.Int
+ internal final val d: jet.Int
+ internal final val e: jet.Int
+ internal final var x: jet.Int
+ internal final val y: jet.Int
+ internal final val z: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt258.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt258.txt
new file mode 100644
index 0000000000000..d8b05485691e2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt258.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ K : jet.Any?, /*1*/ V : jet.Any?>java.util.Map<K, V>.set(/*0*/ key: K, /*1*/ value: V): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt26.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt26.txt
new file mode 100644
index 0000000000000..8cc56101dc614
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt26.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="html">
+namespace html
+
+internal abstract class html.Factory</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): html.Factory<T>
+ internal final fun create(): T?
+}
+// </namespace name="html">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt282.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt282.txt
new file mode 100644
index 0000000000000..b4cf816c53369
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt282.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class Set : jet.Any {
+ public final /*constructor*/ fun <init>(): Set
+ internal final fun contains(/*0*/ x: jet.Int): jet.Boolean
+}
+internal final fun jet.Int?.contains(/*0*/ x: jet.Int): jet.Boolean
+internal final fun f(): jet.Tuple0
+internal final fun Set?.plus(/*0*/ x: jet.Int): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt287.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt287.txt
new file mode 100644
index 0000000000000..977f81dc7c0ea
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt287.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final val attributes: java.util.Map<jet.String, jet.String>
+internal final fun attributes(): java.util.Map<jet.String, jet.String>
+internal final fun foo(/*0*/ m: java.util.Map<jet.String, jet.String>): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt302.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt302.txt
new file mode 100644
index 0000000000000..9ccb8bbc7b3b0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt302.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="kt302">
+namespace kt302
+
+internal abstract trait kt302.A : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+internal abstract trait kt302.B : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+internal final class kt302.C : kt302.A, kt302.B {
+ public final /*constructor*/ fun <init>(): kt302.C
+ internal open override /*2*/ fun foo(): jet.Tuple0
+}
+// </namespace name="kt302">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt306.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt306.txt
new file mode 100644
index 0000000000000..1b83462abec04
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt306.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal final class Barr : jet.Any {
+ public final /*constructor*/ fun <init>(): Barr
+ internal final fun bar(): jet.Tuple0
+}
+internal final class Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): Foo
+ internal final fun bar(): jet.Tuple0
+}
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt307.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt307.txt
new file mode 100644
index 0000000000000..9f982e8ca5677
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt307.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal open class AL : jet.Any {
+ public final /*constructor*/ fun <init>(): AL
+ internal final fun get(/*0*/ i: jet.Int): jet.Any?
+}
+internal abstract trait ALE</*0*/ T : jet.Any?> : AL {
+ internal final override /*1*/ fun get(/*0*/ i: jet.Int): jet.Any?
+ internal open fun getOrNull(/*0*/ index: jet.Int, /*1*/ value: T): T
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt312.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt312.txt
new file mode 100644
index 0000000000000..c41c0e08376dc
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt312.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final val args: jet.Array<jet.String>
+internal final val name: jet.String
+internal final val name1: jet.String?
+internal final fun </*0*/ T : jet.Any?>jet.Array<out T>.safeGet(/*0*/ index: jet.Int): T?
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt313.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt313.txt
new file mode 100644
index 0000000000000..72bc183d98c02
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt313.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>jet.Iterable<T>.join(/*0*/ separator: jet.String?): jet.String
+internal final fun </*0*/ T : jet.Any>T?.npe(): T
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt316.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt316.txt
new file mode 100644
index 0000000000000..a72a4477360ec
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt316.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class A : B {
+ public final /*constructor*/ fun <init>(): A
+ internal open override /*1*/ fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+}
+internal abstract trait B : jet.Any {
+ internal open fun bar(): jet.Tuple0
+ internal open fun foo(): jet.Tuple0
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt328.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt328.txt
new file mode 100644
index 0000000000000..67e35484a7cd5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt328.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final val x: jet.Function0<[ERROR : <return type>]>
+}
+internal final val x: jet.Function0<[ERROR : <return type>]>
+internal final val z: [ERROR : Type for z]
+internal final fun bar1(): jet.Function0<[ERROR : <return type>]>
+internal final fun bar2(): jet.Function0<jet.Tuple0>
+internal final fun bar3(): jet.Tuple0
+internal final fun block(/*0*/ f: jet.Function0<jet.Tuple0>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt335.336.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt335.336.txt
new file mode 100644
index 0000000000000..da8169f6c277f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt335.336.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>java.util.List<T>.plus(/*0*/ other: java.util.List<T>): java.util.List<T>
+internal final fun </*0*/ T : java.lang.Comparable<T>>java.util.List<T>.sort(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt337.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt337.txt
new file mode 100644
index 0000000000000..955e222056bb8
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt337.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final fun foo(): jet.Tuple0
+}
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt352.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt352.txt
new file mode 100644
index 0000000000000..1597cca18151e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt352.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="kt352">
+namespace kt352
+
+internal final class kt352.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt352.A
+ internal final val f: jet.Function1<jet.Any, jet.Tuple0>
+}
+internal final val f: jet.Function1<jet.Any, jet.Tuple0>
+internal final val g: jet.Function0<jet.Tuple0>
+internal final val h: jet.Function0<jet.Tuple0>
+internal final val testIt: jet.Function1<jet.Any, jet.Tuple0>
+internal final fun doSmth(): jet.Int
+internal final fun doSmth(/*0*/ a: jet.String): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt352">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt353.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt353.txt
new file mode 100644
index 0000000000000..a6b746fac2e83
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt353.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal abstract trait A : jet.Any {
+ internal abstract fun </*0*/ T : jet.Any?>gen(): T
+}
+internal final fun foo(/*0*/ a: A): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt385.109.441.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt385.109.441.txt
new file mode 100644
index 0000000000000..2cbf0ee5a0fa1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt385.109.441.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+internal final fun box(): jet.String
+internal final fun </*0*/ T : jet.Any?>jet.Iterable<T>.foreach(/*0*/ operation: jet.Function1<T, jet.Tuple0>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>jet.Iterable<T>.foreach(/*0*/ operation: jet.Function2<jet.Int, T, jet.Tuple0>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>jet.Iterator<T>.foreach(/*0*/ operation: jet.Function1<T, jet.Tuple0>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>jet.Iterator<T>.foreach(/*0*/ operation: jet.Function2<jet.Int, T, jet.Tuple0>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>generic_invoker(/*0*/ gen: jet.Function0<T>): T
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun println(/*0*/ message: jet.Int): jet.Tuple0
+internal final fun println(/*0*/ message: jet.Long): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>run(/*0*/ body: jet.Function0<T>): T
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt398.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt398.txt
new file mode 100644
index 0000000000000..dbe7a9bc4f8d1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt398.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class X</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): X<T>
+ internal final val check: jet.Function1<jet.Any, jet.Boolean>
+}
+internal final fun box(): jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt399.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt399.txt
new file mode 100644
index 0000000000000..087509a18834e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt399.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun box(): jet.String
+internal final fun </*0*/ T : jet.Any?>getSameTypeChecker(/*0*/ obj: T): jet.Function1<jet.Any, jet.Boolean>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt402.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt402.txt
new file mode 100644
index 0000000000000..bef4752805fa7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt402.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt402">
+namespace kt402
+
+internal final fun f(): jet.Function1<jet.Any, jet.Boolean>
+internal final fun getTypeChecker(): jet.Function1<jet.Any, jet.Boolean>
+// </namespace name="kt402">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt41.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt41.txt
new file mode 100644
index 0000000000000..0fb842f2c66bf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt41.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt41">
+namespace kt41
+
+internal final fun aaa(): [ERROR : Error function type]
+internal final fun bbb(): jet.Tuple0
+// </namespace name="kt41">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt411.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt411.txt
new file mode 100644
index 0000000000000..ea60c1f0cd370
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt411.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt411">
+namespace kt411
+
+internal final fun f(): jet.Tuple0
+internal final fun invoker(/*0*/ gen: jet.Function0<jet.Int>): jet.Int
+internal final fun t1(): jet.Tuple0
+internal final fun t2(): jet.String
+internal final fun t3(): jet.String
+internal final fun t4(): jet.Int
+// </namespace name="kt411">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt439.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt439.txt
new file mode 100644
index 0000000000000..c35601905d8fd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt439.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun main1(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>run1(/*0*/ body: jet.Function0<T>): T
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt442.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt442.txt
new file mode 100644
index 0000000000000..ec55b504b9891
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt442.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+internal final fun box(): jet.String
+internal final fun </*0*/ T : jet.Any?>funny(/*0*/ f: jet.Function0<T>): T
+internal final fun </*0*/ T : jet.Any?>funny2(/*0*/ f: jet.Function1<T, T>): T
+internal final fun </*0*/ T : jet.Any?>generic_invoker(/*0*/ gen: jet.Function1<jet.String, T>): T
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun testFunny(): jet.Tuple0
+internal final fun testFunny2(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>T.with(/*0*/ f: jet.ExtensionFunction0<T, jet.Tuple0>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt443.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt443.txt
new file mode 100644
index 0000000000000..1d3ff8dddb04e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt443.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+internal open class M : jet.Any {
+ public final /*constructor*/ fun <init>(): M
+ internal open val b: jet.Int
+}
+internal final class N : M {
+ public final /*constructor*/ fun <init>(): N
+ internal final val a: jet.Int
+ internal open override /*1*/ val b: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt455.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt455.txt
new file mode 100644
index 0000000000000..decaf84711991
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt455.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt455">
+namespace kt455
+
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+// </namespace name="kt455">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt456.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt456.txt
new file mode 100644
index 0000000000000..5e1da2e3112fb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt456.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="kt456">
+namespace kt456
+
+internal final class kt456.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt456.A
+ internal final val i: jet.Int
+}
+internal final class kt456.B : jet.Any {
+ public final /*constructor*/ fun <init>(): kt456.B
+ internal final val i: jet.Int
+}
+internal final class kt456.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt456.C
+ internal final val i: jet.Int
+}
+internal final fun doSmth(): jet.Tuple0
+// </namespace name="kt456">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt459.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt459.txt
new file mode 100644
index 0000000000000..d8b05485691e2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt459.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ K : jet.Any?, /*1*/ V : jet.Any?>java.util.Map<K, V>.set(/*0*/ key: K, /*1*/ value: V): jet.Tuple0
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt469.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt469.txt
new file mode 100644
index 0000000000000..4ca0d641485a6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt469.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+// <namespace name="kt469">
+namespace kt469
+
+internal final class kt469.MyNumber : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ i: jet.Int): kt469.MyNumber
+ internal final var i: jet.Int
+ internal final fun minusAssign(/*0*/ m: kt469.MyNumber): jet.Tuple0
+}
+internal final fun bar(/*0*/ list: java.util.List<jet.Int>): jet.Tuple0
+internal final fun foo(): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>java.util.List<T>.plusAssign(/*0*/ t: T): jet.Tuple0
+// </namespace name="kt469">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt498.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt498.txt
new file mode 100644
index 0000000000000..e17c5a9b5694d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt498.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class IdUnavailableException : java.lang.Exception {
+ public final /*constructor*/ fun <init>(): IdUnavailableException
+ public final override /*1*/ fun getCause(): jet.Throwable?
+ public final override /*1*/ fun getMessage(): jet.String?
+ public final override /*1*/ fun printStackTrace(): jet.Tuple0
+}
+internal final fun </*0*/ T : jet.Any>T.getJavaClass(): java.lang.Class<T>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt524.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt524.txt
new file mode 100644
index 0000000000000..5d8c9ce2cea2c
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt524.txt
@@ -0,0 +1,10 @@
+namespace <root>
+
+// <namespace name="StringBuilder">
+namespace StringBuilder
+
+internal final val jet.Int.bd: java.lang.StringBuilder
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun java.lang.StringBuilder.plus(/*0*/ other: java.lang.StringBuilder): java.lang.StringBuilder
+internal final fun </*0*/ T : jet.Any>T?.sure1(): T
+// </namespace name="StringBuilder">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt526UnresolvedReferenceInnerStatic.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt526UnresolvedReferenceInnerStatic.txt
new file mode 100644
index 0000000000000..219081851dfea
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt526UnresolvedReferenceInnerStatic.txt
@@ -0,0 +1,19 @@
+namespace <root>
+
+// <namespace name="demo">
+namespace demo
+
+internal final class demo.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): demo.Foo
+ internal final object demo.Foo.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): demo.Foo.<no name provided>
+ internal final class demo.Foo.<no name provided>.Bar : jet.Any {
+ public final /*constructor*/ fun <init>(): demo.Foo.<no name provided>.Bar
+ }
+ }
+}
+internal final class demo.User : jet.Any {
+ public final /*constructor*/ fun <init>(): demo.User
+ internal final fun main(): jet.Tuple0
+}
+// </namespace name="demo">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt549.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt549.txt
new file mode 100644
index 0000000000000..f125786e17e11
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt549.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="demo">
+namespace demo
+
+internal final fun </*0*/ T : jet.Any?>filter(/*0*/ list: jet.Array<T>, /*1*/ filter: jet.Function1<T, jet.Boolean>): java.util.List<T>
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="demo">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt557.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt557.txt
new file mode 100644
index 0000000000000..a26707c1a3c40
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt557.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun jet.Array<jet.String>.length(): jet.Int
+internal final fun test(/*0*/ array: jet.Array<jet.String?>?): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt571.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt571.txt
new file mode 100644
index 0000000000000..86a4a28757dd5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt571.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+private final fun double(/*0*/ d: jet.Int): jet.Int
+internal final fun </*0*/ T : jet.Any?, /*1*/ R : jet.Any?>let(/*0*/ t: T, /*1*/ body: jet.Function1<T, R>): R
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt58.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt58.txt
new file mode 100644
index 0000000000000..f09add8b664f6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt58.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="kt58">
+namespace kt58
+
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>lock(/*0*/ lock: java.util.concurrent.locks.Lock, /*1*/ body: jet.Function0<T>): T
+internal final fun t1(): jet.Int
+internal final fun t2(): jet.Int
+internal final fun t3(): jet.Int
+internal final fun t4(): jet.Int
+internal final fun t5(): jet.Int
+internal final fun t6(): jet.Int
+internal final fun t7(): jet.Int
+// </namespace name="kt58">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt580.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt580.txt
new file mode 100644
index 0000000000000..131cc4f4c7016
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt580.txt
@@ -0,0 +1,18 @@
+namespace <root>
+
+// <namespace name="whats">
+namespace whats
+
+// <namespace name="the">
+namespace the
+
+// <namespace name="difference">
+namespace difference
+
+internal final val </*0*/ T : jet.Any?> jet.Array<T>.lastIndex: jet.Int
+internal final fun iarray(/*0*/ vararg a: jet.String /*jet.Array<jet.String>*/): jet.Array<jet.String>
+internal final fun </*0*/ T : jet.Any?>jet.Array<T>.lastIndex(): jet.Int
+internal final fun main(): jet.Tuple0
+// </namespace name="difference">
+// </namespace name="the">
+// </namespace name="whats">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt588.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt588.txt
new file mode 100644
index 0000000000000..9824d5fcee301
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt588.txt
@@ -0,0 +1,37 @@
+namespace <root>
+
+internal final class Test : java.lang.Thread {
+ public final /*constructor*/ fun <init>(): Test
+ public final override /*1*/ fun checkAccess(): jet.Tuple0
+ public open override /*1*/ fun countStackFrames(): jet.Int
+ public open override /*1*/ fun destroy(): jet.Tuple0
+ public open override /*1*/ fun getContextClassLoader(): java.lang.ClassLoader?
+ public open override /*1*/ fun getId(): jet.Long
+ public final override /*1*/ fun getName(): jet.String?
+ public final override /*1*/ fun getPriority(): jet.Int
+ public open override /*1*/ fun getStackTrace(): jet.Array<[ERROR : Unresolved java class: StackTraceElement]>?
+ public final override /*1*/ fun getThreadGroup(): [ERROR : Unresolved java class: ThreadGroup]
+ public open override /*1*/ fun interrupt(): jet.Tuple0
+ invisible_fake final override /*1*/ var inheritableThreadLocals: java.lang.ThreadLocal.ThreadLocalMap?
+ invisible_fake final override /*1*/ var threadLocals: java.lang.ThreadLocal.ThreadLocalMap?
+ public final override /*1*/ fun isAlive(): jet.Boolean
+ public final override /*1*/ fun isDaemon(): jet.Boolean
+ public open override /*1*/ fun isInterrupted(): jet.Boolean
+ public final override /*1*/ fun join(): jet.Tuple0
+ public final override /*1*/ fun join(/*0*/ p0: jet.Long): jet.Tuple0
+ public final override /*1*/ fun join(/*0*/ p0: jet.Long, /*1*/ p1: jet.Int): jet.Tuple0
+ public final override /*1*/ fun resume(): jet.Tuple0
+ public open override /*1*/ fun run(): jet.Tuple0
+ public open override /*1*/ fun setContextClassLoader(/*0*/ p0: java.lang.ClassLoader?): jet.Tuple0
+ public final override /*1*/ fun setDaemon(/*0*/ p0: jet.Boolean): jet.Tuple0
+ public final override /*1*/ fun setName(/*0*/ p0: jet.String?): jet.Tuple0
+ public final override /*1*/ fun setPriority(/*0*/ p0: jet.Int): jet.Tuple0
+ public open override /*1*/ fun start(): jet.Tuple0
+ public final override /*1*/ fun stop(): jet.Tuple0
+ public final override /*1*/ fun stop(/*0*/ p0: jet.Throwable?): jet.Tuple0
+ public final override /*1*/ fun suspend(): jet.Tuple0
+ internal final object Test.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Test.<no name provided>
+ internal final fun init2(): jet.Tuple0
+ }
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt597.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt597.txt
new file mode 100644
index 0000000000000..e944d823e3b54
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt597.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>jet.Array<T>?.get(/*0*/ i: jet.Int): T
+internal final fun jet.Int?.inc(): jet.Int
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt600.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt600.txt
new file mode 100644
index 0000000000000..dd05b09a9faf6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt600.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any>T?._sure(): T
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt604.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt604.txt
new file mode 100644
index 0000000000000..f0952c956b356
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt604.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+internal abstract trait ChannelPipeline : jet.Any {
+}
+internal abstract trait ChannelPipelineFactory : jet.Any {
+ internal abstract fun getPipeline(): ChannelPipeline
+}
+internal final class DefaultChannelPipeline : ChannelPipeline {
+ public final /*constructor*/ fun <init>(): DefaultChannelPipeline
+}
+internal final class StandardPipelineFactory : ChannelPipelineFactory {
+ public final /*constructor*/ fun <init>(/*0*/ config: jet.ExtensionFunction0<ChannelPipeline, jet.Tuple0>): StandardPipelineFactory
+ internal final val config: jet.ExtensionFunction0<ChannelPipeline, jet.Tuple0>
+ internal open override /*1*/ fun getPipeline(): ChannelPipeline
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt618.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt618.txt
new file mode 100644
index 0000000000000..3ff11450de4ae
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt618.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="lol">
+namespace lol
+
+internal final class lol.B : jet.Any {
+ public final /*constructor*/ fun <init>(): lol.B
+ internal final fun divAssign(/*0*/ other: lol.B): jet.String
+ internal final fun minusAssign(/*0*/ other: lol.B): jet.String
+ internal final fun modAssign(/*0*/ other: lol.B): jet.String
+ internal final fun plusAssign(/*0*/ other: lol.B): jet.String
+ internal final fun timesAssign(/*0*/ other: lol.B): jet.String
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+// </namespace name="lol">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt629.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt629.txt
new file mode 100644
index 0000000000000..c4af41b826e72
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt629.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt629">
+namespace kt629
+
+internal final class kt629.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt629.A
+ internal final fun mod(/*0*/ other: kt629.A): kt629.A
+ internal final var p: jet.String
+}
+internal final fun box(): jet.Boolean
+internal final fun box2(): jet.Boolean
+// </namespace name="kt629">
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt630.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt630.txt
new file mode 100644
index 0000000000000..6bc93b1f2744b
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt630.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final val s: jet.String
+internal final val x: jet.String
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt688.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt688.txt
new file mode 100644
index 0000000000000..0597951b0d403
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt688.txt
@@ -0,0 +1,14 @@
+namespace <root>
+
+internal open class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+}
+internal open class B : A {
+ public final /*constructor*/ fun <init>(): B
+ internal final fun b(): B
+}
+internal final class C : jet.Any {
+ public final /*constructor*/ fun <init>(): C
+ internal final fun </*0*/ T : jet.Any?>a(/*0*/ x: jet.Function1<T, T>, /*1*/ y: T): T
+ internal final val x: B
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt701.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt701.txt
new file mode 100644
index 0000000000000..b4847e1c74a59
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt701.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+public final class Throwables : jet.Any {
+ public final /*constructor*/ fun <init>(): Throwables
+ internal final object Throwables.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Throwables.<no name provided>
+ public final fun </*0*/ X : jet.Throwable?>propagateIfInstanceOf(/*0*/ throwable: jet.Throwable?, /*1*/ declaredType: java.lang.Class<X?>?): jet.Tuple0
+ public final fun propagateIfPossible(/*0*/ throwable: jet.Throwable?): jet.Tuple0
+ }
+}
+internal final fun </*0*/ T : jet.Any?>getJavaClass(): java.lang.Class<T>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt716.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt716.txt
new file mode 100644
index 0000000000000..bd191ad0fc62d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt716.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class TypeInfo</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): TypeInfo<T>
+}
+internal final fun </*0*/ T : jet.Any?>TypeInfo<T>.getJavaClass(): java.lang.Class<T>
+internal final fun </*0*/ T : jet.Any?>getJavaClass(): java.lang.Class<T>
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
+internal final fun </*0*/ T : jet.Any?>typeinfo(): TypeInfo<T>
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt743.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt743.txt
new file mode 100644
index 0000000000000..bf9c380a76d04
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt743.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+internal final class List</*0*/ T : jet.Any?> : jet.Any {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ head: T, /*1*/ tail: List<T>? = ?): List<T>
+ internal final val head: T
+ internal final val tail: List<T>?
+}
+internal final fun </*0*/ T : jet.Any?>foo(/*0*/ t: T): T
+internal final fun </*0*/ T : jet.Any?, /*1*/ Q : jet.Any?>List<T>.map(/*0*/ f: jet.Function1<T, Q>): List<T>?
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt750.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt750.txt
new file mode 100644
index 0000000000000..dc622bf14c5ed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt750.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt762.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt762.txt
new file mode 100644
index 0000000000000..dc622bf14c5ed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt762.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt847.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt847.txt
new file mode 100644
index 0000000000000..70b47b23e1705
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt847.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun </*0*/ T : jet.Any?>T.mustBe(/*0*/ t: T): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/regressions/kt860.txt b/compiler/testData/lazyResolve/diagnostics/regressions/kt860.txt
new file mode 100644
index 0000000000000..7d99e93722a59
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/regressions/kt860.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kotlin">
+namespace kotlin
+
+// <namespace name="util">
+namespace util
+
+internal final fun </*0*/ T : jet.Any?, /*1*/ U : java.util.Collection<in T>>jet.Iterator<T>.to(/*0*/ container: U): U
+internal final fun </*0*/ T : jet.Any?>jet.Iterator<T>.toArrayList(): java.util.ArrayList<T>
+// </namespace name="util">
+// </namespace name="kotlin">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/ImportFromCurrentWithDifferentName.txt b/compiler/testData/lazyResolve/diagnostics/scopes/ImportFromCurrentWithDifferentName.txt
new file mode 100644
index 0000000000000..4ea07c437bbc0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/ImportFromCurrentWithDifferentName.txt
@@ -0,0 +1,9 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final class a.A : jet.Any {
+ public final /*constructor*/ fun <init>(): a.A
+}
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimes.txt b/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimes.txt
new file mode 100644
index 0000000000000..b024e5ffd0869
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimes.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="weatherForecast">
+namespace weatherForecast
+
+internal final fun weatherToday(): jet.String
+// </namespace name="weatherForecast">
+// <namespace name="myApp">
+namespace myApp
+
+internal final fun needUmbrella(): jet.Boolean
+// </namespace name="myApp">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimesStar.txt b/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimesStar.txt
new file mode 100644
index 0000000000000..b024e5ffd0869
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/ImportTwoTimesStar.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="weatherForecast">
+namespace weatherForecast
+
+internal final fun weatherToday(): jet.String
+// </namespace name="weatherForecast">
+// <namespace name="myApp">
+namespace myApp
+
+internal final fun needUmbrella(): jet.Boolean
+// </namespace name="myApp">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/ImportsUselessSimpleImport.txt b/compiler/testData/lazyResolve/diagnostics/scopes/ImportsUselessSimpleImport.txt
new file mode 100644
index 0000000000000..ec5450c3f40c2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/ImportsUselessSimpleImport.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final val B: a.B
+// </namespace name="a">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/initializerScopeOfExtensionProperty.txt b/compiler/testData/lazyResolve/diagnostics/scopes/initializerScopeOfExtensionProperty.txt
new file mode 100644
index 0000000000000..87773d626bbdf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/initializerScopeOfExtensionProperty.txt
@@ -0,0 +1,25 @@
+namespace <root>
+
+// <namespace name="i">
+namespace i
+
+internal final class i.A : jet.Any {
+ public final /*constructor*/ fun <init>(): i.A
+ internal final val ii: jet.Int
+}
+internal final class i.C : jet.Any {
+ public final /*constructor*/ fun <init>(): i.C
+ internal final class i.C.D : jet.Any {
+ public final /*constructor*/ fun <init>(): i.C.D
+ }
+}
+internal final val i.C.bar: i.C.D
+internal final val jet.String.bd: [ERROR : <ERROR FUNCTION RETURN TYPE>]
+internal final val jet.String.bd1: jet.String
+internal final val i.A.foo: [ERROR : Type for ii]
+internal final val i.C.foo: i.C.D
+internal final val i.A.foo1: jet.Int
+internal final val i.C.foo1: i.C.D
+internal final val </*0*/ T : jet.Any?> java.util.List<T>.length: [ERROR : Type for size()]
+internal final val </*0*/ T : jet.Any?> java.util.List<T>.length1: jet.Int
+// </namespace name="i">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1078.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1078.txt
new file mode 100644
index 0000000000000..1b65f105bc8eb
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1078.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt1078">
+namespace kt1078
+
+internal final class kt1078.B : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1078.B
+ internal final fun bar(): jet.Boolean
+}
+internal final fun foo(): kt1078.B
+internal final fun test(): kt1078.B
+// </namespace name="kt1078">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1244.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1244.txt
new file mode 100644
index 0000000000000..49560a42e0cff
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1244.txt
@@ -0,0 +1,13 @@
+namespace <root>
+
+// <namespace name="kt1244">
+namespace kt1244
+
+internal final class kt1244.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1244.A
+ private final var a: jet.String
+}
+internal final class kt1244.B : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1244.B
+}
+// </namespace name="kt1244">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1248.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1248.txt
new file mode 100644
index 0000000000000..4054dfc25e0bd
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1248.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="kt1248">
+namespace kt1248
+
+internal abstract trait kt1248.ParseResult</*0*/ out T : jet.Any?> : jet.Any {
+ public abstract val success: jet.Boolean
+ public abstract val value: T
+}
+internal final class kt1248.Success</*0*/ T : jet.Any?> : kt1248.ParseResult<T> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(/*0*/ value: T): kt1248.Success<T>
+ internal open override /*1*/ val success: jet.Boolean
+ internal open override /*1*/ val value: T
+}
+// </namespace name="kt1248">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt151.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt151.txt
new file mode 100644
index 0000000000000..6b5055cfa2767
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt151.txt
@@ -0,0 +1,38 @@
+namespace <root>
+
+// <namespace name="kt151">
+namespace kt151
+
+internal open class kt151.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt151.A
+ protected open fun x(): jet.Tuple0
+}
+internal final class kt151.B : kt151.A {
+ public final /*constructor*/ fun <init>(): kt151.B
+ protected open override /*1*/ fun x(): jet.Tuple0
+}
+internal open class kt151.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt151.C
+ internal open fun foo(): jet.Tuple0
+}
+internal final class kt151.D : kt151.C, kt151.T {
+ public final /*constructor*/ fun <init>(): kt151.D
+ protected open override /*2*/ fun foo(): jet.Tuple0
+}
+internal final class kt151.E : kt151.C, kt151.T {
+ public final /*constructor*/ fun <init>(): kt151.E
+ internal open override /*2*/ fun foo(): jet.Tuple0
+}
+internal final class kt151.F : kt151.C, kt151.T {
+ public final /*constructor*/ fun <init>(): kt151.F
+ private open override /*2*/ fun foo(): jet.Tuple0
+}
+internal final class kt151.G : kt151.C, kt151.T {
+ public final /*constructor*/ fun <init>(): kt151.G
+ public open override /*2*/ fun foo(): jet.Tuple0
+}
+internal abstract trait kt151.T : jet.Any {
+ protected open fun foo(): jet.Tuple0
+}
+internal final fun test(/*0*/ b: kt151.B): jet.Tuple0
+// </namespace name="kt151">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1579_map_entry.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1579_map_entry.txt
new file mode 100644
index 0000000000000..cc98a11c4fbaf
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1579_map_entry.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+internal final fun foo(/*0*/ b: java.util.Map.Entry<jet.String, jet.String>): java.util.Map.Entry<jet.String, jet.String>
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final fun bar(/*0*/ b: java.util.Map.Entry<jet.String, jet.String>): java.util.Map.Entry<jet.String, jet.String>
+// </namespace name="b">
+// <namespace name="c">
+namespace c
+
+internal final fun fff(/*0*/ b: java.util.Map.Entry<jet.String, jet.String>): java.util.Map.Entry<jet.String, jet.String>
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1580.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1580.txt
new file mode 100644
index 0000000000000..67c598ce182ca
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1580.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="lib">
+namespace lib
+
+internal abstract trait lib.WithInner : jet.Any {
+ internal abstract trait lib.WithInner.Inner : jet.Any {
+ }
+}
+// </namespace name="lib">
+// <namespace name="user">
+namespace user
+
+internal final fun main(/*0*/ a: lib.WithInner, /*1*/ b: lib.WithInner.Inner): jet.Tuple0
+// </namespace name="user">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1738.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1738.txt
new file mode 100644
index 0000000000000..809fc1501c569
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1738.txt
@@ -0,0 +1,12 @@
+namespace <root>
+
+// <namespace name="kt1738">
+namespace kt1738
+
+internal final class kt1738.A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ i: jet.Int, /*1*/ j: jet.Int): kt1738.A
+ private final var i: jet.Int
+ internal final var j: jet.Int
+}
+internal final fun test(/*0*/ a: kt1738.A): jet.Tuple0
+// </namespace name="kt1738">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1805.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1805.txt
new file mode 100644
index 0000000000000..1d2552ad448e7
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1805.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="kt1805">
+namespace kt1805
+
+internal open class kt1805.Some : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1805.Some
+ private final val privateField: jet.Int
+}
+internal final class kt1805.SomeSubclass : kt1805.Some {
+ public final /*constructor*/ fun <init>(): kt1805.SomeSubclass
+ invisible_fake final override /*1*/ val privateField: jet.Int private get
+ internal final fun test(): jet.Tuple0
+}
+internal final fun test(): jet.Tuple0
+// </namespace name="kt1805">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1806.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1806.txt
new file mode 100644
index 0000000000000..6b3e7850ff04f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1806.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt1806">
+namespace kt1806
+
+internal final val MyObject: kt1806.MyObject
+internal final val MyObject1: kt1806.<no name provided>
+internal final fun doSmth(/*0*/ s: jet.String): jet.String
+internal final fun test1(): jet.Tuple0
+internal final fun test2(): jet.Tuple0
+// </namespace name="kt1806">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt1822.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt1822.txt
new file mode 100644
index 0000000000000..42a10a651edb5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt1822.txt
@@ -0,0 +1,31 @@
+namespace <root>
+
+// <namespace name="kt1822">
+namespace kt1822
+
+internal open class kt1822.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1822.A
+ internal open fun foo(): jet.Tuple0
+}
+internal abstract trait kt1822.B : jet.Any {
+ protected open fun foo(): jet.Tuple0
+}
+internal open class kt1822.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt1822.C
+ internal open fun foo(): jet.Tuple0
+}
+internal abstract trait kt1822.D : jet.Any {
+ public open fun foo(): jet.Tuple0
+}
+internal final class kt1822.E : kt1822.A, kt1822.B, kt1822.D {
+ public final /*constructor*/ fun <init>(): kt1822.E
+ public open override /*3*/ fun foo(): jet.Tuple0
+}
+internal final class kt1822.G : kt1822.C, kt1822.T {
+ public final /*constructor*/ fun <init>(): kt1822.G
+ public open override /*2*/ fun foo(): jet.Tuple0
+}
+internal abstract trait kt1822.T : jet.Any {
+ protected open fun foo(): jet.Tuple0
+}
+// </namespace name="kt1822">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt2262.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt2262.txt
new file mode 100644
index 0000000000000..4a824be7d0468
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt2262.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+// <namespace name="kt2262">
+namespace kt2262
+
+internal final class kt2262.Bar : kt2262.Foo {
+ public final /*constructor*/ fun <init>(): kt2262.Bar
+ internal final class kt2262.Bar.Baz : jet.Any {
+ public final /*constructor*/ fun <init>(): kt2262.Bar.Baz
+ internal final val copy: jet.String
+ internal final val j: jet.Int
+ }
+ protected final override /*1*/ val color: jet.String
+ protected final val i: jet.Int
+}
+internal abstract class kt2262.Foo : jet.Any {
+ public final /*constructor*/ fun <init>(): kt2262.Foo
+ protected final val color: jet.String
+}
+// </namespace name="kt2262">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt323.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt323.txt
new file mode 100644
index 0000000000000..654e871d558c4
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt323.txt
@@ -0,0 +1,16 @@
+namespace <root>
+
+// <namespace name="kt323">
+namespace kt323
+
+internal open class kt323.A : jet.Any {
+ public final /*constructor*/ fun <init>(): kt323.A
+ internal open var a: jet.Int
+}
+internal final class kt323.B : kt323.A {
+ public final /*constructor*/ fun <init>(): kt323.B
+ internal open override /*1*/ val a: jet.Int
+ internal final var b: jet.Int public get
+ protected final var c: jet.Int private set
+}
+// </namespace name="kt323">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt37.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt37.txt
new file mode 100644
index 0000000000000..71ec1ae45c0a0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt37.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="kt37">
+namespace kt37
+
+internal final class kt37.C : jet.Any {
+ public final /*constructor*/ fun <init>(): kt37.C
+ private final var f: jet.Int
+}
+internal final fun box(): jet.String
+// </namespace name="kt37">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt421Scopes.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt421Scopes.txt
new file mode 100644
index 0000000000000..625a507c5a387
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt421Scopes.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(): A
+ internal final val a: jet.Int
+ internal final val b: jet.Int
+ internal final val c: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt587.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt587.txt
new file mode 100644
index 0000000000000..9cd8a83d3ab11
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt587.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+internal final class Main : jet.Any {
+ public final /*constructor*/ fun <init>(): Main
+ internal final object Main.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Main.<no name provided>
+ internal final class Main.<no name provided>.States : jet.Any {
+ public final /*constructor*/ fun <init>(): Main.<no name provided>.States
+ internal final object Main.<no name provided>.States.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): Main.<no name provided>.States.<no name provided>
+ public final val N: Main.<no name provided>.States
+ }
+ }
+ }
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt900-1.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt900-1.txt
new file mode 100644
index 0000000000000..a2782c768468d
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt900-1.txt
@@ -0,0 +1,20 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal final class c.A : jet.Any {
+ public final /*constructor*/ fun <init>(): c.A
+ internal final object c.A.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): c.A.<no name provided>
+ internal final class c.A.<no name provided>.B : jet.Any {
+ public final /*constructor*/ fun <init>(): c.A.<no name provided>.B
+ internal final object c.A.<no name provided>.B.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): c.A.<no name provided>.B.<no name provided>
+ }
+ }
+ }
+}
+internal final val M: c.M
+internal final fun foo(): jet.Tuple0
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt900-2.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt900-2.txt
new file mode 100644
index 0000000000000..cc2773f8e563a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt900-2.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+// <namespace name="d">
+namespace d
+
+internal final val A: d.A
+internal final val M: d.M
+internal final var r: d.M.T
+internal final val y: d.M.T
+internal final fun f(): jet.Tuple0
+// </namespace name="d">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/kt939.txt b/compiler/testData/lazyResolve/diagnostics/scopes/kt939.txt
new file mode 100644
index 0000000000000..d3b6a63b4acd5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/kt939.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+// <namespace name="kt939">
+namespace kt939
+
+internal final fun compare(/*0*/ o1: jet.String?, /*1*/ o2: jet.String?): jet.Int
+internal final fun test(): jet.Tuple0
+// </namespace name="kt939">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/stopResolutionOnAmbiguity.txt b/compiler/testData/lazyResolve/diagnostics/scopes/stopResolutionOnAmbiguity.txt
new file mode 100644
index 0000000000000..ded0f368884a5
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/stopResolutionOnAmbiguity.txt
@@ -0,0 +1,15 @@
+namespace <root>
+
+// <namespace name="c">
+namespace c
+
+internal abstract trait c.B : jet.Any {
+ internal open fun bar(): jet.Tuple0
+}
+internal final class c.C : jet.Any {
+ public final /*constructor*/ fun <init>(): c.C
+ internal final fun bar(): jet.Tuple0
+}
+internal final fun jet.Any?.bar(): jet.Tuple0
+internal final fun test(/*0*/ a: jet.Any?): jet.Tuple0
+// </namespace name="c">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/visibility.txt b/compiler/testData/lazyResolve/diagnostics/scopes/visibility.txt
new file mode 100644
index 0000000000000..977bda3f9d270
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/visibility.txt
@@ -0,0 +1,71 @@
+namespace <root>
+
+// <namespace name="test_visibility">
+namespace test_visibility
+
+internal final class test_visibility.A : jet.Any {
+ public final /*constructor*/ fun <init>(): test_visibility.A
+ private final fun f(/*0*/ i: jet.Int): test_visibility.B
+ private final val i: jet.Int
+ internal final fun test(): jet.Tuple0
+ private final val v: test_visibility.B
+}
+internal final class test_visibility.B : jet.Any {
+ public final /*constructor*/ fun <init>(): test_visibility.B
+ internal final fun bMethod(): jet.Tuple0
+}
+internal open class test_visibility.C : test_visibility.T {
+ public final /*constructor*/ fun <init>(): test_visibility.C
+ protected final var i: jet.Int
+ internal final fun test5(): jet.Tuple0
+}
+internal final class test_visibility.D : test_visibility.C {
+ public final /*constructor*/ fun <init>(): test_visibility.D
+ protected final override /*1*/ var i: jet.Int
+ internal final val j: jet.Int
+ internal final override /*1*/ fun test5(): jet.Tuple0
+ internal final fun test6(): jet.Tuple0
+}
+internal final class test_visibility.E : test_visibility.C {
+ public final /*constructor*/ fun <init>(): test_visibility.E
+ protected final override /*1*/ var i: jet.Int
+ internal final override /*1*/ fun test5(): jet.Tuple0
+ internal final fun test7(): jet.Tuple0
+}
+internal final class test_visibility.F : test_visibility.C {
+ public final /*constructor*/ fun <init>(): test_visibility.F
+ protected final override /*1*/ var i: jet.Int
+ internal final override /*1*/ fun test5(): jet.Tuple0
+ internal final fun test8(/*0*/ c: test_visibility.C): jet.Tuple0
+}
+internal final class test_visibility.G : test_visibility.T {
+ public final /*constructor*/ fun <init>(): test_visibility.G
+ internal final fun test8(/*0*/ c: test_visibility.C): jet.Tuple0
+}
+protected final class test_visibility.ProtectedClass : jet.Any {
+ public final /*constructor*/ fun <init>(): test_visibility.ProtectedClass
+}
+protected abstract trait test_visibility.ProtectedTrait : jet.Any {
+}
+internal abstract trait test_visibility.T : jet.Any {
+}
+internal final class test_visibility.Y : jet.Any {
+ public final /*constructor*/ fun <init>(): test_visibility.Y
+ internal final fun test2(): jet.Tuple0
+}
+internal final val internal_val: jet.Int
+private final val private_val: jet.Int
+protected final val protected_val: jet.Int
+internal final fun doSmth(/*0*/ i: jet.Int): jet.Int
+internal final fun internal_fun(): jet.Tuple0
+private final fun private_fun(): jet.Tuple0
+protected final fun protected_fun(): jet.Tuple0
+internal final fun test1(): jet.Tuple0
+internal final fun test3(/*0*/ a: test_visibility.A): jet.Tuple0
+internal final fun test4(/*0*/ c: test_visibility.C): jet.Tuple0
+// </namespace name="test_visibility">
+// <namespace name="test_visibility2">
+namespace test_visibility2
+
+internal final fun test(): jet.Tuple0
+// </namespace name="test_visibility2">
diff --git a/compiler/testData/lazyResolve/diagnostics/scopes/visibility2.txt b/compiler/testData/lazyResolve/diagnostics/scopes/visibility2.txt
new file mode 100644
index 0000000000000..c7a1fef0d2996
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/scopes/visibility2.txt
@@ -0,0 +1,59 @@
+namespace <root>
+
+// <namespace name="a">
+namespace a
+
+private open class a.A : jet.Any {
+ public final /*constructor*/ fun <init>(): a.A
+ internal final fun bar(): jet.Tuple0
+}
+private final val PO: a.PO
+private final fun foo(): jet.Tuple0
+internal final fun makeA(): a.A
+// </namespace name="a">
+// <namespace name="b">
+namespace b
+
+internal final class b.B : a.A {
+ public final /*constructor*/ fun <init>(): b.B
+ invisible_fake final override /*1*/ fun bar(): jet.Tuple0
+}
+internal final class b.NewClass : java.util.ArrayList<java.lang.Integer> {
+ public final /*constructor*/ fun <init>(): b.NewClass
+ public open override /*1*/ fun add(/*0*/ p0: java.lang.Integer): jet.Boolean
+ public open override /*1*/ fun add(/*0*/ p0: jet.Int, /*1*/ p1: java.lang.Integer): jet.Tuple0
+ public open override /*1*/ fun addAll(/*0*/ p0: java.util.Collection<out java.lang.Integer>): jet.Boolean
+ public open override /*1*/ fun addAll(/*0*/ p0: jet.Int, /*1*/ p1: java.util.Collection<out java.lang.Integer>): jet.Boolean
+ public open override /*1*/ fun clear(): jet.Tuple0
+ public open override /*1*/ fun contains(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun containsAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun ensureCapacity(/*0*/ p0: jet.Int): jet.Tuple0
+ public open override /*1*/ fun get(/*0*/ p0: jet.Int): java.lang.Integer
+ public open override /*1*/ fun indexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun isEmpty(): jet.Boolean
+ public open override /*1*/ fun iterator(): java.util.Iterator<java.lang.Integer>
+ public open override /*1*/ fun lastIndexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun listIterator(): java.util.ListIterator<java.lang.Integer>
+ public open override /*1*/ fun listIterator(/*0*/ p0: jet.Int): java.util.ListIterator<java.lang.Integer>
+ protected final override /*1*/ var modCount: jet.Int
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Int): java.lang.Integer
+ public open override /*1*/ fun removeAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ protected open override /*1*/ fun removeRange(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0
+ public open override /*1*/ fun retainAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun set(/*0*/ p0: jet.Int, /*1*/ p1: java.lang.Integer): java.lang.Integer
+ public open override /*1*/ fun size(): jet.Int
+ public open override /*1*/ fun subList(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): java.util.List<java.lang.Integer>
+ public open override /*1*/ fun toArray(): jet.Array<jet.Any?>
+ public open override /*1*/ fun </*0*/ T : jet.Any?>toArray(/*0*/ p0: jet.Array<T>): jet.Array<T>
+ public open override /*1*/ fun trimToSize(): jet.Tuple0
+}
+internal final class b.Q : jet.Any {
+ public final /*constructor*/ fun <init>(): b.Q
+ internal final class b.Q.W : jet.Any {
+ public final /*constructor*/ fun <init>(): b.Q.W
+ internal final fun foo(): jet.Tuple0
+ }
+}
+internal final fun test(): jet.Tuple0
+// </namespace name="b">
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInFunctionBody.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInFunctionBody.txt
new file mode 100644
index 0000000000000..3c8b106de7b4e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInFunctionBody.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(/*0*/ p: jet.Int): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInNestedBlockInFor.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInNestedBlockInFor.txt
new file mode 100644
index 0000000000000..44d0ba473256f
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowParameterInNestedBlockInFor.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(/*0*/ i: jet.Int): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInClosure.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInClosure.txt
new file mode 100644
index 0000000000000..9e3751a0ccfed
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInClosure.txt
@@ -0,0 +1,4 @@
+namespace <root>
+
+internal final val f: jet.Function0<jet.Int>
+internal final val i: jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFor.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFor.txt
new file mode 100644
index 0000000000000..8208812b6e320
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFor.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class RedefinePropertyInFor : jet.Any {
+ public final /*constructor*/ fun <init>(): RedefinePropertyInFor
+ internal final fun ff(): jet.Tuple0
+ internal final var i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFunction.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFunction.txt
new file mode 100644
index 0000000000000..9990bd4c6a941
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowPropertyInFunction.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+internal final class RedefinePropertyInFunction : jet.Any {
+ public final /*constructor*/ fun <init>(): RedefinePropertyInFunction
+ internal final fun f(): jet.Int
+ internal final var i: jet.Int
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInFor.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInFor.txt
new file mode 100644
index 0000000000000..d7faa630170d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInFor.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedBlock.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedBlock.txt
new file mode 100644
index 0000000000000..d7faa630170d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedBlock.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosure.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosure.txt
new file mode 100644
index 0000000000000..5d7114f2eee24
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosure.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun f(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosureParam.txt b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosureParam.txt
new file mode 100644
index 0000000000000..d7faa630170d3
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/shadowing/ShadowVariableInNestedClosureParam.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun ff(): jet.Int
diff --git a/compiler/testData/lazyResolve/diagnostics/substitutions/kt1558-short.txt b/compiler/testData/lazyResolve/diagnostics/substitutions/kt1558-short.txt
new file mode 100644
index 0000000000000..3e4365ff960ea
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/substitutions/kt1558-short.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun testArrays(/*0*/ ci: java.util.List<jet.Int>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/subtyping/kt-1457.txt b/compiler/testData/lazyResolve/diagnostics/subtyping/kt-1457.txt
new file mode 100644
index 0000000000000..4e199aaf64d42
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/subtyping/kt-1457.txt
@@ -0,0 +1,33 @@
+namespace <root>
+
+internal final class MyListOfPairs</*0*/ T : jet.Any?> : java.util.ArrayList<jet.Tuple2<out T, out T>> {
+ public final /*constructor*/ fun </*0*/ T : jet.Any?><init>(): MyListOfPairs<T>
+ public open override /*1*/ fun add(/*0*/ p0: jet.Int, /*1*/ p1: jet.Tuple2<out T, out T>): jet.Tuple0
+ public open override /*1*/ fun add(/*0*/ p0: jet.Tuple2<out T, out T>): jet.Boolean
+ public open override /*1*/ fun addAll(/*0*/ p0: java.util.Collection<out jet.Tuple2<out T, out T>>): jet.Boolean
+ public open override /*1*/ fun addAll(/*0*/ p0: jet.Int, /*1*/ p1: java.util.Collection<out jet.Tuple2<out T, out T>>): jet.Boolean
+ public open override /*1*/ fun clear(): jet.Tuple0
+ public open override /*1*/ fun contains(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun containsAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun ensureCapacity(/*0*/ p0: jet.Int): jet.Tuple0
+ public open override /*1*/ fun get(/*0*/ p0: jet.Int): jet.Tuple2<out T, out T>
+ public open override /*1*/ fun indexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun isEmpty(): jet.Boolean
+ public open override /*1*/ fun iterator(): java.util.Iterator<jet.Tuple2<out T, out T>>
+ public open override /*1*/ fun lastIndexOf(/*0*/ p0: jet.Any?): jet.Int
+ public open override /*1*/ fun listIterator(): java.util.ListIterator<jet.Tuple2<out T, out T>>
+ public open override /*1*/ fun listIterator(/*0*/ p0: jet.Int): java.util.ListIterator<jet.Tuple2<out T, out T>>
+ protected final override /*1*/ var modCount: jet.Int
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Any?): jet.Boolean
+ public open override /*1*/ fun remove(/*0*/ p0: jet.Int): jet.Tuple2<out T, out T>
+ public open override /*1*/ fun removeAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ protected open override /*1*/ fun removeRange(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): jet.Tuple0
+ public open override /*1*/ fun retainAll(/*0*/ p0: java.util.Collection<out jet.Any?>): jet.Boolean
+ public open override /*1*/ fun set(/*0*/ p0: jet.Int, /*1*/ p1: jet.Tuple2<out T, out T>): jet.Tuple2<out T, out T>
+ public open override /*1*/ fun size(): jet.Int
+ public open override /*1*/ fun subList(/*0*/ p0: jet.Int, /*1*/ p1: jet.Int): java.util.List<jet.Tuple2<out T, out T>>
+ public open override /*1*/ fun toArray(): jet.Array<jet.Any?>
+ public open override /*1*/ fun </*0*/ T : jet.Any?>toArray(/*0*/ p0: jet.Array<T>): jet.Array<T>
+ public open override /*1*/ fun trimToSize(): jet.Tuple0
+}
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/subtyping/kt2069.txt b/compiler/testData/lazyResolve/diagnostics/subtyping/kt2069.txt
new file mode 100644
index 0000000000000..f3b6159f0df0e
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/subtyping/kt2069.txt
@@ -0,0 +1,17 @@
+namespace <root>
+
+// <namespace name="kt2069">
+namespace kt2069
+
+internal final class kt2069.T : kt2069.T1 {
+ public final /*constructor*/ fun <init>(): kt2069.T
+ internal final fun bar(): jet.Tuple0
+ internal open override /*1*/ fun foo(): jet.Tuple0
+ internal final object kt2069.T.<no name provided> : jet.Any {
+ internal final /*constructor*/ fun <init>(): kt2069.T.<no name provided>
+ }
+}
+internal abstract trait kt2069.T1 : jet.Any {
+ internal open fun foo(): jet.Tuple0
+}
+// </namespace name="kt2069">
diff --git a/compiler/testData/lazyResolve/diagnostics/tuples/BasicTuples.txt b/compiler/testData/lazyResolve/diagnostics/tuples/BasicTuples.txt
new file mode 100644
index 0000000000000..d4170907a0bc6
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/tuples/BasicTuples.txt
@@ -0,0 +1,3 @@
+namespace <root>
+
+internal final fun foo(/*0*/ a: jet.Tuple2<out jet.Int, out jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/AmbiguousVararg.txt b/compiler/testData/lazyResolve/diagnostics/varargs/AmbiguousVararg.txt
new file mode 100644
index 0000000000000..9ae417d42d909
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/AmbiguousVararg.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun foo(/*0*/ vararg t: jet.Int /*jet.IntArray*/): jet.String
+internal final fun foo(/*0*/ vararg t: jet.String /*jet.Array<jet.String>*/): jet.String
+internal final fun test(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/MoreSpecificVarargsOfEqualLength.txt b/compiler/testData/lazyResolve/diagnostics/varargs/MoreSpecificVarargsOfEqualLength.txt
new file mode 100644
index 0000000000000..f586865c7fb7a
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/MoreSpecificVarargsOfEqualLength.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+internal final class D : jet.Any {
+ public final /*constructor*/ fun <init>(): D
+ internal final fun from(/*0*/ vararg a: jet.Any /*jet.Array<jet.Any>*/): jet.Tuple0
+ internal final fun from(/*0*/ vararg a: jet.String /*jet.Array<jet.String>*/): jet.Tuple0
+}
+internal final fun main(/*0*/ d: D): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/MostSepcificVarargsWithJava.txt b/compiler/testData/lazyResolve/diagnostics/varargs/MostSepcificVarargsWithJava.txt
new file mode 100644
index 0000000000000..1f37d7bfc50b0
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/MostSepcificVarargsWithJava.txt
@@ -0,0 +1,11 @@
+namespace <root>
+
+public open class C : java.lang.Object {
+ public final /*constructor*/ fun <init>(): C
+ package open fun from(): jet.Tuple0
+ package open fun from(/*0*/ s1: jet.String?, /*1*/ vararg s: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+ package open fun from(/*0*/ s: jet.String?): jet.Tuple0
+ package open fun from(/*0*/ s: jet.String?, /*1*/ s1: jet.String?): jet.Tuple0
+ package open fun from(/*0*/ vararg s: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+}
+internal final fun main(/*0*/ j: C, /*1*/ s: jet.Array<jet.String?>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/NilaryVsVararg.txt b/compiler/testData/lazyResolve/diagnostics/varargs/NilaryVsVararg.txt
new file mode 100644
index 0000000000000..f996f8debcbb1
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/NilaryVsVararg.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun foo0(): jet.String
+internal final fun foo0(/*0*/ vararg t: jet.Int /*jet.IntArray*/): jet.String
+internal final fun test0(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/UnaryVsVararg.txt b/compiler/testData/lazyResolve/diagnostics/varargs/UnaryVsVararg.txt
new file mode 100644
index 0000000000000..a2a5212852fad
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/UnaryVsVararg.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final fun foo1(/*0*/ a: jet.Int): jet.String
+internal final fun foo1(/*0*/ a: jet.Int, /*1*/ vararg t: jet.Int /*jet.IntArray*/): jet.String
+internal final fun test1(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/kt1781.txt b/compiler/testData/lazyResolve/diagnostics/varargs/kt1781.txt
new file mode 100644
index 0000000000000..eb653699101be
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/kt1781.txt
@@ -0,0 +1,7 @@
+namespace <root>
+
+public open class JavaClass : java.lang.Object {
+ public final /*constructor*/ fun <init>(): JavaClass
+ public final /*constructor*/ fun <init>(/*0*/ vararg ss: jet.String? /*jet.Array<jet.String?>*/): JavaClass
+}
+internal final fun foo(): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/kt1835.txt b/compiler/testData/lazyResolve/diagnostics/varargs/kt1835.txt
new file mode 100644
index 0000000000000..39182329abd27
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/kt1835.txt
@@ -0,0 +1,8 @@
+namespace <root>
+
+public open class JavaClass : java.lang.Object {
+ public final /*constructor*/ fun <init>(): JavaClass
+ package open fun from(/*0*/ s: jet.String?): jet.Tuple0
+ package open fun from(/*0*/ vararg s: jet.String? /*jet.Array<jet.String?>*/): jet.Tuple0
+}
+internal final fun main(/*0*/ args: jet.Array<jet.String>): jet.Tuple0
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-param.txt b/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-param.txt
new file mode 100644
index 0000000000000..b0f8c7c49f3d2
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-param.txt
@@ -0,0 +1,5 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ vararg t: jet.Int /*jet.IntArray*/): A
+}
diff --git a/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-val.txt b/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-val.txt
new file mode 100644
index 0000000000000..cae074c94a972
--- /dev/null
+++ b/compiler/testData/lazyResolve/diagnostics/varargs/kt1838-val.txt
@@ -0,0 +1,6 @@
+namespace <root>
+
+internal final class A : jet.Any {
+ public final /*constructor*/ fun <init>(/*0*/ vararg t: jet.Int /*jet.IntArray*/): A
+ internal final val t: jet.IntArray
+}
diff --git a/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java b/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java
index 77b940858ad37..00c5f0ae8985c 100644
--- a/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java
+++ b/compiler/tests/org/jetbrains/jet/checkers/AbstractDiagnosticsTestWithEagerResolve.java
@@ -37,7 +37,8 @@
*/
public abstract class AbstractDiagnosticsTestWithEagerResolve extends AbstractJetDiagnosticsTest {
- protected void analyzeAndCheck(String expectedText, List<TestFile> testFiles) {
+ @Override
+ protected void analyzeAndCheck(File testDataFile, String expectedText, List<TestFile> testFiles) {
List<JetFile> jetFiles = getJetFiles(testFiles);
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
diff --git a/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java b/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java
index 224b863d6a397..5bf46e99695b9 100644
--- a/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java
+++ b/compiler/tests/org/jetbrains/jet/checkers/AbstractJetDiagnosticsTest.java
@@ -86,10 +86,10 @@ public TestFile create(String fileName, String text) {
getEnvironment().addToClasspath(javaFilesDir);
}
- analyzeAndCheck(expectedText, testFiles);
+ analyzeAndCheck(file, expectedText, testFiles);
}
- protected abstract void analyzeAndCheck(String expectedText, List<TestFile> files);
+ protected abstract void analyzeAndCheck(File testDataFile, String expectedText, List<TestFile> files);
protected static List<JetFile> getJetFiles(List<TestFile> testFiles) {
List<JetFile> jetFiles = Lists.newArrayList();
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 72a492a53e876..5be6dfd47c316 100644
--- a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java
+++ b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/AbstractLazyResolveDiagnosticsTest.java
@@ -16,15 +16,18 @@
package org.jetbrains.jet.lang.resolve.lazy;
-import com.google.common.base.Predicates;
+import com.google.common.base.Predicate;
+import com.intellij.openapi.util.io.FileUtil;
import junit.framework.TestCase;
import org.jetbrains.jet.ConfigurationKind;
+import org.jetbrains.jet.JetTestUtils;
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.lang.resolve.name.Name;
import org.jetbrains.jet.test.generator.SimpleTestClassModel;
import org.jetbrains.jet.test.generator.TestGenerator;
@@ -37,18 +40,31 @@
* @author abreslav
*/
public abstract class AbstractLazyResolveDiagnosticsTest extends AbstractJetDiagnosticsTest {
+
+ private static final File TEST_DATA_DIR = new File("compiler/testData/diagnostics/tests");
+
@Override
protected JetCoreEnvironment createEnvironment() {
- return createEnvironmentWithMockJdk(ConfigurationKind.ALL);
+ return createEnvironmentWithMockJdk(ConfigurationKind.JDK_AND_ANNOTATIONS);
}
@Override
- protected void analyzeAndCheck(String expectedText, List<TestFile> files) {
+ protected void analyzeAndCheck(File testDataFile, 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());
+ String path = JetTestUtils.getFilePath(new File(FileUtil.getRelativePath(TEST_DATA_DIR, testDataFile)));
+ String txtFileRelativePath = path.replaceAll("\\.kt$|\\.ktscript", ".txt");
+ File txtFile = new File("compiler/testData/lazyResolve/diagnostics/" + txtFileRelativePath);
+ NamespaceComparator.compareNamespaces(eagerModule.getRootNamespace(), lazyModule.getRootNamespace(), false,
+ new Predicate<NamespaceDescriptor>() {
+ @Override
+ public boolean apply(NamespaceDescriptor descriptor) {
+ return !Name.identifier("jet").equals(descriptor.getName());
+ }
+ },
+ txtFile);
}
public static void main(String[] args) throws IOException {
@@ -59,7 +75,7 @@ public static void main(String[] args) throws IOException {
"LazyResolveDiagnosticsTestGenerated",
thisClass,
Arrays.asList(
- new SimpleTestClassModel(new File("compiler/testData/diagnostics/tests"), true, "kt", "doTest"),
+ new SimpleTestClassModel(TEST_DATA_DIR, true, "kt", "doTest"),
new SimpleTestClassModel(new File("compiler/testData/diagnostics/tests/script"), true, "ktscript", "doTest")
),
thisClass
|
f119ea70438e3ff3d72678086ce4c58441a445a7
|
orientdb
|
GraphDB: supported 3 locking modes: no locking
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java
index e318c7141d9..564fcd31ea6 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphDatabase.java
@@ -32,6 +32,7 @@
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
+import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.OStorageEmbedded;
import com.orientechnologies.orient.core.tx.OTransactionNoTx;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;
@@ -47,6 +48,10 @@
*
*/
public class OGraphDatabase extends ODatabaseDocumentTx {
+ public enum LOCK_MODE {
+ NO_LOCKING, DATABASE_LEVEL_LOCKING, RECORD_LEVEL_LOCKING
+ }
+
public static final String TYPE = "graph";
public static final String VERTEX_CLASS_NAME = "OGraphVertex";
@@ -62,7 +67,7 @@ public class OGraphDatabase extends ODatabaseDocumentTx {
private boolean useCustomTypes = true;
private boolean safeMode = false;
- private boolean autoLock = true;
+ private LOCK_MODE lockMode = LOCK_MODE.DATABASE_LEVEL_LOCKING;
protected OClass vertexBaseClass;
protected OClass edgeBaseClass;
@@ -80,11 +85,6 @@ public OGraphDatabase(final ODatabaseRecordTx iSource) {
public <THISDB extends ODatabase> THISDB open(final String iUserName, final String iUserPassword) {
super.open(iUserName, iUserPassword);
checkForGraphSchema();
-
- if (autoLock && !(getStorage() instanceof OStorageEmbedded))
- // NOT YET SUPPORETD REMOTE LOCKING
- autoLock = false;
-
return (THISDB) this;
}
@@ -218,10 +218,9 @@ public ODocument createEdge(final ODocument iOutVertex, final ODocument iInVerte
edge.field(iFields[i].toString(), iFields[i + 1]);
// OUT FIELD
- if (autoLock)
- // LOCK VERTEX TO AVOID CONCURRENT ACCESS
- acquireWriteLock(iOutVertex);
+ acquireWriteLock(iOutVertex);
try {
+
final Object outField = iOutVertex.field(VERTEX_FIELD_OUT);
final OMVRBTreeRIDSet out;
if (outField instanceof OMVRBTreeRIDSet) {
@@ -235,15 +234,13 @@ public ODocument createEdge(final ODocument iOutVertex, final ODocument iInVerte
}
out.add(edge);
} finally {
- if (autoLock)
- releaseWriteLock(iOutVertex);
+ releaseWriteLock(iOutVertex);
}
// IN FIELD
- if (autoLock)
- // LOCK VERTEX TO AVOID CONCURRENT ACCESS
- acquireWriteLock(iInVertex);
+ acquireWriteLock(iInVertex);
try {
+
final Object inField = iInVertex.field(VERTEX_FIELD_IN);
final OMVRBTreeRIDSet in;
if (inField instanceof OMVRBTreeRIDSet) {
@@ -256,9 +253,9 @@ public ODocument createEdge(final ODocument iOutVertex, final ODocument iInVerte
iInVertex.field(VERTEX_FIELD_IN, in);
}
in.add(edge);
+
} finally {
- if (autoLock)
- releaseWriteLock(iInVertex);
+ releaseWriteLock(iInVertex);
}
edge.setDirty();
@@ -290,8 +287,7 @@ public boolean removeEdge(final OIdentifiable iEdge) {
// OUT VERTEX
final ODocument outVertex = edge.field(EDGE_FIELD_OUT);
- if (autoLock)
- acquireWriteLock(outVertex);
+ acquireWriteLock(outVertex);
try {
if (outVertex != null) {
@@ -302,15 +298,13 @@ public boolean removeEdge(final OIdentifiable iEdge) {
}
} finally {
- if (autoLock)
- releaseWriteLock(outVertex);
+ releaseWriteLock(outVertex);
}
// IN VERTEX
final ODocument inVertex = edge.field(EDGE_FIELD_IN);
- if (autoLock)
- acquireWriteLock(inVertex);
+ acquireWriteLock(inVertex);
try {
if (inVertex != null) {
@@ -321,8 +315,7 @@ public boolean removeEdge(final OIdentifiable iEdge) {
}
} finally {
- if (autoLock)
- releaseWriteLock(inVertex);
+ releaseWriteLock(inVertex);
}
delete(edge);
@@ -344,10 +337,9 @@ public void removeVertex(final ODocument iVertex) {
Set<ODocument> otherEdges;
// REMOVE OUT EDGES
- if (autoLock)
- // LOCK VERTEX TO AVOID CONCURRENT ACCESS
- acquireWriteLock(iVertex);
+ acquireWriteLock(iVertex);
try {
+
Set<ODocument> edges = iVertex.field(VERTEX_FIELD_OUT);
if (edges != null) {
for (ODocument edge : edges) {
@@ -383,8 +375,7 @@ public void removeVertex(final ODocument iVertex) {
delete(iVertex);
} finally {
- if (autoLock)
- releaseWriteLock(iVertex);
+ releaseWriteLock(iVertex);
}
commitBlock(safeMode);
@@ -444,9 +435,7 @@ public Set<OIdentifiable> getEdgesBetweenVertexes(final OIdentifiable iVertex1,
final Set<OIdentifiable> result = new HashSet<OIdentifiable>();
if (iVertex1 != null && iVertex2 != null) {
- if (autoLock)
- // LOCK VERTEX TO AVOID CONCURRENT ACCESS
- acquireReadLock(iVertex1);
+ acquireReadLock(iVertex1);
try {
// CHECK OUT EDGES
@@ -472,8 +461,7 @@ public Set<OIdentifiable> getEdgesBetweenVertexes(final OIdentifiable iVertex1,
}
} finally {
- if (autoLock)
- releaseReadLock(iVertex1);
+ releaseReadLock(iVertex1);
}
}
@@ -500,8 +488,7 @@ public Set<OIdentifiable> getOutEdges(final OIdentifiable iVertex, final String
OMVRBTreeRIDSet result = null;
- if (autoLock)
- acquireReadLock(iVertex);
+ acquireReadLock(iVertex);
try {
final OMVRBTreeRIDSet set = vertex.field(VERTEX_FIELD_OUT);
@@ -522,8 +509,7 @@ public Set<OIdentifiable> getOutEdges(final OIdentifiable iVertex, final String
}
} finally {
- if (autoLock)
- releaseReadLock(iVertex);
+ releaseReadLock(iVertex);
}
return result;
@@ -571,8 +557,7 @@ public Set<OIdentifiable> getInEdges(final OIdentifiable iVertex, final String i
OMVRBTreeRIDSet result = null;
- if (autoLock)
- acquireReadLock(iVertex);
+ acquireReadLock(iVertex);
try {
final OMVRBTreeRIDSet set = vertex.field(VERTEX_FIELD_IN);
@@ -593,8 +578,7 @@ public Set<OIdentifiable> getInEdges(final OIdentifiable iVertex, final String i
}
} finally {
- if (autoLock)
- releaseReadLock(iVertex);
+ releaseReadLock(iVertex);
}
return result;
}
@@ -664,8 +648,7 @@ public ODocument getOutVertex(final OIdentifiable iEdge) {
}
public Set<OIdentifiable> filterEdgesByProperties(final OMVRBTreeRIDSet iEdges, final Iterable<String> iPropertyNames) {
- if (autoLock)
- acquireReadLock(null);
+ acquireReadLock(null);
try {
if (iPropertyNames == null)
@@ -690,14 +673,12 @@ public Set<OIdentifiable> filterEdgesByProperties(final OMVRBTreeRIDSet iEdges,
return result;
} finally {
- if (autoLock)
- releaseReadLock(null);
+ releaseReadLock(null);
}
}
public Set<OIdentifiable> filterEdgesByProperties(final OMVRBTreeRIDSet iEdges, final Map<String, Object> iProperties) {
- if (autoLock)
- acquireReadLock(null);
+ acquireReadLock(null);
try {
if (iProperties == null)
@@ -727,8 +708,7 @@ public Set<OIdentifiable> filterEdgesByProperties(final OMVRBTreeRIDSet iEdges,
return result;
} finally {
- if (autoLock)
- releaseReadLock(null);
+ releaseReadLock(null);
}
}
@@ -886,14 +866,6 @@ public boolean isEdge(final ODocument iRecord) {
return iRecord != null ? iRecord.getSchemaClass().isSubClassOf(edgeBaseClass) : false;
}
- public boolean isAutoLock() {
- return autoLock;
- }
-
- public void setAutoLock(final boolean iAutoLock) {
- this.autoLock = iAutoLock;
- }
-
/**
* Locks the record in exclusive mode to avoid concurrent access.
*
@@ -902,8 +874,16 @@ public void setAutoLock(final boolean iAutoLock) {
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase acquireWriteLock(final OIdentifiable iRecord) {
- ((OStorageEmbedded) getStorage()).getLock().acquireExclusiveLock();
- // ((OStorageEmbedded) getStorage()).acquireWriteLock(iRecord.getIdentity());
+ switch (lockMode) {
+ case DATABASE_LEVEL_LOCKING:
+ ((OStorage) getStorage()).getLock().acquireExclusiveLock();
+ break;
+ case RECORD_LEVEL_LOCKING:
+ ((OStorageEmbedded) getStorage()).acquireWriteLock(iRecord.getIdentity());
+ break;
+ case NO_LOCKING:
+ break;
+ }
return this;
}
@@ -915,8 +895,16 @@ public OGraphDatabase acquireWriteLock(final OIdentifiable iRecord) {
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase releaseWriteLock(final OIdentifiable iRecord) {
- ((OStorageEmbedded) getStorage()).getLock().releaseExclusiveLock();
- // ((OStorageEmbedded) getStorage()).releaseWriteLock(iRecord.getIdentity());
+ switch (lockMode) {
+ case DATABASE_LEVEL_LOCKING:
+ ((OStorage) getStorage()).getLock().releaseExclusiveLock();
+ break;
+ case RECORD_LEVEL_LOCKING:
+ ((OStorageEmbedded) getStorage()).releaseWriteLock(iRecord.getIdentity());
+ break;
+ case NO_LOCKING:
+ break;
+ }
return this;
}
@@ -928,8 +916,16 @@ public OGraphDatabase releaseWriteLock(final OIdentifiable iRecord) {
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase acquireReadLock(final OIdentifiable iRecord) {
- ((OStorageEmbedded) getStorage()).getLock().acquireSharedLock();
- // ((OStorageEmbedded) getStorage()).acquireReadLock(iRecord.getIdentity());
+ switch (lockMode) {
+ case DATABASE_LEVEL_LOCKING:
+ ((OStorage) getStorage()).getLock().acquireSharedLock();
+ break;
+ case RECORD_LEVEL_LOCKING:
+ ((OStorageEmbedded) getStorage()).acquireReadLock(iRecord.getIdentity());
+ break;
+ case NO_LOCKING:
+ break;
+ }
return this;
}
@@ -941,8 +937,16 @@ public OGraphDatabase acquireReadLock(final OIdentifiable iRecord) {
* @return The current instance as fluent interface to allow calls in chain.
*/
public OGraphDatabase releaseReadLock(final OIdentifiable iRecord) {
- ((OStorageEmbedded) getStorage()).getLock().releaseSharedLock();
- // ((OStorageEmbedded) getStorage()).releaseReadLock(iRecord.getIdentity());
+ switch (lockMode) {
+ case DATABASE_LEVEL_LOCKING:
+ ((OStorage) getStorage()).getLock().releaseSharedLock();
+ break;
+ case RECORD_LEVEL_LOCKING:
+ ((OStorageEmbedded) getStorage()).releaseReadLock(iRecord.getIdentity());
+ break;
+ case NO_LOCKING:
+ break;
+ }
return this;
}
@@ -1024,4 +1028,16 @@ protected boolean checkEdge(final ODocument iEdge, final String[] iLabels, final
}
return good;
}
+
+ public LOCK_MODE getLockMode() {
+ return lockMode;
+ }
+
+ public void setLockMode(final LOCK_MODE lockMode) {
+ if (lockMode == LOCK_MODE.RECORD_LEVEL_LOCKING && !(getStorage() instanceof OStorageEmbedded))
+ // NOT YET SUPPORETD REMOTE LOCKING
+ throw new IllegalArgumentException("Record leve locking is not supported for remote connections");
+
+ this.lockMode = lockMode;
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
index ed8bacc60ca..0c4bae3a7f5 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
@@ -17,6 +17,7 @@
import java.io.IOException;
+import com.orientechnologies.common.concur.lock.OLockManager.LOCK;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
@@ -52,10 +53,10 @@ public OStorageEmbedded(final String iName, final String iFilePath, final String
PROFILER_DELETE_RECORD = "db." + name + ".deleteRecord";
}
- protected abstract ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId iRid, boolean iAtomicLock);
-
public abstract OCluster getClusterByName(final String iClusterName);
+ protected abstract ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId iRid, boolean iAtomicLock);
+
/**
* Closes the storage freeing the lock manager first.
*/
@@ -94,14 +95,6 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE
}
}
- /**
- * Checks if the storage is open. If it's closed an exception is raised.
- */
- protected void checkOpeness() {
- if (status != STATUS.OPEN)
- throw new OStorageException("Storage " + name + " is not opened.");
- }
-
@Override
public long[] getClusterPositionsForEntry(int currentClusterId, long entry) {
if (currentClusterId == -1)
@@ -126,6 +119,22 @@ public long[] getClusterPositionsForEntry(int currentClusterId, long entry) {
}
}
+ public void acquireWriteLock(final ORID iRid) {
+ lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE);
+ }
+
+ public void releaseWriteLock(final ORID iRid) {
+ lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE);
+ }
+
+ public void acquireReadLock(final ORID iRid) {
+ lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.SHARED);
+ }
+
+ public void releaseReadLock(final ORID iRid) {
+ lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.SHARED);
+ }
+
protected OPhysicalPosition moveRecord(ORID originalId, ORID newId) throws IOException {
final OCluster originalCluster = getClusterById(originalId.getClusterId());
final OCluster destinationCluster = getClusterById(newId.getClusterId());
@@ -190,4 +199,12 @@ protected OPhysicalPosition moveRecord(ORID originalId, ORID newId) throws IOExc
return ppos;
}
+
+ /**
+ * Checks if the storage is open. If it's closed an exception is raised.
+ */
+ protected void checkOpeness() {
+ if (status != STATUS.OPEN)
+ throw new OStorageException("Storage " + name + " is not opened.");
+ }
}
|
37d68385670d60a4bb73d2947e9da1eef0173c6b
|
tapiji
|
Cleans up build stragegy.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html b/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html
new file mode 100644
index 00000000..84ec2511
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.core.ui/epl-v10.html
@@ -0,0 +1,261 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
+<title>Eclipse Public License - Version 1.0</title>
+<style type="text/css">
+ body {
+ size: 8.5in 11.0in;
+ margin: 0.25in 0.5in 0.25in 0.5in;
+ tab-interval: 0.5in;
+ }
+ p {
+ margin-left: auto;
+ margin-top: 0.5em;
+ margin-bottom: 0.5em;
+ }
+ p.list {
+ margin-left: 0.5in;
+ margin-top: 0.05em;
+ margin-bottom: 0.05em;
+ }
+ </style>
+
+</head>
+
+<body lang="EN-US">
+
+<p align=center><b>Eclipse Public License - v 1.0</b></p>
+
+<p>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
+PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
+DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
+AGREEMENT.</p>
+
+<p><b>1. DEFINITIONS</b></p>
+
+<p>"Contribution" means:</p>
+
+<p class="list">a) in the case of the initial Contributor, the initial
+code and documentation distributed under this Agreement, and</p>
+<p class="list">b) in the case of each subsequent Contributor:</p>
+<p class="list">i) changes to the Program, and</p>
+<p class="list">ii) additions to the Program;</p>
+<p class="list">where such changes and/or additions to the Program
+originate from and are distributed by that particular Contributor. A
+Contribution 'originates' from a Contributor if it was added to the
+Program by such Contributor itself or anyone acting on such
+Contributor's behalf. Contributions do not include additions to the
+Program which: (i) are separate modules of software distributed in
+conjunction with the Program under their own license agreement, and (ii)
+are not derivative works of the Program.</p>
+
+<p>"Contributor" means any person or entity that distributes
+the Program.</p>
+
+<p>"Licensed Patents" mean patent claims licensable by a
+Contributor which are necessarily infringed by the use or sale of its
+Contribution alone or when combined with the Program.</p>
+
+<p>"Program" means the Contributions distributed in accordance
+with this Agreement.</p>
+
+<p>"Recipient" means anyone who receives the Program under
+this Agreement, including all Contributors.</p>
+
+<p><b>2. GRANT OF RIGHTS</b></p>
+
+<p class="list">a) Subject to the terms of this Agreement, each
+Contributor hereby grants Recipient a non-exclusive, worldwide,
+royalty-free copyright license to reproduce, prepare derivative works
+of, publicly display, publicly perform, distribute and sublicense the
+Contribution of such Contributor, if any, and such derivative works, in
+source code and object code form.</p>
+
+<p class="list">b) Subject to the terms of this Agreement, each
+Contributor hereby grants Recipient a non-exclusive, worldwide,
+royalty-free patent license under Licensed Patents to make, use, sell,
+offer to sell, import and otherwise transfer the Contribution of such
+Contributor, if any, in source code and object code form. This patent
+license shall apply to the combination of the Contribution and the
+Program if, at the time the Contribution is added by the Contributor,
+such addition of the Contribution causes such combination to be covered
+by the Licensed Patents. The patent license shall not apply to any other
+combinations which include the Contribution. No hardware per se is
+licensed hereunder.</p>
+
+<p class="list">c) Recipient understands that although each Contributor
+grants the licenses to its Contributions set forth herein, no assurances
+are provided by any Contributor that the Program does not infringe the
+patent or other intellectual property rights of any other entity. Each
+Contributor disclaims any liability to Recipient for claims brought by
+any other entity based on infringement of intellectual property rights
+or otherwise. As a condition to exercising the rights and licenses
+granted hereunder, each Recipient hereby assumes sole responsibility to
+secure any other intellectual property rights needed, if any. For
+example, if a third party patent license is required to allow Recipient
+to distribute the Program, it is Recipient's responsibility to acquire
+that license before distributing the Program.</p>
+
+<p class="list">d) Each Contributor represents that to its knowledge it
+has sufficient copyright rights in its Contribution, if any, to grant
+the copyright license set forth in this Agreement.</p>
+
+<p><b>3. REQUIREMENTS</b></p>
+
+<p>A Contributor may choose to distribute the Program in object code
+form under its own license agreement, provided that:</p>
+
+<p class="list">a) it complies with the terms and conditions of this
+Agreement; and</p>
+
+<p class="list">b) its license agreement:</p>
+
+<p class="list">i) effectively disclaims on behalf of all Contributors
+all warranties and conditions, express and implied, including warranties
+or conditions of title and non-infringement, and implied warranties or
+conditions of merchantability and fitness for a particular purpose;</p>
+
+<p class="list">ii) effectively excludes on behalf of all Contributors
+all liability for damages, including direct, indirect, special,
+incidental and consequential damages, such as lost profits;</p>
+
+<p class="list">iii) states that any provisions which differ from this
+Agreement are offered by that Contributor alone and not by any other
+party; and</p>
+
+<p class="list">iv) states that source code for the Program is available
+from such Contributor, and informs licensees how to obtain it in a
+reasonable manner on or through a medium customarily used for software
+exchange.</p>
+
+<p>When the Program is made available in source code form:</p>
+
+<p class="list">a) it must be made available under this Agreement; and</p>
+
+<p class="list">b) a copy of this Agreement must be included with each
+copy of the Program.</p>
+
+<p>Contributors may not remove or alter any copyright notices contained
+within the Program.</p>
+
+<p>Each Contributor must identify itself as the originator of its
+Contribution, if any, in a manner that reasonably allows subsequent
+Recipients to identify the originator of the Contribution.</p>
+
+<p><b>4. COMMERCIAL DISTRIBUTION</b></p>
+
+<p>Commercial distributors of software may accept certain
+responsibilities with respect to end users, business partners and the
+like. While this license is intended to facilitate the commercial use of
+the Program, the Contributor who includes the Program in a commercial
+product offering should do so in a manner which does not create
+potential liability for other Contributors. Therefore, if a Contributor
+includes the Program in a commercial product offering, such Contributor
+("Commercial Contributor") hereby agrees to defend and
+indemnify every other Contributor ("Indemnified Contributor")
+against any losses, damages and costs (collectively "Losses")
+arising from claims, lawsuits and other legal actions brought by a third
+party against the Indemnified Contributor to the extent caused by the
+acts or omissions of such Commercial Contributor in connection with its
+distribution of the Program in a commercial product offering. The
+obligations in this section do not apply to any claims or Losses
+relating to any actual or alleged intellectual property infringement. In
+order to qualify, an Indemnified Contributor must: a) promptly notify
+the Commercial Contributor in writing of such claim, and b) allow the
+Commercial Contributor to control, and cooperate with the Commercial
+Contributor in, the defense and any related settlement negotiations. The
+Indemnified Contributor may participate in any such claim at its own
+expense.</p>
+
+<p>For example, a Contributor might include the Program in a commercial
+product offering, Product X. That Contributor is then a Commercial
+Contributor. If that Commercial Contributor then makes performance
+claims, or offers warranties related to Product X, those performance
+claims and warranties are such Commercial Contributor's responsibility
+alone. Under this section, the Commercial Contributor would have to
+defend claims against the other Contributors related to those
+performance claims and warranties, and if a court requires any other
+Contributor to pay any damages as a result, the Commercial Contributor
+must pay those damages.</p>
+
+<p><b>5. NO WARRANTY</b></p>
+
+<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
+PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
+ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
+OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and
+distributing the Program and assumes all risks associated with its
+exercise of rights under this Agreement , including but not limited to
+the risks and costs of program errors, compliance with applicable laws,
+damage to or loss of data, programs or equipment, and unavailability or
+interruption of operations.</p>
+
+<p><b>6. DISCLAIMER OF LIABILITY</b></p>
+
+<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
+NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
+WITHOUT LIMITATION LOST PROFITS), 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 OR
+DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
+HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p>
+
+<p><b>7. GENERAL</b></p>
+
+<p>If any provision of this Agreement is invalid or unenforceable under
+applicable law, it shall not affect the validity or enforceability of
+the remainder of the terms of this Agreement, and without further action
+by the parties hereto, such provision shall be reformed to the minimum
+extent necessary to make such provision valid and enforceable.</p>
+
+<p>If Recipient institutes patent litigation against any entity
+(including a cross-claim or counterclaim in a lawsuit) alleging that the
+Program itself (excluding combinations of the Program with other
+software or hardware) infringes such Recipient's patent(s), then such
+Recipient's rights granted under Section 2(b) shall terminate as of the
+date such litigation is filed.</p>
+
+<p>All Recipient's rights under this Agreement shall terminate if it
+fails to comply with any of the material terms or conditions of this
+Agreement and does not cure such failure in a reasonable period of time
+after becoming aware of such noncompliance. If all Recipient's rights
+under this Agreement terminate, Recipient agrees to cease use and
+distribution of the Program as soon as reasonably practicable. However,
+Recipient's obligations under this Agreement and any licenses granted by
+Recipient relating to the Program shall continue and survive.</p>
+
+<p>Everyone is permitted to copy and distribute copies of this
+Agreement, but in order to avoid inconsistency the Agreement is
+copyrighted and may only be modified in the following manner. The
+Agreement Steward reserves the right to publish new versions (including
+revisions) of this Agreement from time to time. No one other than the
+Agreement Steward has the right to modify this Agreement. The Eclipse
+Foundation is the initial Agreement Steward. The Eclipse Foundation may
+assign the responsibility to serve as the Agreement Steward to a
+suitable separate entity. Each new version of the Agreement will be
+given a distinguishing version number. The Program (including
+Contributions) may always be distributed subject to the version of the
+Agreement under which it was received. In addition, after a new version
+of the Agreement is published, Contributor may elect to distribute the
+Program (including its Contributions) under the new version. Except as
+expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
+rights or licenses to the intellectual property of any Contributor under
+this Agreement, whether expressly, by implication, estoppel or
+otherwise. All rights in the Program not expressly granted under this
+Agreement are reserved.</p>
+
+<p>This Agreement is governed by the laws of the State of New York and
+the intellectual property laws of the United States of America. No party
+to this Agreement will bring a legal action under this Agreement more
+than one year after the cause of action arose. Each party waives its
+rights to a jury trial in any resulting litigation.</p>
+
+</body>
+
+</html>
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
index 604783c9..7f147a53 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
@@ -19,6 +19,7 @@
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.dialogs.InputDialog;
@@ -29,71 +30,73 @@
public class CreateResourceBundleEntry implements IMarkerResolution2 {
- private String key;
- private String bundleId;
+ private String key;
+ private String bundleId;
- public CreateResourceBundleEntry(String key, String bundleId) {
- this.key = key;
- this.bundleId = bundleId;
- }
+ public CreateResourceBundleEntry(String key, String bundleId) {
+ this.key = key;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Creates a new Resource-Bundle entry for the property-key '"
+ + key + "'";
+ }
- @Override
- public String getDescription() {
- return "Creates a new Resource-Bundle entry for the property-key '"
- + key + "'";
- }
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public String getLabel() {
+ return "Create Resource-Bundle entry for '" + key + "'";
+ }
- @Override
- public String getLabel() {
- return "Create Resource-Bundle entry for '" + key + "'";
- }
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(key != null ? key : "");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle(bundleId);
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(key != null ? key : "");
- config.setPreselectedMessage("");
- config.setPreselectedBundle(bundleId);
- config.setPreselectedLocale("");
- config.setProjectName(resource.getProject().getName());
+ dialog.setDialogConfiguration(config);
- dialog.setDialogConfiguration(config);
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ try {
+ resource.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
- if (dialog.open() != InputDialog.OK)
- return;
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- (new I18nBuilder()).buildResource(resource, null);
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
}
- }
-
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
index 45762ea2..ecb947b4 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
@@ -20,6 +20,7 @@
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IJavaProject;
@@ -37,158 +38,164 @@
public class CreateResourceBundle implements IMarkerResolution2 {
- private IResource resource;
- private int start;
- private int end;
- private String key;
- private boolean jsfContext;
- private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
-
- public CreateResourceBundle(String key, IResource resource, int start,
- int end) {
- this.key = ResourceUtils.deriveNonExistingRBName(key,
- ResourceBundleManager.getManager(resource.getProject()));
- this.resource = resource;
- this.start = start;
- this.end = end;
- this.jsfContext = jsfContext;
- }
-
- @Override
- public String getDescription() {
- return "Creates a new Resource-Bundle with the id '" + key + "'";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Create Resource-Bundle '" + key + "'";
- }
-
- @Override
- public void run(IMarker marker) {
- runAction();
- }
-
- protected void runAction() {
- // First see if this is a "new wizard".
- IWizardDescriptor descriptor = PlatformUI.getWorkbench()
- .getNewWizardRegistry().findWizard(newBunldeWizard);
- // If not check if it is an "import wizard".
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
- .findWizard(newBunldeWizard);
+ private IResource resource;
+ private int start;
+ private int end;
+ private String key;
+ private boolean jsfContext;
+ private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
+
+ public CreateResourceBundle(String key, IResource resource, int start,
+ int end) {
+ this.key = ResourceUtils.deriveNonExistingRBName(key,
+ ResourceBundleManager.getManager(resource.getProject()));
+ this.resource = resource;
+ this.start = start;
+ this.end = end;
+ this.jsfContext = jsfContext;
}
- // Or maybe an export wizard
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
- .findWizard(newBunldeWizard);
+
+ @Override
+ public String getDescription() {
+ return "Creates a new Resource-Bundle with the id '" + key + "'";
}
- try {
- // Then if we have a wizard, open it.
- if (descriptor != null) {
- IWizard wizard = descriptor.createWizard();
- if (!(wizard instanceof IResourceBundleWizard))
- return;
-
- IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
- String[] keySilbings = key.split("\\.");
- String rbName = keySilbings[keySilbings.length - 1];
- String packageName = "";
-
- rbw.setBundleId(rbName);
-
- // Set the default path according to the specified package name
- String pathName = "";
- if (keySilbings.length > 1) {
- try {
- IJavaProject jp = JavaCore
- .create(resource.getProject());
- packageName = key.substring(0, key.lastIndexOf("."));
-
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- IPackageFragment pf = fr
- .getPackageFragment(packageName);
- if (pf.exists()) {
- pathName = pf.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
- }
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- if (pathName.trim().equals("")) {
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- if (!fr.isReadOnly()) {
- pathName = fr.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
- rbw.setDefaultPath(pathName);
-
- WizardDialog wd = new WizardDialog(Display.getDefault()
- .getActiveShell(), wizard);
- wd.setTitle(wizard.getWindowTitle());
- if (wd.open() == WizardDialog.OK) {
- (new I18nBuilder()).buildProject(null,
- resource.getProject());
- (new I18nBuilder()).buildResource(resource, null);
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- if (document.get().charAt(start - 1) == '"'
- && document.get().charAt(start) != '"') {
- start--;
- end++;
- }
- if (document.get().charAt(end + 1) == '"'
- && document.get().charAt(end) != '"')
- end++;
+ @Override
+ public String getLabel() {
+ return "Create Resource-Bundle '" + key + "'";
+ }
- document.replace(start, end - start, "\""
- + (packageName.equals("") ? "" : packageName
- + ".") + rbName + "\"");
+ @Override
+ public void run(IMarker marker) {
+ runAction();
+ }
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- Logger.logError(e);
+ protected void runAction() {
+ // First see if this is a "new wizard".
+ IWizardDescriptor descriptor = PlatformUI.getWorkbench()
+ .getNewWizardRegistry().findWizard(newBunldeWizard);
+ // If not check if it is an "import wizard".
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ // Or maybe an export wizard
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ try {
+ // Then if we have a wizard, open it.
+ if (descriptor != null) {
+ IWizard wizard = descriptor.createWizard();
+ if (!(wizard instanceof IResourceBundleWizard)) {
+ return;
+ }
+
+ IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
+ String[] keySilbings = key.split("\\.");
+ String rbName = keySilbings[keySilbings.length - 1];
+ String packageName = "";
+
+ rbw.setBundleId(rbName);
+
+ // Set the default path according to the specified package name
+ String pathName = "";
+ if (keySilbings.length > 1) {
+ try {
+ IJavaProject jp = JavaCore
+ .create(resource.getProject());
+ packageName = key.substring(0, key.lastIndexOf("."));
+
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ IPackageFragment pf = fr
+ .getPackageFragment(packageName);
+ if (pf.exists()) {
+ pathName = pf.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+ }
+
+ try {
+ IJavaProject jp = JavaCore.create(resource.getProject());
+ if (pathName.trim().equals("")) {
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ if (!fr.isReadOnly()) {
+ pathName = fr.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+
+ rbw.setDefaultPath(pathName);
+
+ WizardDialog wd = new WizardDialog(Display.getDefault()
+ .getActiveShell(), wizard);
+ wd.setTitle(wizard.getWindowTitle());
+ if (wd.open() == WizardDialog.OK) {
+ try {
+ resource.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ if (document.get().charAt(start - 1) == '"'
+ && document.get().charAt(start) != '"') {
+ start--;
+ end++;
+ }
+ if (document.get().charAt(end + 1) == '"'
+ && document.get().charAt(end) != '"') {
+ end++;
+ }
+
+ document.replace(start, end - start, "\""
+ + (packageName.equals("") ? "" : packageName
+ + ".") + rbName + "\"");
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+ }
}
- }
+ } catch (CoreException e) {
+ Logger.logError(e);
}
- }
- } catch (CoreException e) {
- Logger.logError(e);
}
- }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
index b41328e0..578d190c 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
@@ -48,6 +48,7 @@
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
@@ -60,753 +61,786 @@
public class ResourceBundleManager {
- public static String defaultLocaleTag = "[default]"; // TODO externalize
+ public static String defaultLocaleTag = "[default]"; // TODO externalize
- /*** CONFIG SECTION ***/
- private static boolean checkResourceExclusionRoot = false;
+ /*** CONFIG SECTION ***/
+ private static boolean checkResourceExclusionRoot = false;
- /*** MEMBER SECTION ***/
- private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>();
+ /*** MEMBER SECTION ***/
+ private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>();
- public static final String RESOURCE_BUNDLE_EXTENSION = ".properties";
+ public static final String RESOURCE_BUNDLE_EXTENSION = ".properties";
- // project-specific
- private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>();
-
- private Map<String, String> bundleNames = new HashMap<String, String>();
-
- private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>();
-
- private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>();
-
- // global
- private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>();
-
- private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>();
-
- private static IResourceChangeListener changelistener;
-
- /* Host project */
- private IProject project = null;
-
- /** State-Serialization Information **/
- private static boolean state_loaded = false;
- private static final String TAG_INTERNATIONALIZATION = "Internationalization";
- private static final String TAG_EXCLUDED = "Excluded";
- private static final String TAG_RES_DESC = "ResourceDescription";
- private static final String TAG_RES_DESC_ABS = "AbsolutePath";
- private static final String TAG_RES_DESC_REL = "RelativePath";
- private static final String TAB_RES_DESC_PRO = "ProjectName";
- private static final String TAB_RES_DESC_BID = "BundleId";
-
- // Define private constructor
- private ResourceBundleManager() {
- }
-
- public static ResourceBundleManager getManager(IProject project) {
- // check if persistant state has been loaded
- if (!state_loaded)
- loadManagerState();
-
- // set host-project
- if (FragmentProjectUtils.isFragment(project))
- project = FragmentProjectUtils.getFragmentHost(project);
-
- ResourceBundleManager manager = rbmanager.get(project);
- if (manager == null) {
- manager = new ResourceBundleManager();
- manager.project = project;
- rbmanager.put(project, manager);
- manager.detectResourceBundles();
-
- }
- return manager;
- }
-
- public Set<Locale> getProvidedLocales(String bundleName) {
- RBManager instance = RBManager.getInstance(project);
-
- Set<Locale> locales = new HashSet<Locale>();
- IMessagesBundleGroup group = instance
- .getMessagesBundleGroup(bundleName);
- if (group == null)
- return locales;
-
- for (IMessagesBundle bundle : group.getMessagesBundles()) {
- locales.add(bundle.getLocale());
- }
- return locales;
- }
-
- public static String getResourceBundleName(IResource res) {
- String name = res.getName();
- String regex = "^(.*?)" //$NON-NLS-1$
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
- + res.getFileExtension() + ")$"; //$NON-NLS-1$
- return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
- }
-
- protected boolean isResourceBundleLoaded(String bundleName) {
- return RBManager.getInstance(project).containsMessagesBundleGroup(
- bundleName);
- }
-
- protected Locale getLocaleByName(String bundleName, String localeID) {
- // Check locale
- Locale locale = null;
- bundleName = bundleNames.get(bundleName);
- localeID = localeID.substring(0,
- localeID.length() - "properties".length() - 1);
- if (localeID.length() == bundleName.length()) {
- // default locale
- return null;
- } else {
- localeID = localeID.substring(bundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
-
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1],
- localeTokens[2]);
- break;
- default:
- locale = null;
- break;
- }
- }
-
- return locale;
- }
-
- protected void unloadResource(String bundleName, IResource resource) {
- // TODO implement more efficient
- unloadResourceBundle(bundleName);
- // loadResourceBundle(bundleName);
- }
-
- public static String getResourceBundleId(IResource resource) {
- String packageFragment = "";
-
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile)
- .getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "")
- + getResourceBundleName(resource);
- }
-
- public void addBundleResource(IResource resource) {
- if (resource.isDerived())
- return;
-
- String bundleName = getResourceBundleId(resource);
- Set<IResource> res;
-
- if (!resources.containsKey(bundleName))
- res = new HashSet<IResource>();
- else
- res = resources.get(bundleName);
-
- res.add(resource);
- resources.put(bundleName, res);
- allBundles.put(bundleName, new HashSet<IResource>(res));
- bundleNames.put(bundleName, getResourceBundleName(resource));
-
- // Fire resource changed event
- ResourceBundleChangedEvent event = new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.ADDED, bundleName,
- resource.getProject());
- this.fireResourceBundleChangedEvent(bundleName, event);
- }
-
- protected void removeAllBundleResources(String bundleName) {
- unloadResourceBundle(bundleName);
- resources.remove(bundleName);
- // allBundles.remove(bundleName);
- listeners.remove(bundleName);
- }
-
- public void unloadResourceBundle(String name) {
- RBManager instance = RBManager.getInstance(project);
- instance.deleteMessagesBundleGroup(name);
- }
-
- public IMessagesBundleGroup getResourceBundle(String name) {
- RBManager instance = RBManager.getInstance(project);
- return instance.getMessagesBundleGroup(name);
- }
-
- public Collection<IResource> getResourceBundles(String bundleName) {
- return resources.get(bundleName);
- }
-
- public List<String> getResourceBundleNames() {
- List<String> returnList = new ArrayList<String>();
-
- Iterator<String> it = resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(it.next());
- }
- return returnList;
- }
-
- public IResource getResourceFile(String file) {
- String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$";
- String bundleName = file.replaceFirst(regex, "$1");
- IResource resource = null;
-
- for (IResource res : resources.get(bundleName)) {
- if (res.getName().equalsIgnoreCase(file)) {
- resource = res;
- break;
- }
- }
-
- return resource;
- }
-
- public void fireResourceBundleChangedEvent(String bundleName,
- ResourceBundleChangedEvent event) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
-
- if (l == null)
- return;
-
- for (IResourceBundleChangedListener listener : l) {
- listener.resourceBundleChanged(event);
- }
- }
-
- public void registerResourceBundleChangeListener(String bundleName,
- IResourceBundleChangedListener listener) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null)
- l = new ArrayList<IResourceBundleChangedListener>();
- l.add(listener);
- listeners.put(bundleName, l);
- }
-
- public void unregisterResourceBundleChangeListener(String bundleName,
- IResourceBundleChangedListener listener) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null)
- return;
- l.remove(listener);
- listeners.put(bundleName, l);
- }
-
- protected void detectResourceBundles() {
- try {
- project.accept(new ResourceBundleDetectionVisitor(getProject()));
-
- IProject[] fragments = FragmentProjectUtils.lookupFragment(project);
- if (fragments != null) {
- for (IProject p : fragments) {
- p.accept(new ResourceBundleDetectionVisitor(getProject()));
- }
- }
- } catch (CoreException e) {
- }
- }
-
- public IProject getProject() {
- return project;
- }
-
- public List<String> getResourceBundleIdentifiers() {
- List<String> returnList = new ArrayList<String>();
-
- // TODO check other resource bundles that are available on the curren
- // class path
- Iterator<String> it = this.resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(it.next());
- }
+ // project-specific
+ private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>();
- return returnList;
- }
-
- public static List<String> getAllResourceBundleNames() {
- List<String> returnList = new ArrayList<String>();
+ private Map<String, String> bundleNames = new HashMap<String, String>();
- for (IProject p : getAllSupportedProjects()) {
- if (!FragmentProjectUtils.isFragment(p)) {
- Iterator<String> it = getManager(p).resources.keySet()
- .iterator();
+ private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>();
+
+ private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>();
+
+ // global
+ private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>();
+
+ private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>();
+
+ private static IResourceChangeListener changelistener;
+
+ /* Host project */
+ private IProject project = null;
+
+ /** State-Serialization Information **/
+ private static boolean state_loaded = false;
+ private static final String TAG_INTERNATIONALIZATION = "Internationalization";
+ private static final String TAG_EXCLUDED = "Excluded";
+ private static final String TAG_RES_DESC = "ResourceDescription";
+ private static final String TAG_RES_DESC_ABS = "AbsolutePath";
+ private static final String TAG_RES_DESC_REL = "RelativePath";
+ private static final String TAB_RES_DESC_PRO = "ProjectName";
+ private static final String TAB_RES_DESC_BID = "BundleId";
+
+ // Define private constructor
+ private ResourceBundleManager() {
+ }
+
+ public static ResourceBundleManager getManager(IProject project) {
+ // check if persistant state has been loaded
+ if (!state_loaded) {
+ loadManagerState();
+ }
+
+ // set host-project
+ if (FragmentProjectUtils.isFragment(project)) {
+ project = FragmentProjectUtils.getFragmentHost(project);
+ }
+
+ ResourceBundleManager manager = rbmanager.get(project);
+ if (manager == null) {
+ manager = new ResourceBundleManager();
+ manager.project = project;
+ rbmanager.put(project, manager);
+ manager.detectResourceBundles();
+
+ }
+ return manager;
+ }
+
+ public Set<Locale> getProvidedLocales(String bundleName) {
+ RBManager instance = RBManager.getInstance(project);
+
+ Set<Locale> locales = new HashSet<Locale>();
+ IMessagesBundleGroup group = instance
+ .getMessagesBundleGroup(bundleName);
+ if (group == null) {
+ return locales;
+ }
+
+ for (IMessagesBundle bundle : group.getMessagesBundles()) {
+ locales.add(bundle.getLocale());
+ }
+ return locales;
+ }
+
+ public static String getResourceBundleName(IResource res) {
+ String name = res.getName();
+ String regex = "^(.*?)" //$NON-NLS-1$
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ + res.getFileExtension() + ")$"; //$NON-NLS-1$
+ return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
+ }
+
+ protected boolean isResourceBundleLoaded(String bundleName) {
+ return RBManager.getInstance(project).containsMessagesBundleGroup(
+ bundleName);
+ }
+
+ protected Locale getLocaleByName(String bundleName, String localeID) {
+ // Check locale
+ Locale locale = null;
+ bundleName = bundleNames.get(bundleName);
+ localeID = localeID.substring(0,
+ localeID.length() - "properties".length() - 1);
+ if (localeID.length() == bundleName.length()) {
+ // default locale
+ return null;
+ } else {
+ localeID = localeID.substring(bundleName.length() + 1);
+ String[] localeTokens = localeID.split("_");
+
+ switch (localeTokens.length) {
+ case 1:
+ locale = new Locale(localeTokens[0]);
+ break;
+ case 2:
+ locale = new Locale(localeTokens[0], localeTokens[1]);
+ break;
+ case 3:
+ locale = new Locale(localeTokens[0], localeTokens[1],
+ localeTokens[2]);
+ break;
+ default:
+ locale = null;
+ break;
+ }
+ }
+
+ return locale;
+ }
+
+ protected void unloadResource(String bundleName, IResource resource) {
+ // TODO implement more efficient
+ unloadResourceBundle(bundleName);
+ // loadResourceBundle(bundleName);
+ }
+
+ public static String getResourceBundleId(IResource resource) {
+ String packageFragment = "";
+
+ IJavaElement propertyFile = JavaCore.create(resource.getParent());
+ if (propertyFile != null && propertyFile instanceof IPackageFragment) {
+ packageFragment = ((IPackageFragment) propertyFile)
+ .getElementName();
+ }
+
+ return (packageFragment.length() > 0 ? packageFragment + "." : "")
+ + getResourceBundleName(resource);
+ }
+
+ public void addBundleResource(IResource resource) {
+ if (resource.isDerived()) {
+ return;
+ }
+
+ String bundleName = getResourceBundleId(resource);
+ Set<IResource> res;
+
+ if (!resources.containsKey(bundleName)) {
+ res = new HashSet<IResource>();
+ } else {
+ res = resources.get(bundleName);
+ }
+
+ res.add(resource);
+ resources.put(bundleName, res);
+ allBundles.put(bundleName, new HashSet<IResource>(res));
+ bundleNames.put(bundleName, getResourceBundleName(resource));
+
+ // Fire resource changed event
+ ResourceBundleChangedEvent event = new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.ADDED, bundleName,
+ resource.getProject());
+ this.fireResourceBundleChangedEvent(bundleName, event);
+ }
+
+ protected void removeAllBundleResources(String bundleName) {
+ unloadResourceBundle(bundleName);
+ resources.remove(bundleName);
+ // allBundles.remove(bundleName);
+ listeners.remove(bundleName);
+ }
+
+ public void unloadResourceBundle(String name) {
+ RBManager instance = RBManager.getInstance(project);
+ instance.deleteMessagesBundleGroup(name);
+ }
+
+ public IMessagesBundleGroup getResourceBundle(String name) {
+ RBManager instance = RBManager.getInstance(project);
+ return instance.getMessagesBundleGroup(name);
+ }
+
+ public Collection<IResource> getResourceBundles(String bundleName) {
+ return resources.get(bundleName);
+ }
+
+ public List<String> getResourceBundleNames() {
+ List<String> returnList = new ArrayList<String>();
+
+ Iterator<String> it = resources.keySet().iterator();
while (it.hasNext()) {
- returnList.add(p.getName() + "/" + it.next());
+ returnList.add(it.next());
}
- }
+ return returnList;
}
- return returnList;
- }
- public static Set<IProject> getAllSupportedProjects() {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
- .getProjects();
- Set<IProject> projs = new HashSet<IProject>();
+ public IResource getResourceFile(String file) {
+ String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$";
+ String bundleName = file.replaceFirst(regex, "$1");
+ IResource resource = null;
+
+ for (IResource res : resources.get(bundleName)) {
+ if (res.getName().equalsIgnoreCase(file)) {
+ resource = res;
+ break;
+ }
+ }
- for (IProject p : projects) {
- if (InternationalizationNature.hasNature(p))
- projs.add(p);
+ return resource;
}
- return projs;
- }
- public String getKeyHoverString(String rbName, String key) {
- try {
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup bundleGroup = instance
- .getMessagesBundleGroup(rbName);
- if (!bundleGroup.containsKey(key))
- return null;
+ public void fireResourceBundleChangedEvent(String bundleName,
+ ResourceBundleChangedEvent event) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+
+ if (l == null) {
+ return;
+ }
+
+ for (IResourceBundleChangedListener listener : l) {
+ listener.resourceBundleChanged(event);
+ }
+ }
+
+ public void registerResourceBundleChangeListener(String bundleName,
+ IResourceBundleChangedListener listener) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ if (l == null) {
+ l = new ArrayList<IResourceBundleChangedListener>();
+ }
+ l.add(listener);
+ listeners.put(bundleName, l);
+ }
+
+ public void unregisterResourceBundleChangeListener(String bundleName,
+ IResourceBundleChangedListener listener) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ if (l == null) {
+ return;
+ }
+ l.remove(listener);
+ listeners.put(bundleName, l);
+ }
+
+ protected void detectResourceBundles() {
+ try {
+ project.accept(new ResourceBundleDetectionVisitor(getProject()));
+
+ IProject[] fragments = FragmentProjectUtils.lookupFragment(project);
+ if (fragments != null) {
+ for (IProject p : fragments) {
+ p.accept(new ResourceBundleDetectionVisitor(getProject()));
+ }
+ }
+ } catch (CoreException e) {
+ }
+ }
+
+ public IProject getProject() {
+ return project;
+ }
+
+ public List<String> getResourceBundleIdentifiers() {
+ List<String> returnList = new ArrayList<String>();
+
+ // TODO check other resource bundles that are available on the curren
+ // class path
+ Iterator<String> it = this.resources.keySet().iterator();
+ while (it.hasNext()) {
+ returnList.add(it.next());
+ }
+
+ return returnList;
+ }
+
+ public static List<String> getAllResourceBundleNames() {
+ List<String> returnList = new ArrayList<String>();
+
+ for (IProject p : getAllSupportedProjects()) {
+ if (!FragmentProjectUtils.isFragment(p)) {
+ Iterator<String> it = getManager(p).resources.keySet()
+ .iterator();
+ while (it.hasNext()) {
+ returnList.add(p.getName() + "/" + it.next());
+ }
+ }
+ }
+ return returnList;
+ }
+
+ public static Set<IProject> getAllSupportedProjects() {
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects();
+ Set<IProject> projs = new HashSet<IProject>();
+
+ for (IProject p : projects) {
+ if (InternationalizationNature.hasNature(p)) {
+ projs.add(p);
+ }
+ }
+ return projs;
+ }
- String hoverText = "<html><head></head><body>";
-
- for (IMessage message : bundleGroup.getMessages(key)) {
- String displayName = message.getLocale() == null ? "Default"
- : message.getLocale().getDisplayName();
- String value = message.getValue();
- hoverText += "<b><i>" + displayName + "</i></b><br/>"
- + value.replace("\n", "<br/>") + "<br/><br/>";
- }
- return hoverText + "</body></html>";
- } catch (Exception e) {
- // silent catch
- return "";
- }
- }
-
- public boolean isKeyBroken(String rbName, String key) {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
- project).getMessagesBundleGroup(rbName);
- if (messagesBundleGroup == null) {
- return true;
- } else {
- return !messagesBundleGroup.containsKey(key);
- }
-
- // if (!resourceBundles.containsKey(rbName))
- // return true;
- // return !this.isResourceExisting(rbName, key);
- }
-
- protected void excludeSingleResource(IResource res) {
- IResourceDescriptor rd = new ResourceDescriptor(res);
- EditorUtils.deleteAuditMarkersForResource(res);
-
- // exclude resource
- excludedResources.add(rd);
- Collection<Object> changedExclusoins = new HashSet<Object>();
- changedExclusoins.add(res);
- fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins));
-
- // Check if the excluded resource represents a resource-bundle
- if (RBFileUtils.isResourceBundleFile(res)) {
- String bundleName = getResourceBundleId(res);
- Set<IResource> resSet = resources.remove(bundleName);
- if (resSet != null) {
- resSet.remove(res);
-
- if (!resSet.isEmpty()) {
- resources.put(bundleName, resSet);
- unloadResource(bundleName, res);
+ public String getKeyHoverString(String rbName, String key) {
+ try {
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup bundleGroup = instance
+ .getMessagesBundleGroup(rbName);
+ if (!bundleGroup.containsKey(key)) {
+ return null;
+ }
+
+ String hoverText = "<html><head></head><body>";
+
+ for (IMessage message : bundleGroup.getMessages(key)) {
+ String displayName = message.getLocale() == null ? "Default"
+ : message.getLocale().getDisplayName();
+ String value = message.getValue();
+ hoverText += "<b><i>" + displayName + "</i></b><br/>"
+ + value.replace("\n", "<br/>") + "<br/><br/>";
+ }
+ return hoverText + "</body></html>";
+ } catch (Exception e) {
+ // silent catch
+ return "";
+ }
+ }
+
+ public boolean isKeyBroken(String rbName, String key) {
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ project).getMessagesBundleGroup(rbName);
+ if (messagesBundleGroup == null) {
+ return true;
} else {
- rd.setBundleId(bundleName);
- unloadResourceBundle(bundleName);
- (new I18nBuilder()).buildProject(null, res.getProject());
- }
-
- fireResourceBundleChangedEvent(getResourceBundleId(res),
- new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.EXCLUDED,
- bundleName, res.getProject()));
- }
- }
- }
-
- public void excludeResource(IResource res, IProgressMonitor monitor) {
- try {
- if (monitor == null)
- monitor = new NullProgressMonitor();
-
- final List<IResource> resourceSubTree = new ArrayList<IResource>();
- res.accept(new IResourceVisitor() {
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- Logger.logInfo("Excluding resource '"
- + resource.getFullPath().toOSString() + "'");
- resourceSubTree.add(resource);
- return true;
- }
-
- });
-
- // Iterate previously retrieved resource and exclude them from
- // Internationalization
- monitor.beginTask(
- "Exclude resources from Internationalization context",
- resourceSubTree.size());
- try {
- for (IResource resource : resourceSubTree) {
- excludeSingleResource(resource);
- EditorUtils.deleteAuditMarkersForResource(resource);
- monitor.worked(1);
- }
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- monitor.done();
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public void includeResource(IResource res, IProgressMonitor monitor) {
- if (monitor == null)
- monitor = new NullProgressMonitor();
-
- final Collection<Object> changedResources = new HashSet<Object>();
- IResource resource = res;
-
- if (!excludedResources.contains(new ResourceDescriptor(res))) {
- while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) {
- if (excludedResources
- .contains(new ResourceDescriptor(resource))) {
- excludeResource(resource, monitor);
- changedResources.add(resource);
- break;
- } else
- resource = resource.getParent();
- }
- }
-
- try {
- res.accept(new IResourceVisitor() {
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- changedResources.add(resource);
- return true;
- }
- });
-
- monitor.beginTask("Add resources to Internationalization context",
- changedResources.size());
- try {
- for (Object r : changedResources) {
- excludedResources.remove(new ResourceDescriptor(
- (IResource) r));
- monitor.worked(1);
- }
-
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- monitor.done();
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
-
- (new I18nBuilder()).buildResource(res, null);
-
- // Check if the included resource represents a resource-bundle
- if (RBFileUtils.isResourceBundleFile(res)) {
- String bundleName = getResourceBundleId(res);
- boolean newRB = resources.containsKey(bundleName);
-
- this.addBundleResource(res);
- this.unloadResourceBundle(bundleName);
- // this.loadResourceBundle(bundleName);
-
- if (newRB)
- (new I18nBuilder()).buildProject(null, res.getProject());
- fireResourceBundleChangedEvent(getResourceBundleId(res),
- new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.INCLUDED, bundleName,
- res.getProject()));
- }
-
- fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources));
- }
-
- protected void fireResourceExclusionEvent(ResourceExclusionEvent event) {
- for (IResourceExclusionListener listener : exclusionListeners)
- listener.exclusionChanged(event);
- }
-
- public static boolean isResourceExcluded(IResource res) {
- IResource resource = res;
-
- if (!state_loaded)
- loadManagerState();
-
- boolean isExcluded = false;
-
- do {
- if (excludedResources.contains(new ResourceDescriptor(resource))) {
- if (RBFileUtils.isResourceBundleFile(resource)) {
- Set<IResource> resources = allBundles
- .remove(getResourceBundleName(resource));
- if (resources == null)
- resources = new HashSet<IResource>();
- resources.add(resource);
- allBundles.put(getResourceBundleName(resource), resources);
- }
-
- isExcluded = true;
- break;
- }
- resource = resource.getParent();
- } while (resource != null
- && !(resource instanceof IProject || resource instanceof IWorkspaceRoot)
- && checkResourceExclusionRoot);
-
- return isExcluded; // excludedResources.contains(new
- // ResourceDescriptor(res));
- }
-
- public IFile getRandomFile(String bundleName) {
- try {
- IResource res = (resources.get(bundleName)).iterator().next();
- return res.getProject().getFile(res.getProjectRelativePath());
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private static void loadManagerState() {
- excludedResources = new HashSet<IResourceDescriptor>();
- FileReader reader = null;
- try {
- reader = new FileReader(FileUtils.getRBManagerStateFile());
- loadManagerState(XMLMemento.createReadRoot(reader));
- state_loaded = true;
- } catch (Exception e) {
- // do nothing
- }
-
- changelistener = new RBChangeListner();
- ResourcesPlugin.getWorkspace().addResourceChangeListener(
- changelistener,
- IResourceChangeEvent.PRE_DELETE
- | IResourceChangeEvent.POST_CHANGE);
- }
-
- private static void loadManagerState(XMLMemento memento) {
- IMemento excludedChild = memento.getChild(TAG_EXCLUDED);
- for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) {
- IResourceDescriptor descriptor = new ResourceDescriptor();
- descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS));
- descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL));
- descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO));
- descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID));
- excludedResources.add(descriptor);
- }
- }
-
- public static void saveManagerState() {
- if (excludedResources == null)
- return;
- XMLMemento memento = XMLMemento
- .createWriteRoot(TAG_INTERNATIONALIZATION);
- IMemento exclChild = memento.createChild(TAG_EXCLUDED);
-
- Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
- while (itExcl.hasNext()) {
- IResourceDescriptor desc = itExcl.next();
- IMemento resDesc = exclChild.createChild(TAG_RES_DESC);
- resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName());
- resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath());
- resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath());
- resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId());
- }
- FileWriter writer = null;
- try {
- writer = new FileWriter(FileUtils.getRBManagerStateFile());
- memento.save(writer);
- } catch (Exception e) {
- // do nothing
- } finally {
- try {
- if (writer != null)
- writer.close();
- } catch (Exception e) {
- // do nothing
- }
- }
- }
-
- @Deprecated
- protected static boolean isResourceExcluded(IProject project, String bname) {
- Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
- while (itExcl.hasNext()) {
- IResourceDescriptor rd = itExcl.next();
- if (project.getName().equals(rd.getProjectName())
- && bname.equals(rd.getBundleId()))
- return true;
- }
- return false;
- }
-
- public static ResourceBundleManager getManager(String projectName) {
- for (IProject p : getAllSupportedProjects()) {
- if (p.getName().equalsIgnoreCase(projectName)) {
- // check if the projectName is a fragment and return the manager
- // for the host
- if (FragmentProjectUtils.isFragment(p))
- return getManager(FragmentProjectUtils.getFragmentHost(p));
- else
- return getManager(p);
- }
- }
- return null;
- }
-
- public IFile getResourceBundleFile(String resourceBundle, Locale l) {
- IFile res = null;
- Set<IResource> resSet = resources.get(resourceBundle);
-
- if (resSet != null) {
- for (IResource resource : resSet) {
- Locale refLoc = getLocaleByName(resourceBundle,
- resource.getName());
- if (refLoc == null
- && l == null
- || (refLoc != null && refLoc.equals(l) || l != null
- && l.equals(refLoc))) {
- res = resource.getProject().getFile(
- resource.getProjectRelativePath());
- break;
- }
- }
- }
-
- return res;
- }
-
- public Set<IResource> getAllResourceBundleResources(String resourceBundle) {
- return allBundles.get(resourceBundle);
- }
-
- public void registerResourceExclusionListener(
- IResourceExclusionListener listener) {
- exclusionListeners.add(listener);
- }
-
- public void unregisterResourceExclusionListener(
- IResourceExclusionListener listener) {
- exclusionListeners.remove(listener);
- }
-
- public boolean isResourceExclusionListenerRegistered(
- IResourceExclusionListener listener) {
- return exclusionListeners.contains(listener);
- }
-
- public static void unregisterResourceExclusionListenerFromAllManagers(
- IResourceExclusionListener excludedResource) {
- for (ResourceBundleManager mgr : rbmanager.values()) {
- mgr.unregisterResourceExclusionListener(excludedResource);
- }
- }
-
- public void addResourceBundleEntry(String resourceBundleId, String key,
- Locale locale, String message) throws ResourceBundleException {
-
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup bundleGroup = instance
- .getMessagesBundleGroup(resourceBundleId);
- IMessage entry = bundleGroup.getMessage(key, locale);
+ return !messagesBundleGroup.containsKey(key);
+ }
+
+ // if (!resourceBundles.containsKey(rbName))
+ // return true;
+ // return !this.isResourceExisting(rbName, key);
+ }
+
+ protected void excludeSingleResource(IResource res) {
+ IResourceDescriptor rd = new ResourceDescriptor(res);
+ EditorUtils.deleteAuditMarkersForResource(res);
+
+ // exclude resource
+ excludedResources.add(rd);
+ Collection<Object> changedExclusoins = new HashSet<Object>();
+ changedExclusoins.add(res);
+ fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins));
+
+ // Check if the excluded resource represents a resource-bundle
+ if (RBFileUtils.isResourceBundleFile(res)) {
+ String bundleName = getResourceBundleId(res);
+ Set<IResource> resSet = resources.remove(bundleName);
+ if (resSet != null) {
+ resSet.remove(res);
+
+ if (!resSet.isEmpty()) {
+ resources.put(bundleName, resSet);
+ unloadResource(bundleName, res);
+ } else {
+ rd.setBundleId(bundleName);
+ unloadResourceBundle(bundleName);
+ try {
+ res.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ fireResourceBundleChangedEvent(getResourceBundleId(res),
+ new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.EXCLUDED,
+ bundleName, res.getProject()));
+ }
+ }
+ }
+
+ public void excludeResource(IResource res, IProgressMonitor monitor) {
+ try {
+ if (monitor == null) {
+ monitor = new NullProgressMonitor();
+ }
+
+ final List<IResource> resourceSubTree = new ArrayList<IResource>();
+ res.accept(new IResourceVisitor() {
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ Logger.logInfo("Excluding resource '"
+ + resource.getFullPath().toOSString() + "'");
+ resourceSubTree.add(resource);
+ return true;
+ }
+
+ });
+
+ // Iterate previously retrieved resource and exclude them from
+ // Internationalization
+ monitor.beginTask(
+ "Exclude resources from Internationalization context",
+ resourceSubTree.size());
+ try {
+ for (IResource resource : resourceSubTree) {
+ excludeSingleResource(resource);
+ EditorUtils.deleteAuditMarkersForResource(resource);
+ monitor.worked(1);
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ monitor.done();
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public void includeResource(IResource res, IProgressMonitor monitor) {
+ if (monitor == null) {
+ monitor = new NullProgressMonitor();
+ }
+
+ final Collection<Object> changedResources = new HashSet<Object>();
+ IResource resource = res;
+
+ if (!excludedResources.contains(new ResourceDescriptor(res))) {
+ while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) {
+ if (excludedResources
+ .contains(new ResourceDescriptor(resource))) {
+ excludeResource(resource, monitor);
+ changedResources.add(resource);
+ break;
+ } else {
+ resource = resource.getParent();
+ }
+ }
+ }
- if (entry == null) {
- DirtyHack.setFireEnabled(false);
+ try {
+ res.accept(new IResourceVisitor() {
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ changedResources.add(resource);
+ return true;
+ }
+ });
+
+ monitor.beginTask("Add resources to Internationalization context",
+ changedResources.size());
+ try {
+ for (Object r : changedResources) {
+ excludedResources.remove(new ResourceDescriptor(
+ (IResource) r));
+ monitor.worked(1);
+ }
+
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ monitor.done();
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+
+ (new I18nBuilder()).buildResource(res, null);
- IMessagesBundle messagesBundle = bundleGroup
- .getMessagesBundle(locale);
- IMessage m = MessageFactory.createMessage(key, locale);
- m.setText(message);
- messagesBundle.addMessage(m);
+ // Check if the included resource represents a resource-bundle
+ if (RBFileUtils.isResourceBundleFile(res)) {
+ String bundleName = getResourceBundleId(res);
+ boolean newRB = resources.containsKey(bundleName);
- instance.writeToFile(messagesBundle);
+ this.addBundleResource(res);
+ this.unloadResourceBundle(bundleName);
+ // this.loadResourceBundle(bundleName);
- DirtyHack.setFireEnabled(true);
+ if (newRB) {
+ (new I18nBuilder()).buildProject(null, res.getProject());
+ }
+ fireResourceBundleChangedEvent(getResourceBundleId(res),
+ new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.INCLUDED, bundleName,
+ res.getProject()));
+ }
- // notify the PropertyKeySelectionTree
- instance.fireEditorChanged();
+ fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources));
}
- }
- public void saveResourceBundle(String resourceBundleId,
- IMessagesBundleGroup newBundleGroup) throws ResourceBundleException {
+ protected void fireResourceExclusionEvent(ResourceExclusionEvent event) {
+ for (IResourceExclusionListener listener : exclusionListeners) {
+ listener.exclusionChanged(event);
+ }
+ }
- // RBManager.getInstance().
- }
+ public static boolean isResourceExcluded(IResource res) {
+ IResource resource = res;
- public void removeResourceBundleEntry(String resourceBundleId,
- List<String> keys) throws ResourceBundleException {
+ if (!state_loaded) {
+ loadManagerState();
+ }
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup messagesBundleGroup = instance
- .getMessagesBundleGroup(resourceBundleId);
+ boolean isExcluded = false;
+
+ do {
+ if (excludedResources.contains(new ResourceDescriptor(resource))) {
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ Set<IResource> resources = allBundles
+ .remove(getResourceBundleName(resource));
+ if (resources == null) {
+ resources = new HashSet<IResource>();
+ }
+ resources.add(resource);
+ allBundles.put(getResourceBundleName(resource), resources);
+ }
+
+ isExcluded = true;
+ break;
+ }
+ resource = resource.getParent();
+ } while (resource != null
+ && !(resource instanceof IProject || resource instanceof IWorkspaceRoot)
+ && checkResourceExclusionRoot);
+
+ return isExcluded; // excludedResources.contains(new
+ // ResourceDescriptor(res));
+ }
- DirtyHack.setFireEnabled(false);
+ public IFile getRandomFile(String bundleName) {
+ try {
+ IResource res = (resources.get(bundleName)).iterator().next();
+ return res.getProject().getFile(res.getProjectRelativePath());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
- for (String key : keys) {
- messagesBundleGroup.removeMessages(key);
+ private static void loadManagerState() {
+ excludedResources = new HashSet<IResourceDescriptor>();
+ FileReader reader = null;
+ try {
+ reader = new FileReader(FileUtils.getRBManagerStateFile());
+ loadManagerState(XMLMemento.createReadRoot(reader));
+ state_loaded = true;
+ } catch (Exception e) {
+ // do nothing
+ }
+
+ changelistener = new RBChangeListner();
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(
+ changelistener,
+ IResourceChangeEvent.PRE_DELETE
+ | IResourceChangeEvent.POST_CHANGE);
}
- instance.writeToFile(messagesBundleGroup);
+ private static void loadManagerState(XMLMemento memento) {
+ IMemento excludedChild = memento.getChild(TAG_EXCLUDED);
+ for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) {
+ IResourceDescriptor descriptor = new ResourceDescriptor();
+ descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS));
+ descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL));
+ descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO));
+ descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID));
+ excludedResources.add(descriptor);
+ }
+ }
- DirtyHack.setFireEnabled(true);
+ public static void saveManagerState() {
+ if (excludedResources == null) {
+ return;
+ }
+ XMLMemento memento = XMLMemento
+ .createWriteRoot(TAG_INTERNATIONALIZATION);
+ IMemento exclChild = memento.createChild(TAG_EXCLUDED);
+
+ Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
+ while (itExcl.hasNext()) {
+ IResourceDescriptor desc = itExcl.next();
+ IMemento resDesc = exclChild.createChild(TAG_RES_DESC);
+ resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName());
+ resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath());
+ resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath());
+ resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId());
+ }
+ FileWriter writer = null;
+ try {
+ writer = new FileWriter(FileUtils.getRBManagerStateFile());
+ memento.save(writer);
+ } catch (Exception e) {
+ // do nothing
+ } finally {
+ try {
+ if (writer != null) {
+ writer.close();
+ }
+ } catch (Exception e) {
+ // do nothing
+ }
+ }
+ }
- // notify the PropertyKeySelectionTree
- instance.fireEditorChanged();
- }
+ @Deprecated
+ protected static boolean isResourceExcluded(IProject project, String bname) {
+ Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
+ while (itExcl.hasNext()) {
+ IResourceDescriptor rd = itExcl.next();
+ if (project.getName().equals(rd.getProjectName())
+ && bname.equals(rd.getBundleId())) {
+ return true;
+ }
+ }
+ return false;
+ }
- public boolean isResourceExisting(String bundleId, String key) {
- boolean keyExists = false;
- IMessagesBundleGroup bGroup = getResourceBundle(bundleId);
+ public static ResourceBundleManager getManager(String projectName) {
+ for (IProject p : getAllSupportedProjects()) {
+ if (p.getName().equalsIgnoreCase(projectName)) {
+ // check if the projectName is a fragment and return the manager
+ // for the host
+ if (FragmentProjectUtils.isFragment(p)) {
+ return getManager(FragmentProjectUtils.getFragmentHost(p));
+ } else {
+ return getManager(p);
+ }
+ }
+ }
+ return null;
+ }
+
+ public IFile getResourceBundleFile(String resourceBundle, Locale l) {
+ IFile res = null;
+ Set<IResource> resSet = resources.get(resourceBundle);
+
+ if (resSet != null) {
+ for (IResource resource : resSet) {
+ Locale refLoc = getLocaleByName(resourceBundle,
+ resource.getName());
+ if (refLoc == null
+ && l == null
+ || (refLoc != null && refLoc.equals(l) || l != null
+ && l.equals(refLoc))) {
+ res = resource.getProject().getFile(
+ resource.getProjectRelativePath());
+ break;
+ }
+ }
+ }
- if (bGroup != null) {
- keyExists = bGroup.isKey(key);
+ return res;
}
- return keyExists;
- }
+ public Set<IResource> getAllResourceBundleResources(String resourceBundle) {
+ return allBundles.get(resourceBundle);
+ }
- public static void refreshResource(IResource resource) {
- (new I18nBuilder()).buildProject(null, resource.getProject());
- (new I18nBuilder()).buildResource(resource, null);
- }
+ public void registerResourceExclusionListener(
+ IResourceExclusionListener listener) {
+ exclusionListeners.add(listener);
+ }
- public Set<Locale> getProjectProvidedLocales() {
- Set<Locale> locales = new HashSet<Locale>();
+ public void unregisterResourceExclusionListener(
+ IResourceExclusionListener listener) {
+ exclusionListeners.remove(listener);
+ }
+
+ public boolean isResourceExclusionListenerRegistered(
+ IResourceExclusionListener listener) {
+ return exclusionListeners.contains(listener);
+ }
+
+ public static void unregisterResourceExclusionListenerFromAllManagers(
+ IResourceExclusionListener excludedResource) {
+ for (ResourceBundleManager mgr : rbmanager.values()) {
+ mgr.unregisterResourceExclusionListener(excludedResource);
+ }
+ }
+
+ public void addResourceBundleEntry(String resourceBundleId, String key,
+ Locale locale, String message) throws ResourceBundleException {
+
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup bundleGroup = instance
+ .getMessagesBundleGroup(resourceBundleId);
+ IMessage entry = bundleGroup.getMessage(key, locale);
+
+ if (entry == null) {
+ DirtyHack.setFireEnabled(false);
+
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(locale);
+ IMessage m = MessageFactory.createMessage(key, locale);
+ m.setText(message);
+ messagesBundle.addMessage(m);
+
+ instance.writeToFile(messagesBundle);
+
+ DirtyHack.setFireEnabled(true);
+
+ // notify the PropertyKeySelectionTree
+ instance.fireEditorChanged();
+ }
+ }
+
+ public void saveResourceBundle(String resourceBundleId,
+ IMessagesBundleGroup newBundleGroup) throws ResourceBundleException {
+
+ // RBManager.getInstance().
+ }
+
+ public void removeResourceBundleEntry(String resourceBundleId,
+ List<String> keys) throws ResourceBundleException {
+
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup messagesBundleGroup = instance
+ .getMessagesBundleGroup(resourceBundleId);
+
+ DirtyHack.setFireEnabled(false);
+
+ for (String key : keys) {
+ messagesBundleGroup.removeMessages(key);
+ }
+
+ instance.writeToFile(messagesBundleGroup);
+
+ DirtyHack.setFireEnabled(true);
+
+ // notify the PropertyKeySelectionTree
+ instance.fireEditorChanged();
+ }
+
+ public boolean isResourceExisting(String bundleId, String key) {
+ boolean keyExists = false;
+ IMessagesBundleGroup bGroup = getResourceBundle(bundleId);
+
+ if (bGroup != null) {
+ keyExists = bGroup.isKey(key);
+ }
+
+ return keyExists;
+ }
+
+ public static void refreshResource(IResource resource) {
+ try {
+ resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
- for (String bundleId : getResourceBundleNames()) {
- Set<Locale> rb_l = getProvidedLocales(bundleId);
- if (!rb_l.isEmpty()) {
- Object[] bundlelocales = rb_l.toArray();
- for (Object l : bundlelocales) {
- /* TODO check if useful to add the default */
- if (!locales.contains(l))
- locales.add((Locale) l);
+ public Set<Locale> getProjectProvidedLocales() {
+ Set<Locale> locales = new HashSet<Locale>();
+
+ for (String bundleId : getResourceBundleNames()) {
+ Set<Locale> rb_l = getProvidedLocales(bundleId);
+ if (!rb_l.isEmpty()) {
+ Object[] bundlelocales = rb_l.toArray();
+ for (Object l : bundlelocales) {
+ /* TODO check if useful to add the default */
+ if (!locales.contains(l)) {
+ locales.add((Locale) l);
+ }
+ }
+ }
}
- }
+ return locales;
}
- return locales;
- }
}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
index 7f39b6b7..14bbbc7d 100644
--- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
@@ -7,6 +7,7 @@
******************************************************************************/
package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+import org.eclipse.babel.tapiji.tools.core.Logger;
import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
@@ -16,6 +17,7 @@
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.filebuffers.LocationKind;
import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IJavaProject;
@@ -136,9 +138,13 @@ protected void runAction() {
wd.setTitle(wizard.getWindowTitle());
if (wd.open() == WizardDialog.OK) {
- (new I18nBuilder()).buildProject(null,
- resource.getProject());
- (new I18nBuilder()).buildResource(resource, null);
+ try {
+ resource.getProject().build(
+ IncrementalProjectBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
ITextFileBufferManager bufferManager = FileBuffers
.getTextFileBufferManager();
|
9ccbb766bd98a4958a38ddc840e00b7dfa6230d6
|
hbase
|
HBASE-8033 Break TestRestoreSnapshotFromClient- into TestRestoreSnapshotFromClient and TestCloneSnapshotFromClient (Ted Yu)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1454186 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestCloneSnapshotFromClient.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestCloneSnapshotFromClient.java
new file mode 100644
index 000000000000..1449865262a8
--- /dev/null
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestCloneSnapshotFromClient.java
@@ -0,0 +1,269 @@
+/**
+ * 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.client;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hbase.HBaseTestingUtility;
+import org.apache.hadoop.hbase.HColumnDescriptor;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.LargeTests;
+import org.apache.hadoop.hbase.exceptions.SnapshotDoesNotExistException;
+import org.apache.hadoop.hbase.master.MasterFileSystem;
+import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.MD5Hash;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Test clone snapshots from the client
+ */
+@Category(LargeTests.class)
+public class TestCloneSnapshotFromClient {
+ final Log LOG = LogFactory.getLog(getClass());
+
+ private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
+
+ private final byte[] FAMILY = Bytes.toBytes("cf");
+
+ private byte[] emptySnapshot;
+ private byte[] snapshotName0;
+ private byte[] snapshotName1;
+ private byte[] snapshotName2;
+ private int snapshot0Rows;
+ private int snapshot1Rows;
+ private byte[] tableName;
+ private HBaseAdmin admin;
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ TEST_UTIL.getConfiguration().setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
+ TEST_UTIL.getConfiguration().setBoolean("hbase.online.schema.update.enable", true);
+ TEST_UTIL.getConfiguration().setInt("hbase.hstore.compactionThreshold", 10);
+ TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100);
+ TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250);
+ TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6);
+ TEST_UTIL.getConfiguration().setBoolean(
+ "hbase.master.enabletable.roundrobin", true);
+ TEST_UTIL.startMiniCluster(3);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ TEST_UTIL.shutdownMiniCluster();
+ }
+
+ /**
+ * Initialize the tests with a table filled with some data
+ * and two snapshots (snapshotName0, snapshotName1) of different states.
+ * The tableName, snapshotNames and the number of rows in the snapshot are initialized.
+ */
+ @Before
+ public void setup() throws Exception {
+ this.admin = TEST_UTIL.getHBaseAdmin();
+
+ long tid = System.currentTimeMillis();
+ tableName = Bytes.toBytes("testtb-" + tid);
+ emptySnapshot = Bytes.toBytes("emptySnaptb-" + tid);
+ snapshotName0 = Bytes.toBytes("snaptb0-" + tid);
+ snapshotName1 = Bytes.toBytes("snaptb1-" + tid);
+ snapshotName2 = Bytes.toBytes("snaptb2-" + tid);
+
+ // create Table and disable it
+ createTable(tableName, FAMILY);
+ admin.disableTable(tableName);
+
+ // take an empty snapshot
+ admin.snapshot(emptySnapshot, tableName);
+
+ HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName);
+ try {
+ // enable table and insert data
+ admin.enableTable(tableName);
+ loadData(table, 500, FAMILY);
+ snapshot0Rows = TEST_UTIL.countRows(table);
+ admin.disableTable(tableName);
+
+ // take a snapshot
+ admin.snapshot(snapshotName0, tableName);
+
+ // enable table and insert more data
+ admin.enableTable(tableName);
+ loadData(table, 500, FAMILY);
+ snapshot1Rows = TEST_UTIL.countRows(table);
+ admin.disableTable(tableName);
+
+ // take a snapshot of the updated table
+ admin.snapshot(snapshotName1, tableName);
+
+ // re-enable table
+ admin.enableTable(tableName);
+ } finally {
+ table.close();
+ }
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ if (admin.tableExists(tableName)) {
+ TEST_UTIL.deleteTable(tableName);
+ }
+ admin.deleteSnapshot(snapshotName0);
+ admin.deleteSnapshot(snapshotName1);
+
+ // Ensure the archiver to be empty
+ MasterFileSystem mfs = TEST_UTIL.getMiniHBaseCluster().getMaster().getMasterFileSystem();
+ mfs.getFileSystem().delete(
+ new Path(mfs.getRootDir(), HConstants.HFILE_ARCHIVE_DIRECTORY), true);
+ }
+
+ @Test(expected=SnapshotDoesNotExistException.class)
+ public void testCloneNonExistentSnapshot() throws IOException, InterruptedException {
+ String snapshotName = "random-snapshot-" + System.currentTimeMillis();
+ String tableName = "random-table-" + System.currentTimeMillis();
+ admin.cloneSnapshot(snapshotName, tableName);
+ }
+
+ @Test
+ public void testCloneSnapshot() throws IOException, InterruptedException {
+ byte[] clonedTableName = Bytes.toBytes("clonedtb-" + System.currentTimeMillis());
+ testCloneSnapshot(clonedTableName, snapshotName0, snapshot0Rows);
+ testCloneSnapshot(clonedTableName, snapshotName1, snapshot1Rows);
+ testCloneSnapshot(clonedTableName, emptySnapshot, 0);
+ }
+
+ private void testCloneSnapshot(final byte[] tableName, final byte[] snapshotName,
+ int snapshotRows) throws IOException, InterruptedException {
+ // create a new table from snapshot
+ admin.cloneSnapshot(snapshotName, tableName);
+ verifyRowCount(tableName, snapshotRows);
+
+ admin.disableTable(tableName);
+ admin.deleteTable(tableName);
+ }
+
+ /**
+ * Verify that tables created from the snapshot are still alive after source table deletion.
+ */
+ @Test
+ public void testCloneLinksAfterDelete() throws IOException, InterruptedException {
+ // Clone a table from the first snapshot
+ byte[] clonedTableName = Bytes.toBytes("clonedtb1-" + System.currentTimeMillis());
+ admin.cloneSnapshot(snapshotName0, clonedTableName);
+ verifyRowCount(clonedTableName, snapshot0Rows);
+
+ // Take a snapshot of this cloned table.
+ admin.disableTable(clonedTableName);
+ admin.snapshot(snapshotName2, clonedTableName);
+
+ // Clone the snapshot of the cloned table
+ byte[] clonedTableName2 = Bytes.toBytes("clonedtb2-" + System.currentTimeMillis());
+ admin.cloneSnapshot(snapshotName2, clonedTableName2);
+ verifyRowCount(clonedTableName2, snapshot0Rows);
+ admin.disableTable(clonedTableName2);
+
+ // Remove the original table
+ admin.disableTable(tableName);
+ admin.deleteTable(tableName);
+ waitCleanerRun();
+
+ // Verify the first cloned table
+ admin.enableTable(clonedTableName);
+ verifyRowCount(clonedTableName, snapshot0Rows);
+
+ // Verify the second cloned table
+ admin.enableTable(clonedTableName2);
+ verifyRowCount(clonedTableName2, snapshot0Rows);
+ admin.disableTable(clonedTableName2);
+
+ // Delete the first cloned table
+ admin.disableTable(clonedTableName);
+ admin.deleteTable(clonedTableName);
+ waitCleanerRun();
+
+ // Verify the second cloned table
+ admin.enableTable(clonedTableName2);
+ verifyRowCount(clonedTableName2, snapshot0Rows);
+
+ // Clone a new table from cloned
+ byte[] clonedTableName3 = Bytes.toBytes("clonedtb3-" + System.currentTimeMillis());
+ admin.cloneSnapshot(snapshotName2, clonedTableName3);
+ verifyRowCount(clonedTableName3, snapshot0Rows);
+
+ // Delete the cloned tables
+ admin.disableTable(clonedTableName2);
+ admin.deleteTable(clonedTableName2);
+ admin.disableTable(clonedTableName3);
+ admin.deleteTable(clonedTableName3);
+ admin.deleteSnapshot(snapshotName2);
+ }
+
+ // ==========================================================================
+ // Helpers
+ // ==========================================================================
+ private void createTable(final byte[] tableName, final byte[]... families) throws IOException {
+ HTableDescriptor htd = new HTableDescriptor(tableName);
+ for (byte[] family: families) {
+ HColumnDescriptor hcd = new HColumnDescriptor(family);
+ htd.addFamily(hcd);
+ }
+ byte[][] splitKeys = new byte[16][];
+ byte[] hex = Bytes.toBytes("0123456789abcdef");
+ for (int i = 0; i < 16; ++i) {
+ splitKeys[i] = new byte[] { hex[i] };
+ }
+ admin.createTable(htd, splitKeys);
+ }
+
+ public void loadData(final HTable table, int rows, byte[]... families) throws IOException {
+ byte[] qualifier = Bytes.toBytes("q");
+ table.setAutoFlush(false);
+ while (rows-- > 0) {
+ byte[] value = Bytes.add(Bytes.toBytes(System.currentTimeMillis()), Bytes.toBytes(rows));
+ byte[] key = Bytes.toBytes(MD5Hash.getMD5AsHex(value));
+ Put put = new Put(key);
+ put.setWriteToWAL(false);
+ for (byte[] family: families) {
+ put.add(family, qualifier, value);
+ }
+ table.put(put);
+ }
+ table.flushCommits();
+ }
+
+ private void waitCleanerRun() throws InterruptedException {
+ TEST_UTIL.getMiniHBaseCluster().getMaster().getHFileCleaner().choreForTesting();
+ }
+
+ private void verifyRowCount(final byte[] tableName, long expectedRows) throws IOException {
+ HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName);
+ assertEquals(expectedRows, TEST_UTIL.countRows(table));
+ table.close();
+ }
+}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestRestoreSnapshotFromClient.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestRestoreSnapshotFromClient.java
index ab1ecd8ec07f..0cb764aeee26 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestRestoreSnapshotFromClient.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestRestoreSnapshotFromClient.java
@@ -17,9 +17,7 @@
*/
package org.apache.hadoop.hbase.client;
-import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
@@ -30,22 +28,25 @@
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseTestingUtility;
+import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
-import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.LargeTests;
+import org.apache.hadoop.hbase.exceptions.NoSuchColumnFamilyException;
import org.apache.hadoop.hbase.master.MasterFileSystem;
import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
-import org.apache.hadoop.hbase.exceptions.NoSuchColumnFamilyException;
-import org.apache.hadoop.hbase.exceptions.SnapshotDoesNotExistException;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.hbase.util.MD5Hash;
-import org.junit.*;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
- * Test clone/restore snapshots from the client
+ * Test restore snapshots from the client
*/
@Category(LargeTests.class)
public class TestRestoreSnapshotFromClient {
@@ -225,31 +226,6 @@ public void testRestoreSchemaChange() throws IOException {
table.close();
}
- @Test(expected=SnapshotDoesNotExistException.class)
- public void testCloneNonExistentSnapshot() throws IOException, InterruptedException {
- String snapshotName = "random-snapshot-" + System.currentTimeMillis();
- String tableName = "random-table-" + System.currentTimeMillis();
- admin.cloneSnapshot(snapshotName, tableName);
- }
-
- @Test
- public void testCloneSnapshot() throws IOException, InterruptedException {
- byte[] clonedTableName = Bytes.toBytes("clonedtb-" + System.currentTimeMillis());
- testCloneSnapshot(clonedTableName, snapshotName0, snapshot0Rows);
- testCloneSnapshot(clonedTableName, snapshotName1, snapshot1Rows);
- testCloneSnapshot(clonedTableName, emptySnapshot, 0);
- }
-
- private void testCloneSnapshot(final byte[] tableName, final byte[] snapshotName,
- int snapshotRows) throws IOException, InterruptedException {
- // create a new table from snapshot
- admin.cloneSnapshot(snapshotName, tableName);
- verifyRowCount(tableName, snapshotRows);
-
- admin.disableTable(tableName);
- admin.deleteTable(tableName);
- }
-
@Test
public void testRestoreSnapshotOfCloned() throws IOException, InterruptedException {
byte[] clonedTableName = Bytes.toBytes("clonedtb-" + System.currentTimeMillis());
@@ -266,62 +242,6 @@ public void testRestoreSnapshotOfCloned() throws IOException, InterruptedExcepti
admin.deleteTable(clonedTableName);
}
- /**
- * Verify that tables created from the snapshot are still alive after source table deletion.
- */
- @Test
- public void testCloneLinksAfterDelete() throws IOException, InterruptedException {
- // Clone a table from the first snapshot
- byte[] clonedTableName = Bytes.toBytes("clonedtb1-" + System.currentTimeMillis());
- admin.cloneSnapshot(snapshotName0, clonedTableName);
- verifyRowCount(clonedTableName, snapshot0Rows);
-
- // Take a snapshot of this cloned table.
- admin.disableTable(clonedTableName);
- admin.snapshot(snapshotName2, clonedTableName);
-
- // Clone the snapshot of the cloned table
- byte[] clonedTableName2 = Bytes.toBytes("clonedtb2-" + System.currentTimeMillis());
- admin.cloneSnapshot(snapshotName2, clonedTableName2);
- verifyRowCount(clonedTableName2, snapshot0Rows);
- admin.disableTable(clonedTableName2);
-
- // Remove the original table
- admin.disableTable(tableName);
- admin.deleteTable(tableName);
- waitCleanerRun();
-
- // Verify the first cloned table
- admin.enableTable(clonedTableName);
- verifyRowCount(clonedTableName, snapshot0Rows);
-
- // Verify the second cloned table
- admin.enableTable(clonedTableName2);
- verifyRowCount(clonedTableName2, snapshot0Rows);
- admin.disableTable(clonedTableName2);
-
- // Delete the first cloned table
- admin.disableTable(clonedTableName);
- admin.deleteTable(clonedTableName);
- waitCleanerRun();
-
- // Verify the second cloned table
- admin.enableTable(clonedTableName2);
- verifyRowCount(clonedTableName2, snapshot0Rows);
-
- // Clone a new table from cloned
- byte[] clonedTableName3 = Bytes.toBytes("clonedtb3-" + System.currentTimeMillis());
- admin.cloneSnapshot(snapshotName2, clonedTableName3);
- verifyRowCount(clonedTableName3, snapshot0Rows);
-
- // Delete the cloned tables
- admin.disableTable(clonedTableName2);
- admin.deleteTable(clonedTableName2);
- admin.disableTable(clonedTableName3);
- admin.deleteTable(clonedTableName3);
- admin.deleteSnapshot(snapshotName2);
- }
-
// ==========================================================================
// Helpers
// ==========================================================================
|
7d8aff2ef670306fc01bd2160b1e755196558da1
|
orientdb
|
Fix by Andrey on marshalling/unmarshalling of- embedded documents--
|
c
|
https://github.com/orientechnologies/orientdb
|
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 4ff35d1ed82..f188da62984 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
@@ -51,6 +51,7 @@
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.serialization.serializer.object.OObjectSerializerHelper;
+import com.orientechnologies.orient.core.serialization.serializer.string.OStringSerializerAnyStreamable;
import com.orientechnologies.orient.core.tx.OTransactionRecordEntry;
@SuppressWarnings("unchecked")
@@ -134,7 +135,12 @@ public Object fieldFromStream(final ORecordInternal<?> iSourceRecord, final OTyp
if (iValue.length() > 2) {
// REMOVE BEGIN & END EMBEDDED CHARACTERS
final String value = iValue.substring(1, iValue.length() - 1);
- return fieldTypeFromStream((ODocument) iSourceRecord, iType, value);
+
+ // RECORD
+ final Object result = OStringSerializerAnyStreamable.INSTANCE.fromStream(iSourceRecord.getDatabase(), value);
+ if (result instanceof ODocument)
+ ((ODocument) result).addOwner(iSourceRecord);
+ return result;
} else
return null;
@@ -174,7 +180,7 @@ public Map<String, Object> embeddedMapFromStream(final ODocument iSourceDocument
String mapValue = entry.get(1);
final OType linkedType;
-
+
if (iLinkedType == null)
if (mapValue.length() > 0) {
linkedType = getType(mapValue);
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java
index 4c9c877fdbc..5db718dd9c3 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerSchemaAware2CSV.java
@@ -407,7 +407,7 @@ else if (fieldValue.equals("true") || fieldValue.equals("false"))
}
}
- if (type == OType.EMBEDDEDLIST || type == OType.EMBEDDEDSET || type == OType.EMBEDDEDMAP)
+ if (type == OType.EMBEDDEDLIST || type == OType.EMBEDDEDSET || type == OType.EMBEDDEDMAP || type == OType.EMBEDDED)
// SAVE THE TYPE AS EMBEDDED
record.field(fieldName, fieldFromStream(iRecord, type, linkedClass, linkedType, fieldName, fieldValue), type);
else
|
f128dc6ce8b5fa81a4f56972b80af18e89f46d98
|
frontlinesms-credit$plugin-paymentview
|
Now we have the functionality extended to the UI...
|
p
|
https://github.com/frontlinesms-credit/plugin-paymentview
|
diff --git a/src/main/java/net/frontlinesms/payment/PaymentServiceStartedNotification.java b/src/main/java/net/frontlinesms/payment/PaymentServiceStartedNotification.java
new file mode 100644
index 00000000..e0cda1ef
--- /dev/null
+++ b/src/main/java/net/frontlinesms/payment/PaymentServiceStartedNotification.java
@@ -0,0 +1,6 @@
+package net.frontlinesms.payment;
+
+import net.frontlinesms.events.FrontlineEventNotification;
+
+public class PaymentServiceStartedNotification implements FrontlineEventNotification {
+}
diff --git a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPaymentService.java b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPaymentService.java
index 71dd677d..1f6a7437 100644
--- a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPaymentService.java
+++ b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPaymentService.java
@@ -48,6 +48,9 @@ public abstract class MpesaPaymentService implements PaymentService, EventObserv
protected static final String PAID_BY_PATTERN = "([A-Za-z ]+)";
protected static final String ACCOUNT_NUMBER_PATTERN = "Account Number [\\d]+";
protected static final String RECEIVED_FROM = "received from";
+
+ private static final int BALANCE_ENQUIRY_CHARGE = 1;
+ private static final BigDecimal BD_BALANCE_ENQUIRY_CHARGE = new BigDecimal(BALANCE_ENQUIRY_CHARGE);
//> INSTANCE PROPERTIES
protected Logger pvLog;
@@ -63,7 +66,7 @@ public abstract class MpesaPaymentService implements PaymentService, EventObserv
//> FIELDS
private String pin;
protected Balance balance;
- private EventBus eventBus;
+ protected EventBus eventBus;
private TargetAnalytics targetAnalytics;
//> STK & PAYMENT ACCOUNT
@@ -247,6 +250,30 @@ public void run() {
}.execute();
}
+ protected void processBalance(final FrontlineMessage message){
+ //TODO: On first run, should the user be told to update the
+ //balance by making an enquiry to M-PESA, or?
+ new PaymentJob() {
+ public void run() {
+ performBalanceEnquiryFraudCheck(message);
+ }
+ }.execute();
+ }
+
+ synchronized void performBalanceEnquiryFraudCheck(final FrontlineMessage message) {
+ BigDecimal tempBalance = balance.getBalanceAmount();
+ BigDecimal expectedBalance = tempBalance.subtract(BD_BALANCE_ENQUIRY_CHARGE);
+
+ BigDecimal actualBalance = getAmount(message);
+ informUserOnFraud(expectedBalance, actualBalance, !expectedBalance.equals(actualBalance));
+
+ balance.setBalanceAmount(actualBalance);
+ balance.setConfirmationMessage(getConfirmationCode(message));
+ balance.setDateTime(getTimePaid(message));
+ balance.setBalanceUpdateMethod("BalanceEnquiry");
+ balance.updateBalance();
+ }
+
synchronized void performIncominPaymentFraudCheck(final FrontlineMessage message,
final IncomingPayment payment) {
//check is: Let Previous Balance be p, Current Balance be c and Amount received be a
@@ -266,7 +293,9 @@ synchronized void performIncominPaymentFraudCheck(final FrontlineMessage message
void informUserOnFraud(BigDecimal expected, BigDecimal actual, boolean fraudCommited) {
if (fraudCommited) {
- pvLog.warn("Fraud commited? Was Expecting: "+expected+", But was "+actual);
+ String message = "Fraud commited? Was expecting balance as: "+expected+", But was "+actual;
+ pvLog.warn(message);
+ this.eventBus.notifyObservers(new BalanceFraudNotification(message));
}else{
pvLog.info("No Fraud occured!");
}
@@ -279,7 +308,6 @@ private boolean isValidIncomingPaymentConfirmation(final FrontlineMessage messag
return isMessageTextValid(message.getTextContent());
}
- abstract void processBalance(FrontlineMessage message);
abstract Date getTimePaid(FrontlineMessage message);
abstract boolean isMessageTextValid(String message);
abstract Account getAccount(FrontlineMessage message);
@@ -405,8 +433,12 @@ public void initDaosAndServices(final PaymentViewPluginController pluginControll
this.targetAnalytics = pluginController.getTargetAnalytics();
this.balance = Balance.getInstance().getLatest();
- this.balance.setEventBus(pluginController.getUiGeneratorController()
- .getFrontlineController().getEventBus());
+ this.registerToEventBus(
+ pluginController.getUiGeneratorController()
+ .getFrontlineController().getEventBus()
+ );
+
+ this.balance.setEventBus(this.eventBus);
//Would like to test using the log...
this.pvLog = pluginController.getLogger(this.getClass());
}
@@ -423,4 +455,10 @@ public String createAccountNumber(){
}
return accountNumberGeneratedStr;
}
+
+ public class BalanceFraudNotification implements FrontlineEventNotification{
+ private final String message;
+ public BalanceFraudNotification(String message){this.message=message;}
+ public String getMessage(){return message;}
+ }
}
\ No newline at end of file
diff --git a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPersonalService.java b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPersonalService.java
index 34c42839..88fca9f7 100644
--- a/src/main/java/net/frontlinesms/payment/safaricom/MpesaPersonalService.java
+++ b/src/main/java/net/frontlinesms/payment/safaricom/MpesaPersonalService.java
@@ -16,8 +16,6 @@
public class MpesaPersonalService extends MpesaPaymentService {
- private static final int BALANCE_ENQUIRY_CHARGE = 1;
- private static final BigDecimal BD_BALANCE_ENQUIRY_CHARGE = new BigDecimal(BALANCE_ENQUIRY_CHARGE);
//> REGEX PATTERN CONSTANTS
private static final String STR_PERSONAL_INCOMING_PAYMENT_REGEX_PATTERN = "[A-Z0-9]+ Confirmed.\n" +
"You have received Ksh[,|.|\\d]+ from\n([A-Za-z ]+) 2547[\\d]{8}\non " +
@@ -45,30 +43,6 @@ protected boolean isValidBalanceMessage(FrontlineMessage message){
return BALANCE_REGEX_PATTERN.matcher(message.getTextContent()).matches();
}
- protected void processBalance(final FrontlineMessage message){
- //TODO: On first run, the user should be told to update the
- //Balance by sending a request to M-PESA, or?
- new PaymentJob() {
- public void run() {
- performBalanceEnquiryFraudCheck(message);
- }
- }.execute();
- }
-
- private synchronized void performBalanceEnquiryFraudCheck(final FrontlineMessage message) {
- BigDecimal tempBalance = balance.getBalanceAmount();
- BigDecimal expectedBalance = getAmount(message);
-
- BigDecimal actual = tempBalance.subtract(BD_BALANCE_ENQUIRY_CHARGE);
- informUserOnFraud(expectedBalance, actual, !expectedBalance.equals(actual));
-
- balance.setBalanceAmount(expectedBalance);
- balance.setConfirmationMessage(getConfirmationCode(message));
- balance.setDateTime(getTimePaid(message));
- balance.setBalanceUpdateMethod("BalanceEnquiry");
- balance.updateBalance();
- }
-
@Override
protected void processMessage(final FrontlineMessage message) {
super.processMessage(message);
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/SettingsTabHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/SettingsTabHandler.java
index ca6228dd..70dc6197 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/SettingsTabHandler.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/SettingsTabHandler.java
@@ -6,7 +6,10 @@
import net.frontlinesms.events.FrontlineEventNotification;
import net.frontlinesms.payment.PaymentService;
import net.frontlinesms.payment.PaymentServiceException;
+import net.frontlinesms.payment.PaymentServiceStartedNotification;
import net.frontlinesms.payment.safaricom.MpesaPaymentService;
+import net.frontlinesms.payment.safaricom.MpesaPaymentService.BalanceFraudNotification;
+import net.frontlinesms.ui.UiDestroyEvent;
import net.frontlinesms.ui.UiGeneratorController;
import net.frontlinesms.ui.events.FrontlineUiUpateJob;
import net.frontlinesms.ui.handler.BaseTabHandler;
@@ -17,6 +20,7 @@
import org.creditsms.plugins.paymentview.userhomepropeties.payment.balance.Balance.BalanceEventNotification;
public class SettingsTabHandler extends BaseTabHandler implements EventObserver{
+ private static final String BTN_CREATE_NEW_SERVICE = "btn_createNewService";
private static final String COMPONENT_SETTINGS_TABLE = "tbl_accounts";
private static final String XML_SETTINGS_TAB = "/ui/plugins/paymentview/settings/settingsTab.xml";
@@ -82,11 +86,19 @@ public void deleteAccount() {
public void notify(final FrontlineEventNotification notification) {
new FrontlineUiUpateJob() {
public void run() {
- if (!(notification instanceof BalanceEventNotification)) {
- return;
- }else{
+ if (notification instanceof BalanceEventNotification) {
ui.alert(((BalanceEventNotification)notification).getMessage());
SettingsTabHandler.this.refresh();
+ }else if (notification instanceof PaymentServiceStartedNotification) {
+ SettingsTabHandler.this.refresh();
+ ui.setEnabled(ui.find(settingsTab, BTN_CREATE_NEW_SERVICE), false);
+ }else if(notification instanceof BalanceFraudNotification){
+ ui.alert(((BalanceFraudNotification)notification).getMessage());
+ SettingsTabHandler.this.refresh();//Hoping this will be moved to the new Log Tab
+ }else if (notification instanceof UiDestroyEvent) {
+ if(((UiDestroyEvent) notification).isFor(ui)) {
+ ui.getFrontlineController().getEventBus().unregisterObserver(SettingsTabHandler.this);
+ }
}
}
}.execute();
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/EnterPinDialog.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/EnterPinDialog.java
index b41a2004..fc2dcbca 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/EnterPinDialog.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/EnterPinDialog.java
@@ -1,6 +1,8 @@
package org.creditsms.plugins.paymentview.ui.handler.tabsettings.dialogs.steps.createnewsettings;
+import net.frontlinesms.events.EventBus;
import net.frontlinesms.messaging.sms.modem.SmsModem;
+import net.frontlinesms.payment.PaymentServiceStartedNotification;
import net.frontlinesms.payment.safaricom.MpesaPaymentService;
import net.frontlinesms.ui.UiGeneratorController;
@@ -60,7 +62,10 @@ public void setUpThePaymentService(final String pin, final String vPin) {
}
public void create() {
- ui.getFrontlineController().getEventBus().registerObserver(paymentService);
+ EventBus eventBus = ui.getFrontlineController().getEventBus();
+ eventBus.registerObserver(paymentService);
+ eventBus.notifyObservers(new PaymentServiceStartedNotification());
+
pluginController.setPaymentService(paymentService);
ui.alert("The Payment service has been created successfully!");
removeDialog(ui.find(DLG_VERIFICATION_CODE));
@@ -74,7 +79,7 @@ private boolean checkValidityOfPinFields(String pin, String vPin){
public void assertMaxLength(Object component) {
String text = ui.getText(component);
if(text.length() > EXPECTED_PIN_LENGTH) {
- ui.setText(component, text.substring(0, EXPECTED_PIN_LENGTH - 1));
+ ui.setText(component, text.substring(0, EXPECTED_PIN_LENGTH));
}
}
}
diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/MobilePaymentServiceSettingsInitialisationDialog.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/MobilePaymentServiceSettingsInitialisationDialog.java
index 6f440cde..78a9902c 100644
--- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/MobilePaymentServiceSettingsInitialisationDialog.java
+++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabsettings/dialogs/steps/createnewsettings/MobilePaymentServiceSettingsInitialisationDialog.java
@@ -38,14 +38,12 @@ private Object getComboChoice(SmsModem s) {
}
private void setUpPaymentServices(Object cmbSelectPaymentService) {
- //TODO: We should think of having modules at this case;Some Metaprogramming in the house!!
MpesaPaymentService mpesaPersonal = new MpesaPersonalService();
Object comboboxChoice1 = ui.createComboboxChoice(mpesaPersonal.toString(), mpesaPersonal);
MpesaPaymentService mpesaPaybill = new MpesaPayBillService();
Object comboboxChoice2 = ui.createComboboxChoice(mpesaPaybill.toString(), mpesaPaybill);
-
ui.add(cmbSelectPaymentService, comboboxChoice1);
ui.add(cmbSelectPaymentService, comboboxChoice2);
}
@@ -64,7 +62,7 @@ public void next() {
}
private void cleanUp() {
- //Memory Leaks; Should the Payment Services be Singletons
+ //Memory Leaks; Should the Payment Services be Singletons?
}
//> ACCESSORS
diff --git a/src/main/resources/ui/plugins/paymentview/settings/settingsTab.xml b/src/main/resources/ui/plugins/paymentview/settings/settingsTab.xml
index d5b7b677..adb1e9d2 100644
--- a/src/main/resources/ui/plugins/paymentview/settings/settingsTab.xml
+++ b/src/main/resources/ui/plugins/paymentview/settings/settingsTab.xml
@@ -4,10 +4,7 @@
columns="1" gap="10">
<panel columns="1" gap="5" name="pnl_accounts" weightx="1"
weighty="1">
- <panel weightx="1">
- <label text="Mobile Payment Account Settings" font="20 Bold"/>
- <button name="refresh" action="refresh" text="Refresh"/>
- </panel>
+ <label text="Mobile Payment Account Settings" font="20 Bold" weightx="1"/>
<table name="tbl_accounts" weightx="1" weighty="1" delete="showConfirmationDialog('deleteAccount')">
<header>
<column text="i18n.common.port" width="200" icon="/icons/port_open.png"/>
@@ -27,7 +24,7 @@
</panel>
<panel gap="5" bottom="5" name="pnl_buttons"
weightx="1">
- <button name="btn_analyse" icon="/icons/keyword_add.png" text="i18n.plugins.paymentview.action.createnew" action="createNew" />
+ <button name="btn_createNewService" icon="/icons/keyword_add.png" text="i18n.plugins.paymentview.action.createnew" action="createNew" />
<panel weightx="1"/>
<panel weightx="1"/>
<button action="updateAccountBalance" icon="/icons/connection.png" halign="right" name="btn_export"
diff --git a/src/test/java/net/frontlinesms/payment/safaricom/MpesaPaymentServiceTest.java b/src/test/java/net/frontlinesms/payment/safaricom/MpesaPaymentServiceTest.java
index 9d7f1d6f..4b581780 100644
--- a/src/test/java/net/frontlinesms/payment/safaricom/MpesaPaymentServiceTest.java
+++ b/src/test/java/net/frontlinesms/payment/safaricom/MpesaPaymentServiceTest.java
@@ -156,7 +156,7 @@ private void setUpDaos() {
FrontlineSMS fsms = mock(FrontlineSMS.class);
EventBus eventBus = mock(EventBus.class);
-
+ mpesaPaymentService.registerToEventBus(eventBus);
when(fsms.getEventBus()).thenReturn(eventBus);
when(ui.getFrontlineController()).thenReturn(fsms);
|
bb85cacf9358f9ed289e72a416e78625fcab18a4
|
Delta Spike
|
DELTASPIKE-289 fix WindowScoped context test on jbossas
I recently removed the <h:form> which did lead to a different
component Id for the outputValue. fixed now.
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java
index c57b16c48..a6e97cb28 100644
--- a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java
+++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java
@@ -20,6 +20,7 @@
import java.net.URL;
+import java.util.logging.Logger;
import org.apache.deltaspike.test.category.WebProfileCategory;
import org.apache.deltaspike.test.jsf.impl.scope.window.beans.WindowScopedBackingBean;
@@ -51,6 +52,8 @@
@Category(WebProfileCategory.class)
public class WindowScopedContextTest
{
+ private static final Logger log = Logger.getLogger(WindowScopedContextTest.class.getName());
+
@Drone
private WebDriver driver;
@@ -79,14 +82,12 @@ public static WebArchive deploy()
public void testWindowId() throws Exception
{
System.out.println("contextpath= " + contextPath);
- //X
- Thread.sleep(600000L);
-
- driver.get(new URL(contextPath, "page.xhtml").toString());
//X comment this in if you like to debug the server
//X I've already reported ARQGRA-213 for it
- //X
+ //X Thread.sleep(600000L);
+
+ driver.get(new URL(contextPath, "page.xhtml").toString());
WebElement inputField = driver.findElement(By.id("test:valueInput"));
inputField.sendKeys("23");
@@ -94,7 +95,7 @@ public void testWindowId() throws Exception
WebElement button = driver.findElement(By.id("test:saveButton"));
button.click();
- Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("test:valueOutput"), "23").apply(driver));
+ Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("valueOutput"), "23").apply(driver));
}
|
e449fb139b70db15ffae182355d5306d90389adb
|
ReactiveX-RxJava
|
Fixed javadoc and comments
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
index 3cf2a410c4..87d0cbe0c9 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
@@ -43,6 +43,14 @@
public class OperationCombineLatest {
+ /**
+ * Combines the two given observables, emitting an event containing an aggregation of the latest values of each of the source observables
+ * each time an event is received from one of the source observables, where the aggregation is defined by the given function.
+ * @param w0 The first source observable.
+ * @param w1 The second source observable.
+ * @param combineLatestFunction The aggregation function used to combine the source observable values.
+ * @return A function from an observer to a subscription. This can be used to create an observable from.
+ */
public static <T0, T1, R> Func1<Observer<R>, Subscription> combineLatest(Observable<T0> w0, Observable<T1> w1, Func2<T0, T1, R> combineLatestFunction) {
Aggregator<R> a = new Aggregator<R>(Functions.fromFunc(combineLatestFunction));
a.addObserver(new CombineObserver<R, T0>(a, w0));
@@ -50,6 +58,9 @@ public static <T0, T1, R> Func1<Observer<R>, Subscription> combineLatest(Observa
return a;
}
+ /**
+ * @see #combineLatest(Observable<T0> w0, Observable<T1> w1, Func2<T0, T1, R> combineLatestFunction)
+ */
public static <T0, T1, T2, R> Func1<Observer<R>, Subscription> combineLatest(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Func3<T0, T1, T2, R> combineLatestFunction) {
Aggregator<R> a = new Aggregator<R>(Functions.fromFunc(combineLatestFunction));
a.addObserver(new CombineObserver<R, T0>(a, w0));
@@ -58,6 +69,9 @@ public static <T0, T1, T2, R> Func1<Observer<R>, Subscription> combineLatest(Obs
return a;
}
+ /**
+ * @see #combineLatest(Observable<T0> w0, Observable<T1> w1, Func2<T0, T1, R> combineLatestFunction)
+ */
public static <T0, T1, T2, T3, R> Func1<Observer<R>, Subscription> combineLatest(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Observable<T3> w3, Func4<T0, T1, T2, T3, R> combineLatestFunction) {
Aggregator<R> a = new Aggregator<R>(Functions.fromFunc(combineLatestFunction));
a.addObserver(new CombineObserver<R, T0>(a, w0));
@@ -91,7 +105,7 @@ public void onCompleted() {
@Override
public void onError(Exception e) {
- a.error(this, e);
+ a.error(e);
}
@Override
@@ -101,32 +115,46 @@ public void onNext(T args) {
}
/**
- * Receive notifications from each of the Observables we are reducing and execute the combineLatestFunction whenever we have received events from all Observables.
- *
- * @param <R>
+ * Receive notifications from each of the observables we are reducing and execute the combineLatestFunction
+ * whenever we have received an event from one of the observables, as soon as each Observable has received
+ * at least one event.
*/
private static class Aggregator<R> implements Func1<Observer<R>, Subscription> {
+ private Observer<R> observer;
+
private final FuncN<R> combineLatestFunction;
- private Observer<R> Observer;
- private AtomicBoolean running = new AtomicBoolean(true);
+ private final AtomicBoolean running = new AtomicBoolean(true);
+ // used as an internal lock for handling the latest values and the completed state of each observer
+ private final Object lockObject = new Object();
+
/**
- * store when a Observer completes
+ * Store when an observer completes.
* <p>
- * Note that access to this set MUST BE SYNCHRONIZED
+ * Note that access to this set MUST BE SYNCHRONIZED via 'lockObject' above.
* */
- private Set<CombineObserver<R, ?>> completed = new HashSet<CombineObserver<R, ?>>();
+ private final Set<CombineObserver<R, ?>> completed = new HashSet<CombineObserver<R, ?>>();
/**
- * The last value from a Observer
+ * The latest value from each observer
* <p>
- * Note that access to this set MUST BE SYNCHRONIZED
+ * Note that access to this set MUST BE SYNCHRONIZED via 'lockObject' above.
* */
- private Map<CombineObserver<R, ?>, Object> lastValue = new HashMap<CombineObserver<R, ?>, Object>();
+ private final Map<CombineObserver<R, ?>, Object> latestValue = new HashMap<CombineObserver<R, ?>, Object>();
- private Set<CombineObserver<R, ?>> hasLastValue = new HashSet<CombineObserver<R, ?>>();
- private List<CombineObserver<R, ?>> observers = new LinkedList<CombineObserver<R, ?>>();
+ /**
+ * Whether each observer has a latest value at all.
+ * <p>
+ * Note that access to this set MUST BE SYNCHRONIZED via 'lockObject' above.
+ * */
+ private final Set<CombineObserver<R, ?>> hasLatestValue = new HashSet<CombineObserver<R, ?>>();
+
+ /**
+ * Ordered list of observers to combine.
+ * No synchronization is necessary as these can not be added or changed asynchronously.
+ */
+ private final List<CombineObserver<R, ?>> observers = new LinkedList<CombineObserver<R, ?>>();
public Aggregator(FuncN<R> combineLatestFunction) {
this.combineLatestFunction = combineLatestFunction;
@@ -135,55 +163,53 @@ public Aggregator(FuncN<R> combineLatestFunction) {
/**
* Receive notification of a Observer starting (meaning we should require it for aggregation)
*
- * @param w
+ * @param w The observer to add.
*/
- synchronized <T> void addObserver(CombineObserver<R, T> w) {
- observers.add(w);
+ <T> void addObserver(CombineObserver<R, T> w) {
+ observers.add(w);
}
/**
* Receive notification of a Observer completing its iterations.
*
- * @param w
+ * @param w The observer that has completed.
*/
- synchronized <T> void complete(CombineObserver<R, T> w) {
- // store that this CombineLatestObserver is completed
- completed.add(w);
- // if all CombineObservers are completed, we mark the whole thing as completed
- if (completed.size() == observers.size()) {
- if (running.get()) {
- // mark ourselves as done
- Observer.onCompleted();
- // just to ensure we stop processing in case we receive more onNext/complete/error calls after this
- running.set(false);
+ <T> void complete(CombineObserver<R, T> w) {
+ synchronized(lockObject) {
+ // store that this CombineLatestObserver is completed
+ completed.add(w);
+ // if all CombineObservers are completed, we mark the whole thing as completed
+ if (completed.size() == observers.size()) {
+ if (running.get()) {
+ // mark ourselves as done
+ observer.onCompleted();
+ // just to ensure we stop processing in case we receive more onNext/complete/error calls after this
+ running.set(false);
+ }
}
}
}
/**
* Receive error for a Observer. Throw the error up the chain and stop processing.
- *
- * @param w
*/
- synchronized <T> void error(CombineObserver<R, T> w, Exception e) {
- Observer.onError(e);
- /* tell ourselves to stop processing onNext events, event if the Observers don't obey the unsubscribe we're about to send */
- running.set(false);
- /* tell all Observers to unsubscribe since we had an error */
+ void error(Exception e) {
+ observer.onError(e);
+ /* tell all observers to unsubscribe since we had an error */
stop();
}
/**
- * Receive the next value from a Observer.
+ * Receive the next value from an observer.
* <p>
- * If we have received values from all Observers, trigger the combineLatest function, otherwise store the value and keep waiting.
+ * If we have received values from all observers, trigger the combineLatest function, otherwise store the value and keep waiting.
*
* @param w
* @param arg
*/
<T> void next(CombineObserver<R, T> w, T arg) {
- if (Observer == null) {
- throw new RuntimeException("This shouldn't be running if a Observer isn't registered");
+ if (observer == null) {
+ throw new RuntimeException("This shouldn't be running if an Observer isn't registered");
}
/* if we've been 'unsubscribed' don't process anything further even if the things we're watching keep sending (likely because they are not responding to the unsubscribe call) */
@@ -194,15 +220,17 @@ <T> void next(CombineObserver<R, T> w, T arg) {
// define here so the variable is out of the synchronized scope
Object[] argsToCombineLatest = new Object[observers.size()];
- // we synchronize everything that touches receivedValues and the internal LinkedList objects
- synchronized (this) {
- // remember this as the last value for this Observer
- lastValue.put(w, arg);
- hasLastValue.add(w);
+ // we synchronize everything that touches latest values
+ synchronized (lockObject) {
+ // remember this as the latest value for this observer
+ latestValue.put(w, arg);
+
+ // remember that this observer now has a latest value set
+ hasLatestValue.add(w);
- // if all CombineLatestObservers in 'receivedValues' map have a value, invoke the combineLatestFunction
+ // if all observers in the 'observers' list have a value, invoke the combineLatestFunction
for (CombineObserver<R, ?> rw : observers) {
- if (!hasLastValue.contains(rw)) {
+ if (!hasLatestValue.contains(rw)) {
// we don't have a value yet for each observer to combine, so we don't have a combined value yet either
return;
}
@@ -210,48 +238,45 @@ <T> void next(CombineObserver<R, T> w, T arg) {
// if we get to here this means all the queues have data
int i = 0;
for (CombineObserver<R, ?> _w : observers) {
- argsToCombineLatest[i++] = lastValue.get(_w);
+ argsToCombineLatest[i++] = latestValue.get(_w);
}
}
// if we did not return above from the synchronized block we can now invoke the combineLatestFunction with all of the args
// we do this outside the synchronized block as it is now safe to call this concurrently and don't need to block other threads from calling
// this 'next' method while another thread finishes calling this combineLatestFunction
- Observer.onNext(combineLatestFunction.call(argsToCombineLatest));
+ observer.onNext(combineLatestFunction.call(argsToCombineLatest));
}
@Override
- public Subscription call(Observer<R> Observer) {
- if (this.Observer != null) {
+ public Subscription call(Observer<R> observer) {
+ if (this.observer != null) {
throw new IllegalStateException("Only one Observer can subscribe to this Observable.");
}
- this.Observer = Observer;
+ this.observer = observer;
- /* start the Observers */
+ /* start the observers */
for (CombineObserver<R, ?> rw : observers) {
rw.startWatching();
}
return new Subscription() {
-
@Override
public void unsubscribe() {
stop();
}
-
};
}
private void stop() {
/* tell ourselves to stop processing onNext events */
running.set(false);
- /* propogate to all Observers to unsubscribe */
+ /* propogate to all observers to unsubscribe */
for (CombineObserver<R, ?> rw : observers) {
if (rw.subscription != null) {
rw.subscription.unsubscribe();
}
}
}
-
}
public static class UnitTest {
@@ -597,7 +622,7 @@ public void testAggregatorError() {
verify(aObserver, never()).onCompleted();
verify(aObserver, times(1)).onNext("helloworld");
- a.error(r1, new RuntimeException(""));
+ a.error(new RuntimeException(""));
a.next(r1, "hello");
a.next(r2, "again");
|
45e386a75716885ff1c65211532d8cf7c3950306
|
iee$iee
|
rewritten expression type detection - improved performance, flexibility
|
p
|
https://github.com/iee/iee
|
diff --git a/org.eclipse.iee.p2-repo/pom.xml b/org.eclipse.iee.p2-repo/pom.xml
index e4140806..a61309ca 100644
--- a/org.eclipse.iee.p2-repo/pom.xml
+++ b/org.eclipse.iee.p2-repo/pom.xml
@@ -57,6 +57,10 @@
<id>net.sourceforge.cssparser:cssparser:0.9.11</id>
<source>true</source>
</artifact>
+ <artifact>
+ <id>gov.nist.math:jama:1.0.3</id>
+ <source>true</source>
+ </artifact>
</artifacts>
</configuration>
</execution>
diff --git a/org.eclipse.iee.translator.antlr/META-INF/MANIFEST.MF b/org.eclipse.iee.translator.antlr/META-INF/MANIFEST.MF
index 94a9dc2b..2d866229 100644
--- a/org.eclipse.iee.translator.antlr/META-INF/MANIFEST.MF
+++ b/org.eclipse.iee.translator.antlr/META-INF/MANIFEST.MF
@@ -15,5 +15,7 @@ Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Export-Package: org.eclipse.iee.translator.antlr.java,
org.eclipse.iee.translator.antlr.math,
org.eclipse.iee.translator.antlr.translator
-Import-Package: org.slf4j;version="1.7.2",
+Import-Package: Jama,
+ com.google.common.collect;version="16.0.1",
+ org.slf4j;version="1.7.2",
org.stringtemplate.v4
diff --git a/org.eclipse.iee.translator.antlr/antlr4/org/eclipse/iee/translator/antlr/math/Math.g4 b/org.eclipse.iee.translator.antlr/antlr4/org/eclipse/iee/translator/antlr/math/Math.g4
index 2e4e551a..76599db0 100644
--- a/org.eclipse.iee.translator.antlr/antlr4/org/eclipse/iee/translator/antlr/math/Math.g4
+++ b/org.eclipse.iee.translator.antlr/antlr4/org/eclipse/iee/translator/antlr/math/Math.g4
@@ -27,7 +27,7 @@ standardFunction:
;
variableAssignment:
- name=expression '=' value=expression
+ name=MATH_NAME '=' value=expression
;
expression:
diff --git a/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/JavaTranslator.java b/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/JavaTranslator.java
index a8c6420d..ffbbdc9e 100644
--- a/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/JavaTranslator.java
+++ b/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/JavaTranslator.java
@@ -1,8 +1,10 @@
package org.eclipse.iee.translator.antlr.translator;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@@ -16,8 +18,10 @@
import org.eclipse.iee.translator.antlr.math.MathLexer;
import org.eclipse.iee.translator.antlr.math.MathParser;
import org.eclipse.iee.translator.antlr.math.MathParser.IntervalParameterContext;
+import org.eclipse.iee.translator.antlr.math.MathParser.MatrixElementContext;
+import org.eclipse.iee.translator.antlr.math.MathParser.PrimaryExprContext;
import org.eclipse.iee.translator.antlr.math.MathParser.ValueParameterContext;
-import org.eclipse.jdt.core.IBuffer;
+import org.eclipse.iee.translator.antlr.math.MathParser.VariableAssignmentContext;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
@@ -29,10 +33,7 @@
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
-import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.core.dom.Expression;
-import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import org.slf4j.Logger;
@@ -41,6 +42,8 @@
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupDir;
+import Jama.Matrix;
+
public class JavaTranslator {
private static final Logger logger = LoggerFactory.getLogger(JavaTranslator.class);
@@ -50,47 +53,41 @@ public enum VariableType {
}
private ICompilationUnit fCompilationUnit;
+
private IType fClass;
+
private IMethod fMethod;
private int fPosition;
- private List<String> fDoubleFields = new ArrayList<>();
-
- private List<String> fIntegerFields = new ArrayList<>();
-
- private List<String> fMatrixFields = new ArrayList<>();
-
- private List<String> fOtherFields = new ArrayList<>();
+ private Map<String, String> fFields = new HashMap<>();
private Set<String> fOtherSourceClasses = new HashSet<>();
+
private Set<String> fMethodClasses = new HashSet<>();
+
private Set<String> fInnerClasses = new HashSet<>();
- private VariableType fVariableType = null;
- private String fVariableTypeString = "";
-
- private boolean fNewVariable;
- private boolean fVariableAssignment;
-
- private boolean fFunctionDefinition;
- private List<String> fDeterminedFunctionParams = new ArrayList<>();
- private List<String> fDeterminedFunctionVariables = new ArrayList<>();
-
- private List<String> fFoundedVariables = new ArrayList<>();
- private List<String> fInternalFunctionsParams = new ArrayList<>();
-
- private class JavaMathVisitor extends MathBaseVisitor<String> {
+ private static class JavaMathVisitor extends MathBaseVisitor<String> {
// statement rule
/*
* Help variables
*/
+ private boolean fFunctionDefinition;
+ private List<String> fDeterminedFunctionParams = new ArrayList<>();
+ private List<String> fDeterminedFunctionVariables = new ArrayList<>();
+
+ private List<String> fFoundedVariables = new ArrayList<>();
+ private List<String> fInternalFunctionsParams = new ArrayList<>();
- Boolean fVisitVariableName = false;
- Boolean fVisitedMatrixElement = false;
- Boolean fNewMatrix = false;
- Boolean fMatrixExpression = false;
+ private ExternalTranslationContext fExternalContext;
+ private TypeVisitior fTypeVisitor;
+
+ public JavaMathVisitor(ExternalTranslationContext externalContext) {
+ fExternalContext = externalContext;
+ fTypeVisitor = new TypeVisitior(fExternalContext);
+ }
public String visitFunctionDefinition(
MathParser.FunctionDefinitionContext ctx) {
@@ -133,49 +130,24 @@ public String visitFunctionDefinition(
public String visitVariableAssignment(
MathParser.VariableAssignmentContext ctx) {
- fVariableAssignment = true;
-
- fVisitVariableName = true;
- String name = visit(ctx.name);
- fVisitVariableName = false;
-
String value = visit(ctx.value);
-
- if (fVisitedMatrixElement) {
- fVariableType = VariableType.DOUBLE;
- return name += value + ");";
+
+ if (ctx.name instanceof PrimaryExprContext
+ && ((PrimaryExprContext) ctx.name).primary() instanceof MatrixElementContext) {
+ MatrixElementContext elt = (MatrixElementContext) ((PrimaryExprContext) ctx.name).primary();
+ String rowIndex = visit(elt.rowIdx).replaceAll("\\.0", "");
+ String columnIndex = visit(elt.columnIdx).replaceAll("\\.0", "");
+ return translateName(elt.name.getText()) + ".set(" + rowIndex + "," + columnIndex + "," + value + ")";
}
-
- if (fClass == null)
- return name + "=" + value + ";";
-
+
+
+ String name = translateName(ctx.name.getText());
+
String assignment = "";
- if (fDoubleFields.contains(name) || fMatrixFields.contains(name)
- || fIntegerFields.contains(name)) {
- if (fDoubleFields.contains(name))
- fVariableType = VariableType.DOUBLE;
- else if (fMatrixFields.contains(name))
- fVariableType = VariableType.MATRIX;
- else if (fIntegerFields.contains(name))
- fVariableType = VariableType.INT;
- else if (fOtherFields.contains(name))
- fVariableType = VariableType.OTHER;
-
- assignment += name + "=" + value + ";";
- } else {
- if ((fNewMatrix || fMatrixExpression || (fMatrixFields
- .contains(value)) && !name.matches(value))) {
- assignment += "Matrix ";
- fVariableType = VariableType.MATRIX;
- } else {
- fNewVariable = true;
- }
- assignment += name + "=";
- assignment += value + ";";
-
- }
+ assignment += name + "=" + value;
+
return assignment;
}
@@ -200,11 +172,11 @@ public String visitStandardFunction(
List<String> fieldsNames = new ArrayList<>();
List<String> params = new ArrayList<>();
- if (fMethodClasses.contains(firstLetterUpperCase(name))) {
+ if (fExternalContext.containsMethod(name)) {
new_ = "new ";
name_ = firstLetterUpperCase(name);
- IType type = fMethod.getType(firstLetterUpperCase(name), 1);
+ IType type = fExternalContext.getMethodType(name);
try {
IField[] fields = type.getFields();
for (int i = 0; i < fields.length; i++) {
@@ -224,11 +196,11 @@ public String visitStandardFunction(
e.printStackTrace();
}
- } else if (fInnerClasses.contains(firstLetterUpperCase(name))) {
+ } else if (fExternalContext.containsClass(name)) {
new_ = "this.new ";
name_ = firstLetterUpperCase(name);
- IType type = fClass.getType(firstLetterUpperCase(name), 1);
+ IType type = fExternalContext.getClassType(name);
try {
IField[] fields = type.getFields();
for (int i = 0; i < fields.length; i++) {
@@ -247,7 +219,7 @@ public String visitStandardFunction(
e.printStackTrace();
}
- } else if (fOtherSourceClasses.contains(firstLetterUpperCase(name))) {
+ } else if (fExternalContext.containsOtherSourceClass(name)) {
new_ = "new ";
name_ = firstLetterUpperCase(name);
@@ -482,12 +454,11 @@ public String visitAdd(MathParser.AddContext ctx) {
String right = visit(ctx.right);
String sign = ctx.sign.getText();
- if (getType(fPosition, "myTmp=" + left + ";").matches("Matrix")
- && getType(fPosition, "myTmp=" + right + ";").matches(
- "Matrix")) {
- // XXX: temporary solution
- fMatrixExpression = true;
-
+
+ VariableType leftType = ctx.left.accept(fTypeVisitor);
+ VariableType rightType = ctx.right.accept(fTypeVisitor);
+
+ if (leftType.equals(VariableType.MATRIX) && rightType.equals(VariableType.MATRIX)) {
if (sign.matches(Pattern.quote("+")))
return left + ".plus(" + right + ")";
if (sign.matches(Pattern.quote("-")))
@@ -502,12 +473,11 @@ public String visitMult(MathParser.MultContext ctx) {
String right = visit(ctx.right);
String sign = ctx.sign.getText();
- boolean leftMatrix = getType(fPosition, "myTmp=" + left + ";").matches("Matrix");
- boolean rightMatrix = getType(fPosition, "myTmp=" + right + ";").matches("Matrix");
+ VariableType leftType = ctx.left.accept(fTypeVisitor);
+ VariableType rightType = ctx.right.accept(fTypeVisitor);
+ boolean leftMatrix = leftType.equals(VariableType.MATRIX);
+ boolean rightMatrix = rightType.equals(VariableType.MATRIX);
if (leftMatrix || rightMatrix) {
- // XXX: temporary solution
- fMatrixExpression = true;
-
if (!leftMatrix && rightMatrix) {
String tmp = right;
right = left;
@@ -546,11 +516,8 @@ public String visitPower(MathParser.PowerContext ctx) {
String left = visit(ctx.left);
String right = visit(ctx.right);
- if (getType(fPosition, "myTmp=" + left + ";").matches("Matrix")
- && right.matches("T")) {
- // XXX: temporary solution
- fMatrixExpression = true;
-
+ VariableType type = ctx.left.accept(fTypeVisitor);
+ if (type.equals(VariableType.MATRIX) && right.matches("T")) {
return left + ".transpose()";
}
@@ -558,13 +525,10 @@ public String visitPower(MathParser.PowerContext ctx) {
}
public String visitMatrix(MathParser.MatrixContext ctx) {
-
- fNewMatrix = true;
-
String matrix = "";
int i;
- matrix += "new Matrix(new double[][]{";
+ matrix += "new Jama.Matrix(new double[][]{";
int rowsCount = ctx.rows.size();
for (i = 0; i < rowsCount; i++) {
@@ -640,7 +604,7 @@ public String visitFloatNumber(MathParser.FloatNumberContext ctx) {
}
public String visitIntNumber(MathParser.IntNumberContext ctx) {
- return ctx.getText() + ".0";
+ return ctx.getText();
}
public String visitMatrixDefinition(
@@ -653,14 +617,8 @@ public String visitMatrixElement(MathParser.MatrixElementContext ctx) {
String rowIndex = visit(ctx.rowIdx).replaceAll("\\.0", "");
String columnIndex = visit(ctx.columnIdx).replaceAll("\\.0", "");
- if (fVisitVariableName) {
- fVisitedMatrixElement = true;
-
- return translateName(ctx.name.getText()) + ".set(" + rowIndex
- + "," + columnIndex + ",";
- } else
- return translateName(ctx.name.getText()) + ".get(" + rowIndex
- + "," + columnIndex + ")";
+ return translateName(ctx.name.getText()) + ".get(" + rowIndex
+ + "," + columnIndex + ")";
}
public String visitPrimaryFunction(MathParser.PrimaryFunctionContext ctx) {
@@ -686,20 +644,82 @@ public static String translate(String expression) {
}
private String translateIntl(String expression) {
- String result = "";
+ ParserRuleContext tree = parseTree(expression);
+
+ return treeToString(tree);
+ }
+ private ParserRuleContext parseTree(String expression) {
ANTLRInputStream input = new ANTLRInputStream(expression);
MathLexer lexer = new MathLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
MathParser parser = new MathParser(tokens);
parser.setBuildParseTree(true);
ParserRuleContext tree = parser.statement();
+ return tree;
+ }
- JavaMathVisitor mathVisitor = new JavaMathVisitor();
+ private String treeToString(ParserRuleContext tree) {
+ String result;
+ JavaMathVisitor mathVisitor = createVisitor();
result = mathVisitor.visit(tree);
return result;
}
+ private JavaMathVisitor createVisitor() {
+ JavaMathVisitor mathVisitor = new JavaMathVisitor(createContext());
+ return mathVisitor;
+ }
+
+ private ExternalTranslationContext createContext() {
+ return new ExternalTranslationContext() {
+
+ @Override
+ public boolean containsMethod(String name) {
+ return fMethodClasses.contains(firstLetterUpperCase(name));
+ }
+
+ @Override
+ public IType getMethodType(String name) {
+ return fMethod.getType(firstLetterUpperCase(name), 1);
+ }
+
+ @Override
+ public boolean containsClass(String name) {
+ return fInnerClasses.contains(firstLetterUpperCase(name));
+ }
+
+ @Override
+ public IType getClassType(String name) {
+ return fClass.getType(firstLetterUpperCase(name), 1);
+ }
+
+ @Override
+ public boolean containsOtherSourceClass(String name) {
+ return fOtherSourceClasses.contains(firstLetterUpperCase(name));
+ }
+
+ @Override
+ public String translateName(String text) {
+ return JavaTranslator.translateName(text);
+ }
+
+ @Override
+ public VariableType getVariableType(String variable) {
+ String type = fFields.get(variable);
+ if ("double".equals(type)) {
+ return VariableType.DOUBLE;
+ } else if (Matrix.class.getName().equals(type)) {
+ return VariableType.MATRIX;
+ } else if ("int".equals(type)) {
+ return VariableType.INT;
+ } else {
+ return VariableType.OTHER;
+ }
+ }
+ };
+ }
+
public static String translate(String inputExpression,
ICompilationUnit compilationUnit, int position, String containerId) {
@@ -741,105 +761,59 @@ private String translateIntl(String inputExpression,
parse();
logger.debug("expr: " + expression);
- result = translateIntl(expression);
-
- /*
- * Try get recognize variable type from expression
- */
+ ParserRuleContext tree = parseTree(expression);
+ result = treeToString(tree);
- if (fNewVariable) {
- result = getType(fPosition, result) + " " + result;
+ String name = null;
+ if (tree.getChild(0) instanceof VariableAssignmentContext) {
+ VariableAssignmentContext assignment = (VariableAssignmentContext) tree.getChild(0);
+ name = translateName(assignment.name.getText());
}
-
- if (!fVariableAssignment)
- getType(position, "myTmp=" + result + ";");
-
+
/*
* Generate output code, if necessary
*/
+ VariableType type = tree.accept(new TypeVisitior(createContext()));
if (inputExpression.charAt(inputExpression.length() - 1) == '=') {
- if (!fVariableAssignment) {
- String output = generateOutputCode(result, containerId, false);
- result = output;
+ String output = generateOutputCode(type, result, containerId);
+ if (name != null && !fFields.containsKey(name)) {
+ result = getName(type) + " " + name + ";" + output;
} else {
- String output = generateOutputCode(inputExpression,
- containerId, true);
- result += output;
+ result = output;
}
- }
+ } else {
+ if (name != null && !fFields.containsKey(name)) {
+ result = getName(type) + " " + result + ";";
+ }
+ }
return result;
}
- private String generateOutputCode(String expression,
- String containerId, boolean isInputExpression) {
- String expr = expression;
-
- String[] parts;
-
- if (isInputExpression) {
- parts = expr.replaceAll(Pattern.quote("{"), "")
- .replaceAll(Pattern.quote("}"), "").split("=");
- } else
- parts = expr.split("=");
-
- if (parts.length >= 1) {
- String variable = expression;
- if (parts.length > 1 && isInputExpression)
- variable = expression.substring(0, expression.indexOf('='));
-
- variable = variable.trim();
- if (isInputExpression) {
- variable = variable.replaceAll(Pattern.quote("{"), "");
- variable = variable.replaceAll(Pattern.quote("}"), "");
- }
-
- VariableType varType = fVariableType;
-
- if (varType == null) {
- if (fDoubleFields.contains(variable))
- varType = VariableType.DOUBLE;
- else if (fIntegerFields.contains(variable))
- varType = VariableType.INT;
- else if (fMatrixFields.contains(variable))
- varType = VariableType.MATRIX;
- else
- return "";
- }
-
- logger.debug("Type:" + varType.toString());
+ private String generateOutputCode(VariableType type, String expression, String containerId) {
STGroup group = createSTGroup();
-
- if (varType != VariableType.MATRIX) {
-
- String type = "";
- if (varType == VariableType.DOUBLE)
- type = "double";
- else if (varType == VariableType.INT)
- type = "int";
-
- ST template = group.getInstanceOf("variable");
-
- template.add("type", type);
+ if (VariableType.MATRIX.equals(type)) {
+ ST template = group.getInstanceOf("matrix");
template.add("id", containerId);
- template.add("variable", variable);
-
- return template.render(1).trim().replaceAll("\r\n", "")
- .replaceAll("\t", " ");
-
+ template.add("variable", expression);
+ return template.render(1).trim().replaceAll("\r\n", "").replaceAll("\t", " ");
} else {
-
- String type = "Matrix";
-
- ST template = group.getInstanceOf("matrix");
- template.add("type", type);
+ ST template = group.getInstanceOf("variable");
template.add("id", containerId);
- template.add("variable", variable);
-
- return template.render(1).trim().replaceAll("\r\n", "")
- .replaceAll("\t", " ");
+ template.add("variable", expression);
+ return template.render(1).trim().replaceAll("\r\n", "").replaceAll("\t", " ");
}
- } else {
- return "";
+ }
+
+ private String getName(VariableType type) {
+ switch (type) {
+ case DOUBLE:
+ return "double";
+ case INT:
+ return "int";
+ case MATRIX:
+ return "Jama.Matrix";
+ default:
+ return null;
}
}
@@ -917,19 +891,7 @@ private void parse() {
int fieldOffset = fieldSourceRange.getOffset();
if (fPosition > fieldOffset) {
- if (type.matches("D")) {
- if (!fDoubleFields.contains(name))
- fDoubleFields.add(name);
- } else if (type.matches("QMatrix;")) {
- if (!fMatrixFields.contains(name))
- fMatrixFields.add(name);
- } else if (type.matches("I")) {
- if (!fIntegerFields.contains(name))
- fIntegerFields.add(name);
- } else {
- if (!fOtherFields.contains(name))
- fOtherFields.add(name);
- }
+ fFields.put(name, type);
}
}
}
@@ -940,21 +902,7 @@ private void parse() {
ILocalVariable param = methodParams[i];
String name = param.getElementName();
String type = param.getTypeSignature();
-
- if (type.matches("D")) {
- if (!fDoubleFields.contains(name))
- fDoubleFields.add(name);
- } else if (type.matches("QMatrix;")) {
- if (!fMatrixFields.contains(name))
- fMatrixFields.add(name);
- } else if (type.matches("I")) {
- if (!fIntegerFields.contains(name))
- fIntegerFields.add(name);
- } else {
- if (!fOtherFields.contains(name))
- fOtherFields.add(name);
- }
-
+ fFields.put(name, type);
}
IJavaElement[] innerElements = fMethod.getChildren();
@@ -990,20 +938,7 @@ public boolean visit(VariableDeclarationStatement node) {
VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments
.get(i);
String name = fragment.getName().toString();
-
- if (type.matches("double")) {
- if (!fDoubleFields.contains(name))
- fDoubleFields.add(name);
- } else if (type.matches("Matrix")) {
- if (!fMatrixFields.contains(name))
- fMatrixFields.add(name);
- } else if (type.matches("int")) {
- if (!fIntegerFields.contains(name))
- fIntegerFields.add(name);
- } else {
- if (!fOtherFields.contains(name))
- fOtherFields.add(name);
- }
+ fFields.put(name, type);
}
}
} catch (JavaModelException e) {
@@ -1029,71 +964,8 @@ public boolean visit(VariableDeclarationStatement node) {
logger.debug("fMethod: " + fMethod.getElementName());
logger.debug("fMethodClasses: " + fMethodClasses.toString());
}
- logger.debug("fMatrixFields: " + fMatrixFields.toString());
- logger.debug("fDoubleFields: " + fDoubleFields.toString());
- logger.debug("fIntegerFields: " + fIntegerFields.toString());
- logger.debug("fOtherFields: " + fOtherFields.toString());
-
- }
-
- private String getType(final int position, final String assignment) {
- fVariableTypeString = "double";
-
- try {
-
- IBuffer buffer = fCompilationUnit.getBuffer();
- buffer.replace(position, 0, assignment);
- fCompilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
-
- // logger.debug("CopySource" + copy.getSource());
-
- CompilationUnit unit = (CompilationUnit) createAST(fCompilationUnit);
- unit.accept(new ASTVisitor() {
- @Override
- public boolean visit(Assignment node) {
- int startPosition = node.getStartPosition();
- if (startPosition >= position
- && startPosition < (position + assignment.length())) {
- Expression rightSide = node.getRightHandSide();
- logger.debug("expr: " + rightSide.toString());
- ITypeBinding typeBinding = rightSide
- .resolveTypeBinding();
- if (typeBinding != null) {
- fVariableTypeString = rightSide
- .resolveTypeBinding().getName();
- logger.debug("expr type: " + fVariableTypeString);
- } else
- logger.debug("expr type: undefined variable");
- }
-
- return true;
- }
- });
-
- buffer.replace(position, assignment.length(), "");
- fCompilationUnit.reconcile(AST.JLS4, false, null, null);
-
- } catch (JavaModelException e) {
- e.printStackTrace();
- }
-
- logger.debug("Type: " + fVariableTypeString);
-
- if (fVariableTypeString.matches("double"))
- fVariableType = VariableType.DOUBLE;
- else if (fVariableTypeString.matches("int")) {
- /*
- * If user want's use integer variables, he should define it before
- */
- // fVariableType = VariableType.INT;
- fVariableTypeString = "double";
- fVariableType = VariableType.DOUBLE;
- } else if (fVariableTypeString.matches("Matrix"))
- fVariableType = VariableType.MATRIX;
- else
- fVariableType = VariableType.OTHER;
+ logger.debug("fFields: " + fFields.toString());
- return fVariableTypeString;
}
private static String translateName(String name) {
diff --git a/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/TexTranslator.java b/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/TexTranslator.java
index 2a4d5c7f..12b35990 100644
--- a/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/TexTranslator.java
+++ b/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/TexTranslator.java
@@ -70,9 +70,8 @@ public String visitFunctionDefinition(
return visitStandardFunction(ctx.name) + "=" + visit(ctx.value);
}
- public String visitVariableAssignment(
- MathParser.VariableAssignmentContext ctx) {
- return visit(ctx.name) + "=" + visit(ctx.value);
+ public String visitVariableAssignment(MathParser.VariableAssignmentContext ctx) {
+ return translateName(ctx.name.getText()) + "=" + visit(ctx.value);
}
public String visitLogicComparison(MathParser.LogicComparisonContext ctx) {
diff --git a/org.eclipse.iee.translator.antlr/templates/matrix.st b/org.eclipse.iee.translator.antlr/templates/matrix.st
index 5f8c0dcc..eb7a9e6c 100644
--- a/org.eclipse.iee.translator.antlr/templates/matrix.st
+++ b/org.eclipse.iee.translator.antlr/templates/matrix.st
@@ -1,31 +1,23 @@
-
-matrix(type, id, variable, path) ::= <<
- new Runnable() {
- private <type> variable;
- private Runnable init (<type> var)
+matrix(id, variable) ::= <<
+{
+ Jama.Matrix tmpMtx = <variable>;
+ int i=0, j=0; String matrix = "{";
+ for (i = 0; i \< tmpMtx.getRowDimension(); i++)
+ {
+ matrix += "{";
+
+ for (j = 0; j \< tmpMtx.getColumnDimension(); j++)
{
- variable = var; return this;
+ matrix += tmpMtx.get(i,j);
+ if (j != tmpMtx.getColumnDimension() - 1)
+ matrix += ",";
+ else
+ matrix += "}";
}
- @Override
- public void run() {
- int i=0, j=0; String matrix = "{";
- for (i = 0; i \< variable.getRowDimension(); i++)
- {
- matrix += "{";
-
- for (j = 0; j \< variable.getColumnDimension(); j++)
- {
- matrix += variable.get(i,j);
- if (j != variable.getColumnDimension() - 1)
- matrix += ",";
- else
- matrix += "}";
- }
- if (i != variable.getRowDimension() - 1)
- matrix += ",";
- }
- matrix += "}";
- org.eclipse.iee.core.EvaluationContextHolder.putResult("<id>", String.valueOf(matrix));
- }
- }.init(<variable>).run();
+ if (i != tmpMtx.getRowDimension() - 1)
+ matrix += ",";
+ }
+ matrix += "}";
+ org.eclipse.iee.core.EvaluationContextHolder.putResult("<id>", String.valueOf(matrix));
+}
>>
diff --git a/org.eclipse.iee.translator.antlr/templates/variable.st b/org.eclipse.iee.translator.antlr/templates/variable.st
index c99a4172..7f14a673 100644
--- a/org.eclipse.iee.translator.antlr/templates/variable.st
+++ b/org.eclipse.iee.translator.antlr/templates/variable.st
@@ -1,14 +1,6 @@
-variable(type, id, variable, path) ::= <<
- new Runnable() {
- private <type> variable;
- private Runnable init (<type> var)
- {
- variable = var;return this;
- }
- @Override
- public void run() {
- org.eclipse.iee.core.EvaluationContextHolder.putResult("<id>", String.valueOf(variable));
- }
- }.init(<variable>).run();
+variable(id, variable) ::= <<
+{
+ org.eclipse.iee.core.EvaluationContextHolder.putResult("<id>", String.valueOf(<variable>));
+}
>>
\ No newline at end of file
|
50ac59fa8530bbd35c21cd61cfd64d2bd7d3eb57
|
hbase
|
HBASE-11558 Caching set on Scan object gets lost- when using TableMapReduceUtil in 0.95+ (Ishan Chhabra)--
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java
index f7531eec052e..eea3b72fe79e 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ProtobufUtil.java
@@ -904,6 +904,9 @@ public static ClientProtos.Scan toScan(
if (scan.getConsistency() == Consistency.TIMELINE) {
scanBuilder.setConsistency(toConsistency(scan.getConsistency()));
}
+ if (scan.getCaching() > 0) {
+ scanBuilder.setCaching(scan.getCaching());
+ }
return scanBuilder.build();
}
@@ -986,6 +989,9 @@ public static Scan toScan(
if (proto.hasConsistency()) {
scan.setConsistency(toConsistency(proto.getConsistency()));
}
+ if (proto.hasCaching()) {
+ scan.setCaching(proto.getCaching());
+ }
return scan;
}
diff --git a/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java b/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java
index 6956b310b154..c197eb706c95 100644
--- a/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java
+++ b/hbase-protocol/src/main/java/org/apache/hadoop/hbase/protobuf/generated/ClientProtos.java
@@ -13658,6 +13658,16 @@ org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameBytesPairOrBuilder ge
* <code>optional .Consistency consistency = 16 [default = STRONG];</code>
*/
org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Consistency getConsistency();
+
+ // optional uint32 caching = 17;
+ /**
+ * <code>optional uint32 caching = 17;</code>
+ */
+ boolean hasCaching();
+ /**
+ * <code>optional uint32 caching = 17;</code>
+ */
+ int getCaching();
}
/**
* Protobuf type {@code Scan}
@@ -13829,6 +13839,11 @@ private Scan(
}
break;
}
+ case 136: {
+ bitField0_ |= 0x00004000;
+ caching_ = input.readUInt32();
+ break;
+ }
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
@@ -14191,6 +14206,22 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Consistency getCo
return consistency_;
}
+ // optional uint32 caching = 17;
+ public static final int CACHING_FIELD_NUMBER = 17;
+ private int caching_;
+ /**
+ * <code>optional uint32 caching = 17;</code>
+ */
+ public boolean hasCaching() {
+ return ((bitField0_ & 0x00004000) == 0x00004000);
+ }
+ /**
+ * <code>optional uint32 caching = 17;</code>
+ */
+ public int getCaching() {
+ return caching_;
+ }
+
private void initFields() {
column_ = java.util.Collections.emptyList();
attribute_ = java.util.Collections.emptyList();
@@ -14208,6 +14239,7 @@ private void initFields() {
small_ = false;
reversed_ = false;
consistency_ = org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Consistency.STRONG;
+ caching_ = 0;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
@@ -14287,6 +14319,9 @@ public void writeTo(com.google.protobuf.CodedOutputStream output)
if (((bitField0_ & 0x00002000) == 0x00002000)) {
output.writeEnum(16, consistency_.getNumber());
}
+ if (((bitField0_ & 0x00004000) == 0x00004000)) {
+ output.writeUInt32(17, caching_);
+ }
getUnknownFields().writeTo(output);
}
@@ -14360,6 +14395,10 @@ public int getSerializedSize() {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(16, consistency_.getNumber());
}
+ if (((bitField0_ & 0x00004000) == 0x00004000)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeUInt32Size(17, caching_);
+ }
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
@@ -14457,6 +14496,11 @@ public boolean equals(final java.lang.Object obj) {
result = result &&
(getConsistency() == other.getConsistency());
}
+ result = result && (hasCaching() == other.hasCaching());
+ if (hasCaching()) {
+ result = result && (getCaching()
+ == other.getCaching());
+ }
result = result &&
getUnknownFields().equals(other.getUnknownFields());
return result;
@@ -14534,6 +14578,10 @@ public int hashCode() {
hash = (37 * hash) + CONSISTENCY_FIELD_NUMBER;
hash = (53 * hash) + hashEnum(getConsistency());
}
+ if (hasCaching()) {
+ hash = (37 * hash) + CACHING_FIELD_NUMBER;
+ hash = (53 * hash) + getCaching();
+ }
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
@@ -14706,6 +14754,8 @@ public Builder clear() {
bitField0_ = (bitField0_ & ~0x00004000);
consistency_ = org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Consistency.STRONG;
bitField0_ = (bitField0_ & ~0x00008000);
+ caching_ = 0;
+ bitField0_ = (bitField0_ & ~0x00010000);
return this;
}
@@ -14816,6 +14866,10 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Scan buildPartial
to_bitField0_ |= 0x00002000;
}
result.consistency_ = consistency_;
+ if (((from_bitField0_ & 0x00010000) == 0x00010000)) {
+ to_bitField0_ |= 0x00004000;
+ }
+ result.caching_ = caching_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
@@ -14926,6 +14980,9 @@ public Builder mergeFrom(org.apache.hadoop.hbase.protobuf.generated.ClientProtos
if (other.hasConsistency()) {
setConsistency(other.getConsistency());
}
+ if (other.hasCaching()) {
+ setCaching(other.getCaching());
+ }
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
@@ -16106,6 +16163,39 @@ public Builder clearConsistency() {
return this;
}
+ // optional uint32 caching = 17;
+ private int caching_ ;
+ /**
+ * <code>optional uint32 caching = 17;</code>
+ */
+ public boolean hasCaching() {
+ return ((bitField0_ & 0x00010000) == 0x00010000);
+ }
+ /**
+ * <code>optional uint32 caching = 17;</code>
+ */
+ public int getCaching() {
+ return caching_;
+ }
+ /**
+ * <code>optional uint32 caching = 17;</code>
+ */
+ public Builder setCaching(int value) {
+ bitField0_ |= 0x00010000;
+ caching_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * <code>optional uint32 caching = 17;</code>
+ */
+ public Builder clearCaching() {
+ bitField0_ = (bitField0_ & ~0x00010000);
+ caching_ = 0;
+ onChanged();
+ return this;
+ }
+
// @@protoc_insertion_point(builder_scope:Scan)
}
@@ -30643,7 +30733,7 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiResponse mul
"(\0132\016.MutationProto\022\035\n\tcondition\030\003 \001(\0132\n." +
"Condition\022\023\n\013nonce_group\030\004 \001(\004\"<\n\016Mutate" +
"Response\022\027\n\006result\030\001 \001(\0132\007.Result\022\021\n\tpro" +
- "cessed\030\002 \001(\010\"\250\003\n\004Scan\022\027\n\006column\030\001 \003(\0132\007." +
+ "cessed\030\002 \001(\010\"\271\003\n\004Scan\022\027\n\006column\030\001 \003(\0132\007." +
"Column\022!\n\tattribute\030\002 \003(\0132\016.NameBytesPai" +
"r\022\021\n\tstart_row\030\003 \001(\014\022\020\n\010stop_row\030\004 \001(\014\022\027",
"\n\006filter\030\005 \001(\0132\007.Filter\022\036\n\ntime_range\030\006 " +
@@ -30653,55 +30743,55 @@ public org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiResponse mul
"re_limit\030\013 \001(\r\022\024\n\014store_offset\030\014 \001(\r\022&\n\036" +
"load_column_families_on_demand\030\r \001(\010\022\r\n\005" +
"small\030\016 \001(\010\022\027\n\010reversed\030\017 \001(\010:\005false\022)\n\013" +
- "consistency\030\020 \001(\0162\014.Consistency:\006STRONG\"" +
- "\236\001\n\013ScanRequest\022 \n\006region\030\001 \001(\0132\020.Region" +
- "Specifier\022\023\n\004scan\030\002 \001(\0132\005.Scan\022\022\n\nscanne",
- "r_id\030\003 \001(\004\022\026\n\016number_of_rows\030\004 \001(\r\022\025\n\rcl" +
- "ose_scanner\030\005 \001(\010\022\025\n\rnext_call_seq\030\006 \001(\004" +
- "\"\210\001\n\014ScanResponse\022\030\n\020cells_per_result\030\001 " +
- "\003(\r\022\022\n\nscanner_id\030\002 \001(\004\022\024\n\014more_results\030" +
- "\003 \001(\010\022\013\n\003ttl\030\004 \001(\r\022\030\n\007results\030\005 \003(\0132\007.Re" +
- "sult\022\r\n\005stale\030\006 \001(\010\"\263\001\n\024BulkLoadHFileReq" +
- "uest\022 \n\006region\030\001 \002(\0132\020.RegionSpecifier\0225" +
- "\n\013family_path\030\002 \003(\0132 .BulkLoadHFileReque" +
- "st.FamilyPath\022\026\n\016assign_seq_num\030\003 \001(\010\032*\n" +
- "\nFamilyPath\022\016\n\006family\030\001 \002(\014\022\014\n\004path\030\002 \002(",
- "\t\"\'\n\025BulkLoadHFileResponse\022\016\n\006loaded\030\001 \002" +
- "(\010\"a\n\026CoprocessorServiceCall\022\013\n\003row\030\001 \002(" +
- "\014\022\024\n\014service_name\030\002 \002(\t\022\023\n\013method_name\030\003" +
- " \002(\t\022\017\n\007request\030\004 \002(\014\"9\n\030CoprocessorServ" +
- "iceResult\022\035\n\005value\030\001 \001(\0132\016.NameBytesPair" +
- "\"d\n\031CoprocessorServiceRequest\022 \n\006region\030" +
- "\001 \002(\0132\020.RegionSpecifier\022%\n\004call\030\002 \002(\0132\027." +
- "CoprocessorServiceCall\"]\n\032CoprocessorSer" +
- "viceResponse\022 \n\006region\030\001 \002(\0132\020.RegionSpe" +
- "cifier\022\035\n\005value\030\002 \002(\0132\016.NameBytesPair\"{\n",
- "\006Action\022\r\n\005index\030\001 \001(\r\022 \n\010mutation\030\002 \001(\013" +
- "2\016.MutationProto\022\021\n\003get\030\003 \001(\0132\004.Get\022-\n\014s" +
- "ervice_call\030\004 \001(\0132\027.CoprocessorServiceCa" +
- "ll\"Y\n\014RegionAction\022 \n\006region\030\001 \002(\0132\020.Reg" +
- "ionSpecifier\022\016\n\006atomic\030\002 \001(\010\022\027\n\006action\030\003" +
- " \003(\0132\007.Action\"\221\001\n\021ResultOrException\022\r\n\005i" +
- "ndex\030\001 \001(\r\022\027\n\006result\030\002 \001(\0132\007.Result\022!\n\te" +
- "xception\030\003 \001(\0132\016.NameBytesPair\0221\n\016servic" +
- "e_result\030\004 \001(\0132\031.CoprocessorServiceResul" +
- "t\"f\n\022RegionActionResult\022-\n\021resultOrExcep",
- "tion\030\001 \003(\0132\022.ResultOrException\022!\n\texcept" +
- "ion\030\002 \001(\0132\016.NameBytesPair\"G\n\014MultiReques" +
- "t\022#\n\014regionAction\030\001 \003(\0132\r.RegionAction\022\022" +
- "\n\nnonceGroup\030\002 \001(\004\"@\n\rMultiResponse\022/\n\022r" +
- "egionActionResult\030\001 \003(\0132\023.RegionActionRe" +
- "sult*\'\n\013Consistency\022\n\n\006STRONG\020\000\022\014\n\010TIMEL" +
- "INE\020\0012\261\002\n\rClientService\022 \n\003Get\022\013.GetRequ" +
- "est\032\014.GetResponse\022)\n\006Mutate\022\016.MutateRequ" +
- "est\032\017.MutateResponse\022#\n\004Scan\022\014.ScanReque" +
- "st\032\r.ScanResponse\022>\n\rBulkLoadHFile\022\025.Bul",
- "kLoadHFileRequest\032\026.BulkLoadHFileRespons" +
- "e\022F\n\013ExecService\022\032.CoprocessorServiceReq" +
- "uest\032\033.CoprocessorServiceResponse\022&\n\005Mul" +
- "ti\022\r.MultiRequest\032\016.MultiResponseBB\n*org" +
- ".apache.hadoop.hbase.protobuf.generatedB" +
- "\014ClientProtosH\001\210\001\001\240\001\001"
+ "consistency\030\020 \001(\0162\014.Consistency:\006STRONG\022" +
+ "\017\n\007caching\030\021 \001(\r\"\236\001\n\013ScanRequest\022 \n\006regi" +
+ "on\030\001 \001(\0132\020.RegionSpecifier\022\023\n\004scan\030\002 \001(\013",
+ "2\005.Scan\022\022\n\nscanner_id\030\003 \001(\004\022\026\n\016number_of" +
+ "_rows\030\004 \001(\r\022\025\n\rclose_scanner\030\005 \001(\010\022\025\n\rne" +
+ "xt_call_seq\030\006 \001(\004\"\210\001\n\014ScanResponse\022\030\n\020ce" +
+ "lls_per_result\030\001 \003(\r\022\022\n\nscanner_id\030\002 \001(\004" +
+ "\022\024\n\014more_results\030\003 \001(\010\022\013\n\003ttl\030\004 \001(\r\022\030\n\007r" +
+ "esults\030\005 \003(\0132\007.Result\022\r\n\005stale\030\006 \001(\010\"\263\001\n" +
+ "\024BulkLoadHFileRequest\022 \n\006region\030\001 \002(\0132\020." +
+ "RegionSpecifier\0225\n\013family_path\030\002 \003(\0132 .B" +
+ "ulkLoadHFileRequest.FamilyPath\022\026\n\016assign" +
+ "_seq_num\030\003 \001(\010\032*\n\nFamilyPath\022\016\n\006family\030\001",
+ " \002(\014\022\014\n\004path\030\002 \002(\t\"\'\n\025BulkLoadHFileRespo" +
+ "nse\022\016\n\006loaded\030\001 \002(\010\"a\n\026CoprocessorServic" +
+ "eCall\022\013\n\003row\030\001 \002(\014\022\024\n\014service_name\030\002 \002(\t" +
+ "\022\023\n\013method_name\030\003 \002(\t\022\017\n\007request\030\004 \002(\014\"9" +
+ "\n\030CoprocessorServiceResult\022\035\n\005value\030\001 \001(" +
+ "\0132\016.NameBytesPair\"d\n\031CoprocessorServiceR" +
+ "equest\022 \n\006region\030\001 \002(\0132\020.RegionSpecifier" +
+ "\022%\n\004call\030\002 \002(\0132\027.CoprocessorServiceCall\"" +
+ "]\n\032CoprocessorServiceResponse\022 \n\006region\030" +
+ "\001 \002(\0132\020.RegionSpecifier\022\035\n\005value\030\002 \002(\0132\016",
+ ".NameBytesPair\"{\n\006Action\022\r\n\005index\030\001 \001(\r\022" +
+ " \n\010mutation\030\002 \001(\0132\016.MutationProto\022\021\n\003get" +
+ "\030\003 \001(\0132\004.Get\022-\n\014service_call\030\004 \001(\0132\027.Cop" +
+ "rocessorServiceCall\"Y\n\014RegionAction\022 \n\006r" +
+ "egion\030\001 \002(\0132\020.RegionSpecifier\022\016\n\006atomic\030" +
+ "\002 \001(\010\022\027\n\006action\030\003 \003(\0132\007.Action\"\221\001\n\021Resul" +
+ "tOrException\022\r\n\005index\030\001 \001(\r\022\027\n\006result\030\002 " +
+ "\001(\0132\007.Result\022!\n\texception\030\003 \001(\0132\016.NameBy" +
+ "tesPair\0221\n\016service_result\030\004 \001(\0132\031.Coproc" +
+ "essorServiceResult\"f\n\022RegionActionResult",
+ "\022-\n\021resultOrException\030\001 \003(\0132\022.ResultOrEx" +
+ "ception\022!\n\texception\030\002 \001(\0132\016.NameBytesPa" +
+ "ir\"G\n\014MultiRequest\022#\n\014regionAction\030\001 \003(\013" +
+ "2\r.RegionAction\022\022\n\nnonceGroup\030\002 \001(\004\"@\n\rM" +
+ "ultiResponse\022/\n\022regionActionResult\030\001 \003(\013" +
+ "2\023.RegionActionResult*\'\n\013Consistency\022\n\n\006" +
+ "STRONG\020\000\022\014\n\010TIMELINE\020\0012\261\002\n\rClientService" +
+ "\022 \n\003Get\022\013.GetRequest\032\014.GetResponse\022)\n\006Mu" +
+ "tate\022\016.MutateRequest\032\017.MutateResponse\022#\n" +
+ "\004Scan\022\014.ScanRequest\032\r.ScanResponse\022>\n\rBu",
+ "lkLoadHFile\022\025.BulkLoadHFileRequest\032\026.Bul" +
+ "kLoadHFileResponse\022F\n\013ExecService\022\032.Copr" +
+ "ocessorServiceRequest\032\033.CoprocessorServi" +
+ "ceResponse\022&\n\005Multi\022\r.MultiRequest\032\016.Mul" +
+ "tiResponseBB\n*org.apache.hadoop.hbase.pr" +
+ "otobuf.generatedB\014ClientProtosH\001\210\001\001\240\001\001"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
@@ -30791,7 +30881,7 @@ public com.google.protobuf.ExtensionRegistry assignDescriptors(
internal_static_Scan_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Scan_descriptor,
- new java.lang.String[] { "Column", "Attribute", "StartRow", "StopRow", "Filter", "TimeRange", "MaxVersions", "CacheBlocks", "BatchSize", "MaxResultSize", "StoreLimit", "StoreOffset", "LoadColumnFamiliesOnDemand", "Small", "Reversed", "Consistency", });
+ new java.lang.String[] { "Column", "Attribute", "StartRow", "StopRow", "Filter", "TimeRange", "MaxVersions", "CacheBlocks", "BatchSize", "MaxResultSize", "StoreLimit", "StoreOffset", "LoadColumnFamiliesOnDemand", "Small", "Reversed", "Consistency", "Caching", });
internal_static_ScanRequest_descriptor =
getDescriptor().getMessageTypes().get(12);
internal_static_ScanRequest_fieldAccessorTable = new
diff --git a/hbase-protocol/src/main/protobuf/Client.proto b/hbase-protocol/src/main/protobuf/Client.proto
index 8c71ef1018dc..9eedd1b0c903 100644
--- a/hbase-protocol/src/main/protobuf/Client.proto
+++ b/hbase-protocol/src/main/protobuf/Client.proto
@@ -247,6 +247,7 @@ message Scan {
optional bool small = 14;
optional bool reversed = 15 [default = false];
optional Consistency consistency = 16 [default = STRONG];
+ optional uint32 caching = 17;
}
/**
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/protobuf/TestProtobufUtil.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/protobuf/TestProtobufUtil.java
index f4b71f788fd1..d51f007f8ed0 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/protobuf/TestProtobufUtil.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/protobuf/TestProtobufUtil.java
@@ -291,15 +291,21 @@ public void testScan() throws IOException {
scanBuilder.addColumn(columnBuilder.build());
ClientProtos.Scan proto = scanBuilder.build();
- // default fields
+
+ // Verify default values
assertEquals(1, proto.getMaxVersions());
assertEquals(true, proto.getCacheBlocks());
+ // Verify fields survive ClientProtos.Scan -> Scan -> ClientProtos.Scan
+ // conversion
scanBuilder = ClientProtos.Scan.newBuilder(proto);
- scanBuilder.setMaxVersions(1);
- scanBuilder.setCacheBlocks(true);
-
- Scan scan = ProtobufUtil.toScan(proto);
- assertEquals(scanBuilder.build(), ProtobufUtil.toScan(scan));
+ scanBuilder.setMaxVersions(2);
+ scanBuilder.setCacheBlocks(false);
+ scanBuilder.setCaching(1024);
+ ClientProtos.Scan expectedProto = scanBuilder.build();
+
+ ClientProtos.Scan actualProto = ProtobufUtil.toScan(
+ ProtobufUtil.toScan(expectedProto));
+ assertEquals(expectedProto, actualProto);
}
}
|
bd1b559d47603748f6d57a0ff21f68505258ace5
|
spring-framework
|
MockHttpServletResponse supports multiple- includes (SPR-
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java
index 6256bbe51632..6d220572665d 100644
--- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java
+++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.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.
@@ -98,7 +98,7 @@ public class MockHttpServletResponse implements HttpServletResponse {
private String forwardedUrl;
- private String includedUrl;
+ private final List<String> includedUrls = new ArrayList<String>();
//---------------------------------------------------------------------
@@ -443,11 +443,28 @@ public String getForwardedUrl() {
}
public void setIncludedUrl(String includedUrl) {
- this.includedUrl = includedUrl;
+ this.includedUrls.clear();
+ if (includedUrl != null) {
+ this.includedUrls.add(includedUrl);
+ }
}
public String getIncludedUrl() {
- return this.includedUrl;
+ int count = this.includedUrls.size();
+ if (count > 1) {
+ throw new IllegalStateException(
+ "More than 1 URL included - check getIncludedUrls instead: " + this.includedUrls);
+ }
+ return (count == 1 ? this.includedUrls.get(0) : null);
+ }
+
+ public void addIncludedUrl(String includedUrl) {
+ Assert.notNull(includedUrl, "Included URL must not be null");
+ this.includedUrls.add(includedUrl);
+ }
+
+ public List<String> getIncludedUrls() {
+ return this.includedUrls;
}
diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java
index 17485d21f381..a87bea43c91c 100644
--- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java
+++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.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.
@@ -68,7 +68,7 @@ public void forward(ServletRequest request, ServletResponse response) {
public void include(ServletRequest request, ServletResponse response) {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
- getMockHttpServletResponse(response).setIncludedUrl(this.url);
+ getMockHttpServletResponse(response).addIncludedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockRequestDispatcher: including URL [" + this.url + "]");
}
|
3b0abce3ca9939dc953877cb06942bc716e82cfd
|
Delta Spike
|
DELTASPIKE-745 add TCK test for parallel threads
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/cdictrl/tck/src/main/java/org/apache/deltaspike/cdise/tck/ContainerCtrlTckTest.java b/deltaspike/cdictrl/tck/src/main/java/org/apache/deltaspike/cdise/tck/ContainerCtrlTckTest.java
index e71921050..388ff2c9f 100644
--- a/deltaspike/cdictrl/tck/src/main/java/org/apache/deltaspike/cdise/tck/ContainerCtrlTckTest.java
+++ b/deltaspike/cdictrl/tck/src/main/java/org/apache/deltaspike/cdise/tck/ContainerCtrlTckTest.java
@@ -20,13 +20,19 @@
import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import javax.enterprise.context.ContextNotActiveException;
+import javax.enterprise.context.RequestScoped;
+import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import org.apache.deltaspike.cdise.api.CdiContainer;
import org.apache.deltaspike.cdise.api.CdiContainerLoader;
+import org.apache.deltaspike.cdise.api.ContextControl;
import org.apache.deltaspike.cdise.tck.beans.Car;
import org.apache.deltaspike.cdise.tck.beans.CarRepair;
import org.apache.deltaspike.cdise.tck.beans.TestUser;
@@ -43,6 +49,8 @@
*/
public class ContainerCtrlTckTest
{
+ private static final Logger log = Logger.getLogger(ContainerCtrlTckTest.class.getName());
+ private static final int NUM_THREADS = 100;
@Rule
public VersionControlRule versionControlRule = new VersionControlRule();
@@ -71,6 +79,80 @@ public void testContainerBoot()
cc.shutdown();
}
+ @Test
+ public void testParallelThreadExecution() throws Exception
+ {
+ final CdiContainer cc = CdiContainerLoader.getCdiContainer();
+ Assert.assertNotNull(cc);
+
+ cc.boot();
+ cc.getContextControl().startContexts();
+
+ final BeanManager bm = cc.getBeanManager();
+ Assert.assertNotNull(bm);
+
+ final AtomicInteger numErrors = new AtomicInteger(0);
+
+ Runnable runnable = new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ ContextControl contextControl = cc.getContextControl();
+ contextControl.startContext(SessionScoped.class);
+ contextControl.startContext(RequestScoped.class);
+
+
+ Set<Bean<?>> beans = bm.getBeans(CarRepair.class);
+ Bean<?> bean = bm.resolve(beans);
+
+ CarRepair carRepair = (CarRepair)
+ bm.getReference(bean, CarRepair.class, bm.createCreationalContext(bean));
+ Assert.assertNotNull(carRepair);
+
+ try
+ {
+ for (int i = 0; i < 100000; i++)
+ {
+ // we need the threads doing something ;)
+ Assert.assertNotNull(carRepair.getCar());
+ Assert.assertNotNull(carRepair.getCar().getUser());
+ Assert.assertNotNull(carRepair.getCar().getUser().getName());
+ }
+ }
+ catch (Exception e)
+ {
+ log.log(Level.SEVERE, "An exception happened on a new worker thread", e);
+ numErrors.incrementAndGet();
+ }
+ contextControl.stopContext(RequestScoped.class);
+ contextControl.stopContext(SessionScoped.class);
+ }
+ };
+
+
+ Thread[] threads = new Thread[NUM_THREADS];
+ for (int i = 0 ; i < NUM_THREADS; i++)
+ {
+ threads[i] = new Thread(runnable);
+ }
+
+ for (int i = 0 ; i < NUM_THREADS; i++)
+ {
+ threads[i].start();
+ }
+
+ for (int i = 0 ; i < NUM_THREADS; i++)
+ {
+ threads[i].join();
+ }
+
+ Assert.assertEquals("An error happened while executing parallel threads", 0, numErrors.get());
+
+
+ cc.shutdown();
+ }
+
@Test
public void testSimpleContainerBoot()
{
|
d074c686b3ba0ba6843d0a25dca5ac991f919e68
|
hadoop
|
HADOOP-6139. Fix the FsShell help messages for rm- and rmr. Contributed by Jakob Homan--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@793098 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 9979aefe66ab8..c70d07c0fbf23 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1011,6 +1011,9 @@ Release 0.20.1 - Unreleased
HADOOP-5920. Fixes a testcase failure for TestJobHistory.
(Amar Kamat via ddas)
+ HADOOP-6139. Fix the FsShell help messages for rm and rmr. (Jakob Homan
+ via szetszwo)
+
Release 0.20.0 - 2009-04-15
INCOMPATIBLE CHANGES
diff --git a/src/java/org/apache/hadoop/fs/FsShell.java b/src/java/org/apache/hadoop/fs/FsShell.java
index 3af28dc13e441..634da87da000e 100644
--- a/src/java/org/apache/hadoop/fs/FsShell.java
+++ b/src/java/org/apache/hadoop/fs/FsShell.java
@@ -1679,7 +1679,6 @@ private static void printUsage(String cmd) {
" [-D <[property=value>]");
} else if ("-ls".equals(cmd) || "-lsr".equals(cmd) ||
"-du".equals(cmd) || "-dus".equals(cmd) ||
- "-rm".equals(cmd) || "-rmr".equals(cmd) ||
"-touchz".equals(cmd) || "-mkdir".equals(cmd) ||
"-text".equals(cmd)) {
System.err.println("Usage: java FsShell" +
@@ -1689,6 +1688,9 @@ private static void printUsage(String cmd) {
" [" + cmd + " [<path>]]");
} else if (Count.matches(cmd)) {
System.err.println(prefix + " [" + Count.USAGE + "]");
+ } else if ("-rm".equals(cmd) || "-rmr".equals(cmd)) {
+ System.err.println("Usage: java FsShell [" + cmd +
+ " [-skipTrash] <src>]");
} else if ("-mv".equals(cmd) || "-cp".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [" + cmd + " <src> <dst>]");
|
058d4d4b5ffe40b8e93c7593f0b5346373455480
|
camel
|
CAMEL-3788 Merged the patch into camel-http4--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1083724 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java b/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java
index cf24b151c985a..8de7b8d7aca64 100644
--- a/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java
+++ b/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java
@@ -127,11 +127,13 @@ public HttpEndpoint getEndpoint() {
protected void populateResponse(Exchange exchange, HttpRequestBase httpRequest, HttpResponse httpResponse,
Message in, HeaderFilterStrategy strategy, int responseCode) throws IOException, ClassNotFoundException {
+ // We just make the out message is not create when extractResponseBody throws exception
+ Object response = extractResponseBody(httpRequest, httpResponse, exchange);
Message answer = exchange.getOut();
answer.setHeaders(in.getHeaders());
answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
- answer.setBody(extractResponseBody(httpRequest, httpResponse, exchange));
+ answer.setBody(response);
// propagate HTTP response headers
Header[] headers = httpResponse.getAllHeaders();
|
5b500c684ff416cf88937999b1205dd66d48bc67
|
orientdb
|
Removed old code to handle temporary records in- indexes--
|
p
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
index ec82eb5bed3..be590f0944c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
@@ -17,7 +17,6 @@
import java.util.Collection;
import java.util.Collections;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map.Entry;
@@ -62,7 +61,6 @@ public abstract class OIndexMVRBTreeAbstract extends OSharedResource implements
protected Set<String> clustersToIndex = new LinkedHashSet<String>();
protected OIndexCallback callback;
protected boolean automatic;
- protected Set<Object> tempItems = new HashSet<Object>();
@ODocumentInstance
protected ODocument configuration;
@@ -533,29 +531,7 @@ public void onAfterTxRollback(ODatabase iDatabase) {
public void onBeforeTxCommit(ODatabase iDatabase) {
}
- /**
- * Reset documents into the set to update its hashcode.
- */
public void onAfterTxCommit(ODatabase iDatabase) {
- acquireExclusiveLock();
-
- try {
- if (tempItems.size() > 0) {
- for (Object key : tempItems) {
- Set<OIdentifiable> set = map.get(key);
- if (set != null) {
- // RE-ADD ALL THE ITEM TO UPDATE THE HASHCODE (CHANGED AFTER SAVE+COMMIT)
- final ORecordLazySet newSet = new ORecordLazySet(configuration.getDatabase());
- newSet.addAll(set);
- map.put(key, newSet);
- }
- }
- }
- tempItems.clear();
-
- } finally {
- releaseExclusiveLock();
- }
}
public void onClose(ODatabase iDatabase) {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexNotUnique.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexNotUnique.java
index 34802bfeb47..33324ea2669 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexNotUnique.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexNotUnique.java
@@ -43,9 +43,6 @@ public OIndex put(final Object iKey, final ORecord<?> iSingleValue) {
if (!iSingleValue.getIdentity().isValid())
iSingleValue.save();
- if (iSingleValue.getIdentity().isTemporary())
- tempItems.add(iKey);
-
values.add(iSingleValue);
map.put(iKey, values);
|
4dcd9dfe0ea6f9c8a4eef47d6910dd188638e2f6
|
restlet-framework-java
|
Added support of the Authentication-Info header.--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt
index 7e03cc9809..f20b1481f6 100644
--- a/build/tmpl/text/changes.txt
+++ b/build/tmpl/text/changes.txt
@@ -206,6 +206,7 @@ Changes log
204 (success, no content).
- Added support of the warning header.
- Added support of the ranges in the gwt edition.
+ - Added support of the Authentication-Info header.
- Misc
- Added Velocity template in the org.restlet.example project.
Reported by Ben Vesco.
diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java b/modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java
index 3f75ac6e86..dd1b698969 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java
@@ -78,6 +78,8 @@ public void addAdditionalHeaders(Series<Parameter> existingHeaders,
HttpConstants.HEADER_AGE)
|| param.getName().equalsIgnoreCase(
HttpConstants.HEADER_ALLOW)
+ || param.getName().equalsIgnoreCase(
+ HttpConstants.HEADER_AUTHENTICATION_INFO)
|| param.getName().equalsIgnoreCase(
HttpConstants.HEADER_AUTHORIZATION)
|| param.getName().equalsIgnoreCase(
diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java b/modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java
index 2cb53095f1..e71b55f3c2 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java
@@ -282,8 +282,21 @@ public static void addResponseHeaders(Response response,
// Add the Cache-control headers
if (!response.getCacheDirectives().isEmpty()) {
- responseHeaders.add(HttpConstants.HEADER_CACHE_CONTROL, CacheControlUtils
- .format(response.getCacheDirectives()));
+ responseHeaders.add(HttpConstants.HEADER_CACHE_CONTROL,
+ CacheControlUtils.format(response.getCacheDirectives()));
+ }
+
+ // Add the Authentication-Info header
+ if (response.getAuthenticationInfo() != null) {
+ try {
+ responseHeaders.add(HttpConstants.HEADER_AUTHENTICATION_INFO,
+ org.restlet.engine.security.AuthenticatorUtils
+ .formatAuthenticationInfo(response
+ .getAuthenticationInfo()));
+ } catch (IOException e) {
+ Context.getCurrentLogger().log(Level.WARNING,
+ "Unable to write the Authentication-Info header", e);
+ }
}
}
diff --git a/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorUtils.java b/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorUtils.java
index 87c740e43d..b854663332 100644
--- a/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorUtils.java
+++ b/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorUtils.java
@@ -43,6 +43,7 @@
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Parameter;
import org.restlet.engine.Engine;
+import org.restlet.engine.http.HeaderBuilder;
import org.restlet.engine.http.HeaderReader;
import org.restlet.engine.http.HttpConstants;
import org.restlet.security.Guard;
@@ -155,6 +156,60 @@ public static void challenge(Response response, boolean stale, Guard guard) {
}
}
+ /**
+ * Formats an authentication information as a HTTP header value. The header
+ * is {@link HttpConstants#HEADER_AUTHENTICATION_INFO}.
+ *
+ * @param info
+ * The authentication information to format.
+ * @return The {@link HttpConstants#HEADER_AUTHENTICATION_INFO} header
+ * value.
+ * @throws IOException
+ */
+ public static String formatAuthenticationInfo(AuthenticationInfo info)
+ throws IOException {
+ HeaderBuilder hb = new HeaderBuilder();
+ boolean firstParameter = true;
+
+ if (info != null) {
+ if (info.getNextServerNonce() != null
+ && info.getNextServerNonce().length() > 0) {
+ hb.setFirstParameter(firstParameter);
+ hb
+ .appendQuotedParameter("nextnonce", info
+ .getNextServerNonce());
+ firstParameter = false;
+ }
+ if (info.getQuality() != null && info.getQuality().length() > 0) {
+ hb.setFirstParameter(firstParameter);
+ hb.appendParameter("qop", info.getQuality());
+ firstParameter = false;
+ if (info.getNonceCount() > 0) {
+ StringBuilder result = new StringBuilder(Integer
+ .toHexString(info.getNonceCount()));
+ while (result.length() < 8) {
+ result.insert(0, '0');
+ }
+ hb.appendParameter("nc", result.toString());
+ }
+ }
+ if (info.getResponseDigest() != null
+ && info.getResponseDigest().length() > 0) {
+ hb.setFirstParameter(firstParameter);
+ hb.appendQuotedParameter("rspauth", info.getResponseDigest());
+ firstParameter = false;
+ }
+ if (info.getClientNonce() != null
+ && info.getClientNonce().length() > 0) {
+ hb.setFirstParameter(firstParameter);
+ hb.appendParameter("cnonce", info.getClientNonce());
+ firstParameter = false;
+ }
+ }
+
+ return hb.toString();
+ }
+
/**
* Formats a challenge request as a HTTP header value. The header is
* {@link HttpConstants#HEADER_WWW_AUTHENTICATE}.
@@ -238,41 +293,38 @@ public static String formatResponse(ChallengeResponse challenge,
public static AuthenticationInfo parseAuthenticationInfo(String header) {
AuthenticationInfo result = null;
HeaderReader hr = new HeaderReader(header);
-
try {
- Parameter param;
- param = hr.readParameter();
-
- while (param != null) {
-
- param = hr.readParameter();
- }
-
String nextNonce = null;
- int nonceCount = 0;
- String cnonce = null;
String qop = null;
String responseAuth = null;
+ String cnonce = null;
+ int nonceCount = 0;
- String[] authFields = header.split(",");
- for (String field : authFields) {
- String[] nameValuePair = field.trim().split("=");
- if (nameValuePair[0].equals("nextnonce")) {
- nextNonce = nameValuePair[1];
- } else if (nameValuePair[0].equals("nc")) {
- nonceCount = Integer.parseInt(nameValuePair[1], 16);
- } else if (nameValuePair[0].equals("cnonce")) {
- cnonce = nameValuePair[1];
- if (cnonce.charAt(0) == '"') {
- cnonce = cnonce.substring(1, cnonce.length() - 1);
+ Parameter param = hr.readParameter();
+ while (param != null) {
+ try {
+ if ("nextnonce".equals(param.getName())) {
+ nextNonce = param.getValue();
+ } else if ("qop".equals(param.getName())) {
+ qop = param.getValue();
+ } else if ("rspauth".equals(param.getName())) {
+ responseAuth = param.getValue();
+ } else if ("cnonce".equals(param.getName())) {
+ cnonce = param.getValue();
+ } else if ("nc".equals(param.getName())) {
+ nonceCount = Integer.parseInt(param.getValue(), 16);
}
- } else if (nameValuePair[0].equals("qop")) {
- qop = nameValuePair[1];
- } else if (nameValuePair[0].equals("responseAuth")) {
- responseAuth = nameValuePair[1];
+
+ param = hr.readParameter();
+ } catch (Exception e) {
+ Context
+ .getCurrentLogger()
+ .log(
+ Level.WARNING,
+ "Unable to parse the authentication info header parameter",
+ e);
}
}
-
result = new AuthenticationInfo(nextNonce, nonceCount, cnonce, qop,
responseAuth);
} catch (IOException e) {
|
57ec7d083a68abb23f009f9fdffb80197c138afd
|
hbase
|
HBASE-6400 Add getMasterAdmin() and- getMasterMonitor() to HConnection (Enis)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1363009 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java
index 6161a643388a..b623bc260d39 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java
@@ -33,11 +33,11 @@
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HServerAddress;
import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.MasterAdminProtocol;
+import org.apache.hadoop.hbase.MasterMonitorProtocol;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
-import org.apache.hadoop.hbase.client.AdminProtocol;
-import org.apache.hadoop.hbase.client.ClientProtocol;
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.ipc.CoprocessorProtocol;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
@@ -184,6 +184,17 @@ public HRegionLocation locateRegion(final byte [] regionName)
public List<HRegionLocation> locateRegions(byte[] tableName)
throws IOException;
+ /**
+ * Returns a {@link MasterAdminProtocol} to the active master
+ */
+ public MasterAdminProtocol getMasterAdmin() throws IOException;
+
+ /**
+ * Returns an {@link MasterMonitorProtocol} to the active master
+ */
+ public MasterMonitorProtocol getMasterMonitor() throws IOException;
+
+
/**
* Establishes a connection to the region server at the specified address.
* @param hostname RegionServer hostname
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
index b4af521abc53..632586fb36ae 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
@@ -27,8 +27,18 @@
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.InetSocketAddress;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
import java.util.Map.Entry;
+import java.util.Set;
+import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@@ -52,7 +62,10 @@
import org.apache.hadoop.hbase.HServerAddress;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.MasterAdminProtocol;
+import org.apache.hadoop.hbase.MasterMonitorProtocol;
import org.apache.hadoop.hbase.MasterNotRunningException;
+import org.apache.hadoop.hbase.MasterProtocol;
import org.apache.hadoop.hbase.RegionMovedException;
import org.apache.hadoop.hbase.RemoteExceptionHandler;
import org.apache.hadoop.hbase.ServerName;
@@ -65,11 +78,6 @@
import org.apache.hadoop.hbase.ipc.CoprocessorProtocol;
import org.apache.hadoop.hbase.ipc.ExecRPCInvoker;
import org.apache.hadoop.hbase.ipc.HBaseRPC;
-import org.apache.hadoop.hbase.MasterProtocol;
-import org.apache.hadoop.hbase.MasterMonitorProtocol;
-import org.apache.hadoop.hbase.MasterAdminProtocol;
-import org.apache.hadoop.hbase.client.MasterAdminKeepAliveConnection;
-import org.apache.hadoop.hbase.client.MasterMonitorKeepAliveConnection;
import org.apache.hadoop.hbase.ipc.VersionedProtocol;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.protobuf.RequestConverter;
@@ -77,10 +85,15 @@
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsResponse;
import org.apache.hadoop.hbase.security.User;
-import org.apache.hadoop.hbase.util.*;
-import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
+import org.apache.hadoop.hbase.util.Addressing;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.Pair;
+import org.apache.hadoop.hbase.util.SoftValueSortedMap;
+import org.apache.hadoop.hbase.util.Triple;
+import org.apache.hadoop.hbase.util.Writables;
import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker;
import org.apache.hadoop.hbase.zookeeper.RootRegionTracker;
+import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
import org.apache.hadoop.hbase.zookeeper.ZKTable;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
@@ -1615,6 +1628,16 @@ private Object getKeepAliveMasterProtocol(
}
}
+ @Override
+ public MasterAdminProtocol getMasterAdmin() throws MasterNotRunningException {
+ return getKeepAliveMasterAdmin();
+ };
+
+ @Override
+ public MasterMonitorProtocol getMasterMonitor() throws MasterNotRunningException {
+ return getKeepAliveMasterMonitor();
+ }
+
/**
* This function allows HBaseAdmin and potentially others
* to get a shared MasterAdminProtocol connection.
|
304215665eb630a9c3e722d789e882bf9f59ab21
|
orientdb
|
Fixed issue 800 closing the socket on timeout--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
index adf2bc9ebcf..819195b2761 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
@@ -56,6 +56,10 @@ public void run() {
if (socket == null || socket.isClosed() || socket.isInputShutdown()) {
OLogManager.instance().debug(this, "[OClientConnectionManager] found and removed pending closed channel %d (%s)",
entry.getKey(), socket);
+ try {
+ entry.getValue().close();
+ } catch (Exception e) {
+ }
connections.remove(entry.getKey());
}
}
|
7d14cbcc88e784a0729148713eb86ca3a399ee54
|
d2rq$d2rq
|
Removed the plan package (which was only used for find queries) by inlining its functionality into FindQuery and a new class CompatibleRelationGroup.
|
p
|
https://github.com/d2rq/d2rq
|
diff --git a/src/de/fuberlin/wiwiss/d2rq/find/CompatibleRelationGroup.java b/src/de/fuberlin/wiwiss/d2rq/find/CompatibleRelationGroup.java
new file mode 100644
index 00000000..64b5776a
--- /dev/null
+++ b/src/de/fuberlin/wiwiss/d2rq/find/CompatibleRelationGroup.java
@@ -0,0 +1,96 @@
+package de.fuberlin.wiwiss.d2rq.find;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import de.fuberlin.wiwiss.d2rq.algebra.Relation;
+import de.fuberlin.wiwiss.d2rq.algebra.RelationImpl;
+import de.fuberlin.wiwiss.d2rq.algebra.RelationName;
+import de.fuberlin.wiwiss.d2rq.sql.ResultRow;
+import de.fuberlin.wiwiss.d2rq.sql.TripleMaker;
+
+/**
+ * A group of {@link Relation}s that can be combined into a single
+ * relation without changing the semantics of {@link TripleMaker}s.
+ *
+ * Relations can be combined iff they access the same database and
+ * they contain exactly the same joins and WHERE clauses. If they
+ * both contain no joins, they must contain only columns from the same
+ * table.
+ *
+ * @author Richard Cyganiak ([email protected])
+ * @version $Id: CompatibleRelationGroup.java,v 1.1 2008/08/12 13:07:53 cyganiak Exp $
+ */
+public class CompatibleRelationGroup implements TripleMaker {
+
+ private final List tripleMakers = new ArrayList();
+ private final Relation firstBaseRelation;
+ private boolean allUnique = true;
+ private Set projections = new HashSet();
+
+ public CompatibleRelationGroup(Relation first, TripleMaker tripleMaker) {
+ firstBaseRelation = first;
+ add(first, tripleMaker);
+ }
+
+ public boolean isCompatible(Relation otherRelation) {
+ if (!firstBaseRelation.database().equals(otherRelation.database())) {
+ return false;
+ }
+ if (!firstBaseRelation.joinConditions().equals(otherRelation.joinConditions())) {
+ return false;
+ }
+ if (!firstBaseRelation.condition().equals(otherRelation.condition())) {
+ return false;
+ }
+ Set firstTables = firstBaseRelation.tables();
+ Set secondTables = otherRelation.tables();
+ if (!firstTables.equals(secondTables)) {
+ return false;
+ }
+ Iterator it = firstTables.iterator();
+ while (it.hasNext()) {
+ RelationName tableName = (RelationName) it.next();
+ if (!firstBaseRelation.aliases().originalOf(tableName).equals(
+ otherRelation.aliases().originalOf(tableName))) {
+ return false;
+ }
+ }
+ if (!firstBaseRelation.isUnique() || !otherRelation.isUnique()) {
+ return false;
+ }
+ return true;
+ }
+
+ public void add(Relation relation, TripleMaker tripleMaker) {
+ tripleMakers.add(tripleMaker);
+ projections.addAll(relation.projections());
+ allUnique = allUnique && relation.isUnique();
+ }
+
+ public Relation baseRelation() {
+ if (tripleMakers.size() == 1) {
+ return firstBaseRelation;
+ }
+ return new RelationImpl(firstBaseRelation.database(), firstBaseRelation.aliases(),
+ firstBaseRelation.condition(), firstBaseRelation.joinConditions(),
+ projections, allUnique);
+ }
+
+ public Collection makeTriples(ResultRow row) {
+ if (tripleMakers.size() == 1) {
+ return ((TripleMaker) tripleMakers.get(0)).makeTriples(row);
+ }
+ List result = new ArrayList();
+ Iterator it = this.tripleMakers.iterator();
+ while (it.hasNext()) {
+ TripleMaker relation = (TripleMaker) it.next();
+ result.addAll(relation.makeTriples(row));
+ }
+ return result;
+ }
+}
diff --git a/src/de/fuberlin/wiwiss/d2rq/find/FindQuery.java b/src/de/fuberlin/wiwiss/d2rq/find/FindQuery.java
index e0cbf377..72ec687a 100644
--- a/src/de/fuberlin/wiwiss/d2rq/find/FindQuery.java
+++ b/src/de/fuberlin/wiwiss/d2rq/find/FindQuery.java
@@ -13,13 +13,7 @@
import de.fuberlin.wiwiss.d2rq.algebra.Relation;
import de.fuberlin.wiwiss.d2rq.algebra.TripleRelation;
import de.fuberlin.wiwiss.d2rq.find.URIMakerRule.URIMakerRuleChecker;
-import de.fuberlin.wiwiss.d2rq.plan.ExecuteCompatibleTripleRelations;
-import de.fuberlin.wiwiss.d2rq.plan.ExecuteSequence;
-import de.fuberlin.wiwiss.d2rq.plan.ExecuteTripleRelation;
-import de.fuberlin.wiwiss.d2rq.plan.ExecutionPlanElement;
-import de.fuberlin.wiwiss.d2rq.plan.ExecutionPlanVisitor;
import de.fuberlin.wiwiss.d2rq.sql.RelationToTriplesIterator;
-import de.fuberlin.wiwiss.d2rq.sql.TripleMaker;
/**
@@ -28,7 +22,7 @@
* SQL statement where possible.
*
* @author Richard Cyganiak ([email protected])
- * @version $Id: FindQuery.java,v 1.14 2008/08/12 06:47:37 cyganiak Exp $
+ * @version $Id: FindQuery.java,v 1.15 2008/08/12 13:07:53 cyganiak Exp $
*/
public class FindQuery {
private List compatibleRelations = new ArrayList();
@@ -40,84 +34,40 @@ public FindQuery(Triple triplePattern, Collection propertyBridges) {
URIMakerRuleChecker objectChecker = rule.createRuleChecker(triplePattern.getObject());
Iterator it = propertyBridges.iterator();
while (it.hasNext()) {
- TripleRelation bridge = (TripleRelation) it.next();
- TripleRelation selectionBridge = bridge.selectTriple(triplePattern);
- if (selectionBridge != null
- && subjectChecker.canMatch(bridge.nodeMaker(TripleRelation.SUBJECT_NODE_MAKER))
- && objectChecker.canMatch(bridge.nodeMaker(TripleRelation.OBJECT_NODE_MAKER))) {
- subjectChecker.addPotentialMatch(bridge.nodeMaker(TripleRelation.SUBJECT_NODE_MAKER));
- objectChecker.addPotentialMatch(bridge.nodeMaker(TripleRelation.OBJECT_NODE_MAKER));
- addRelation(new JoinOptimizer(selectionBridge).optimize());
+ TripleRelation tripleRelation = (TripleRelation) it.next();
+ TripleRelation selectedTripleRelation = tripleRelation.selectTriple(triplePattern);
+ if (selectedTripleRelation != null
+ && subjectChecker.canMatch(tripleRelation.nodeMaker(TripleRelation.SUBJECT_NODE_MAKER))
+ && objectChecker.canMatch(tripleRelation.nodeMaker(TripleRelation.OBJECT_NODE_MAKER))) {
+ subjectChecker.addPotentialMatch(tripleRelation.nodeMaker(TripleRelation.SUBJECT_NODE_MAKER));
+ objectChecker.addPotentialMatch(tripleRelation.nodeMaker(TripleRelation.OBJECT_NODE_MAKER));
+ addRelation(new JoinOptimizer(selectedTripleRelation).optimize());
}
}
}
- private void addRelation(TripleRelation relation) {
+ private void addRelation(TripleRelation tripleRelation) {
Iterator it = this.compatibleRelations.iterator();
while (it.hasNext()) {
- List queries = (List) it.next();
- if (ExecuteCompatibleTripleRelations.areCompatible(
- ((TripleRelation) queries.get(0)).baseRelation(),
- relation.baseRelation())) {
- queries.add(relation);
+ CompatibleRelationGroup group = (CompatibleRelationGroup) it.next();
+ if (group.isCompatible(tripleRelation.baseRelation())) {
+ group.add(tripleRelation.baseRelation(), tripleRelation);
return;
}
}
- List newList = new ArrayList();
- newList.add(relation);
- this.compatibleRelations.add(newList);
+ this.compatibleRelations.add(new CompatibleRelationGroup(tripleRelation.baseRelation(), tripleRelation));
}
- private ExecutionPlanElement createPlan() {
- ExecuteSequence sequence = new ExecuteSequence();
+ public ExtendedIterator iterator() {
+ ExtendedIterator result = NullIterator.emptyIterator();
Iterator it = compatibleRelations.iterator();
while (it.hasNext()) {
- List tripleRelations = (List) it.next();
- sequence.add(createPlanForTripleRelationList(tripleRelations));
- }
- return sequence;
- }
-
- private ExecutionPlanElement createPlanForTripleRelationList(List tripleRelations) {
- if (tripleRelations.size() == 1) {
- return new ExecuteTripleRelation((TripleRelation) tripleRelations.get(0));
- }
- return new ExecuteCompatibleTripleRelations(tripleRelations);
- }
-
- public ExtendedIterator iterator() {
- TripleIteratorVisitor visitor = new TripleIteratorVisitor();
- createPlan().visit(visitor);
- return visitor.iterator();
- }
-
- private class TripleIteratorVisitor implements ExecutionPlanVisitor {
- private ExtendedIterator iterator = new NullIterator();
- public ExtendedIterator iterator() {
- return iterator;
- }
- public void visit(ExecuteTripleRelation planElement) {
- TripleRelation relation = planElement.getTripleRelation();
- chain(relation.baseRelation(), relation);
- }
- public void visit(ExecuteCompatibleTripleRelations union) {
- chain(union.relation(), union);
- }
- public void visit(ExecuteSequence sequence) {
- Iterator it = sequence.elements().iterator();
- while (it.hasNext()) {
- ExecutionPlanElement element = (ExecutionPlanElement) it.next();
- element.visit(this);
- }
- }
- public void visitEmptyPlanElement() {
- // Do nothing
- }
- private void chain(Relation relation, TripleMaker tripleMaker) {
- if (relation.equals(Relation.EMPTY)) {
- return;
+ CompatibleRelationGroup group = (CompatibleRelationGroup) it.next();
+ if (!group.baseRelation().equals(Relation.EMPTY)) {
+ result = result.andThen(
+ RelationToTriplesIterator.createTripleIterator(group.baseRelation(), group));
}
- iterator = iterator.andThen(RelationToTriplesIterator.createTripleIterator(relation, tripleMaker));
}
+ return result;
}
}
diff --git a/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteCompatibleTripleRelations.java b/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteCompatibleTripleRelations.java
deleted file mode 100644
index 91ce18d2..00000000
--- a/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteCompatibleTripleRelations.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package de.fuberlin.wiwiss.d2rq.plan;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import de.fuberlin.wiwiss.d2rq.algebra.Relation;
-import de.fuberlin.wiwiss.d2rq.algebra.RelationImpl;
-import de.fuberlin.wiwiss.d2rq.algebra.RelationName;
-import de.fuberlin.wiwiss.d2rq.algebra.TripleRelation;
-import de.fuberlin.wiwiss.d2rq.sql.ResultRow;
-import de.fuberlin.wiwiss.d2rq.sql.TripleMaker;
-
-/**
- * @author Richard Cyganiak ([email protected])
- * @version $Id: ExecuteCompatibleTripleRelations.java,v 1.4 2008/07/29 18:45:32 cyganiak Exp $
- */
-public class ExecuteCompatibleTripleRelations implements ExecutionPlanElement, TripleMaker {
-
- /**
- * Checks if two {@link Relation}s can be combined into
- * a single SQL statement. Relations can be combined iff
- * they access the same database and they contain exactly the same
- * joins and WHERE clauses. If they both contain no joins, they
- * must contain only columns from the same table.
- *
- * @return <tt>true</tt> if both arguments are combinable
- */
- public static boolean areCompatible(Relation first, Relation second) {
- if (!first.database().equals(second.database())) {
- return false;
- }
- if (!first.joinConditions().equals(second.joinConditions())) {
- return false;
- }
- if (!first.condition().equals(second.condition())) {
- return false;
- }
- Set firstTables = first.tables();
- Set secondTables = second.tables();
- if (!firstTables.equals(secondTables)) {
- return false;
- }
- Iterator it = firstTables.iterator();
- while (it.hasNext()) {
- RelationName tableName = (RelationName) it.next();
- if (!first.aliases().originalOf(tableName).equals(
- second.aliases().originalOf(tableName))) {
- return false;
- }
- }
- if (!first.isUnique() || !second.isUnique()) {
- return false;
- }
- return true;
- }
-
- private Relation baseRelation;
- private List tripleMakers;
-
- public ExecuteCompatibleTripleRelations(List baseRelations) {
- this.tripleMakers = baseRelations;
- Relation base = ((TripleRelation) baseRelations.get(0)).baseRelation();
- Set projections = new HashSet();
- boolean allUnique = true;
- Iterator it = baseRelations.iterator();
- while (it.hasNext()) {
- TripleRelation bridge = (TripleRelation) it.next();
- projections.addAll(bridge.baseRelation().projections());
- allUnique = allUnique && bridge.baseRelation().isUnique();
- }
- this.baseRelation = new RelationImpl(base.database(), base.aliases(),
- base.condition(), base.joinConditions(), projections, allUnique);
- }
-
- public Relation relation() {
- return this.baseRelation;
- }
-
- public Collection makeTriples(ResultRow row) {
- List result = new ArrayList();
- Iterator it = this.tripleMakers.iterator();
- while (it.hasNext()) {
- TripleMaker relation = (TripleMaker) it.next();
- result.addAll(relation.makeTriples(row));
- }
- return result;
- }
-
- public void visit(ExecutionPlanVisitor visitor) {
- visitor.visit(this);
- }
-}
diff --git a/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteSequence.java b/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteSequence.java
deleted file mode 100644
index 5cfd0824..00000000
--- a/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteSequence.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package de.fuberlin.wiwiss.d2rq.plan;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-public class ExecuteSequence implements ExecutionPlanElement {
- private final List elements = new ArrayList();
-
- public ExecuteSequence() {
- this(Collections.EMPTY_LIST);
- }
-
- public ExecuteSequence(List elements) {
- this.elements.addAll(elements);
- }
-
- public void add(ExecutionPlanElement element) {
- this.elements.add(element);
- }
-
- public List elements() {
- return Collections.unmodifiableList(elements);
- }
-
- public void visit(ExecutionPlanVisitor visitor) {
- visitor.visit(this);
- }
-}
diff --git a/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteTripleRelation.java b/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteTripleRelation.java
deleted file mode 100644
index 36158901..00000000
--- a/src/de/fuberlin/wiwiss/d2rq/plan/ExecuteTripleRelation.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package de.fuberlin.wiwiss.d2rq.plan;
-
-import de.fuberlin.wiwiss.d2rq.algebra.TripleRelation;
-
-public class ExecuteTripleRelation implements ExecutionPlanElement {
- private TripleRelation tripleRelation;
-
- public ExecuteTripleRelation(TripleRelation tripleRelation) {
- this.tripleRelation = tripleRelation;
- }
-
- public TripleRelation getTripleRelation() {
- return tripleRelation;
- }
-
- public void visit(ExecutionPlanVisitor visitor) {
- visitor.visit(this);
- }
-}
diff --git a/src/de/fuberlin/wiwiss/d2rq/plan/ExecutionPlanElement.java b/src/de/fuberlin/wiwiss/d2rq/plan/ExecutionPlanElement.java
deleted file mode 100644
index 388ef2c4..00000000
--- a/src/de/fuberlin/wiwiss/d2rq/plan/ExecutionPlanElement.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package de.fuberlin.wiwiss.d2rq.plan;
-
-
-/**
- * A relation, as defined in relational algebra, plus a set of NodeMakers
- * attached to the relation, plus a set of TripleMakers attached to the
- * NodeMakers. Very much work in progress.
- *
- * @author Richard Cyganiak ([email protected])
- * @version $Id: ExecutionPlanElement.java,v 1.1 2008/04/25 11:25:05 cyganiak Exp $
- */
-public interface ExecutionPlanElement {
-
- public static final ExecutionPlanElement EMPTY = new ExecutionPlanElement() {
- public String toString() { return "ExecutionPlanElement.EMPTY"; }
- public void visit(ExecutionPlanVisitor visitor) { visitor.visitEmptyPlanElement(); }
- };
-
- public void visit(ExecutionPlanVisitor visitor);
-}
\ No newline at end of file
diff --git a/src/de/fuberlin/wiwiss/d2rq/plan/ExecutionPlanVisitor.java b/src/de/fuberlin/wiwiss/d2rq/plan/ExecutionPlanVisitor.java
deleted file mode 100644
index 63719f7a..00000000
--- a/src/de/fuberlin/wiwiss/d2rq/plan/ExecutionPlanVisitor.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package de.fuberlin.wiwiss.d2rq.plan;
-
-
-public interface ExecutionPlanVisitor {
-
- void visit(ExecuteTripleRelation tripleRelation);
-
- void visit(ExecuteCompatibleTripleRelations compatibleRelations);
-
- void visit(ExecuteSequence sequence);
-
- void visitEmptyPlanElement();
-}
diff --git a/test/de/fuberlin/wiwiss/d2rq/D2RQTestSuite.java b/test/de/fuberlin/wiwiss/d2rq/D2RQTestSuite.java
index 71dd0d5a..0b8dbc94 100644
--- a/test/de/fuberlin/wiwiss/d2rq/D2RQTestSuite.java
+++ b/test/de/fuberlin/wiwiss/d2rq/D2RQTestSuite.java
@@ -7,7 +7,7 @@
* Test suite for D2RQ
*
* @author Richard Cyganiak ([email protected])
- * @version $Id: D2RQTestSuite.java,v 1.14 2008/07/29 18:45:31 cyganiak Exp $
+ * @version $Id: D2RQTestSuite.java,v 1.15 2008/08/12 13:07:53 cyganiak Exp $
*/
public class D2RQTestSuite {
public static final String DIRECTORY = "test/de/fuberlin/wiwiss/d2rq/";
@@ -31,7 +31,6 @@ public static Test suite() {
suite.addTest(de.fuberlin.wiwiss.d2rq.map.AllTests.suite());
suite.addTest(de.fuberlin.wiwiss.d2rq.nodes.AllTests.suite());
suite.addTest(de.fuberlin.wiwiss.d2rq.parser.AllTests.suite());
- suite.addTest(de.fuberlin.wiwiss.d2rq.plan.AllTests.suite());
suite.addTest(de.fuberlin.wiwiss.d2rq.pp.AllTests.suite());
suite.addTest(de.fuberlin.wiwiss.d2rq.sql.AllTests.suite());
suite.addTest(de.fuberlin.wiwiss.d2rq.values.AllTests.suite());
diff --git a/test/de/fuberlin/wiwiss/d2rq/find/AllTests.java b/test/de/fuberlin/wiwiss/d2rq/find/AllTests.java
index 81d49ac7..0f8491cb 100644
--- a/test/de/fuberlin/wiwiss/d2rq/find/AllTests.java
+++ b/test/de/fuberlin/wiwiss/d2rq/find/AllTests.java
@@ -8,6 +8,7 @@ public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for de.fuberlin.wiwiss.d2rq.find");
//$JUnit-BEGIN$
+ suite.addTestSuite(CompatibleRelationGroupTest.class);
suite.addTestSuite(URIMakerRuleTest.class);
//$JUnit-END$
return suite;
diff --git a/test/de/fuberlin/wiwiss/d2rq/plan/ExecuteCompatibleTripleRelationsTest.java b/test/de/fuberlin/wiwiss/d2rq/find/CompatibleRelationGroupTest.java
similarity index 68%
rename from test/de/fuberlin/wiwiss/d2rq/plan/ExecuteCompatibleTripleRelationsTest.java
rename to test/de/fuberlin/wiwiss/d2rq/find/CompatibleRelationGroupTest.java
index 88ba8662..3d1b63f2 100644
--- a/test/de/fuberlin/wiwiss/d2rq/plan/ExecuteCompatibleTripleRelationsTest.java
+++ b/test/de/fuberlin/wiwiss/d2rq/find/CompatibleRelationGroupTest.java
@@ -1,4 +1,4 @@
-package de.fuberlin.wiwiss.d2rq.plan;
+package de.fuberlin.wiwiss.d2rq.find;
import java.util.Collections;
import java.util.Set;
@@ -8,9 +8,10 @@
import de.fuberlin.wiwiss.d2rq.algebra.Attribute;
import de.fuberlin.wiwiss.d2rq.algebra.RelationImpl;
import de.fuberlin.wiwiss.d2rq.expr.Expression;
+import de.fuberlin.wiwiss.d2rq.find.CompatibleRelationGroup;
import de.fuberlin.wiwiss.d2rq.sql.DummyDB;
-public class ExecuteCompatibleTripleRelationsTest extends TestCase {
+public class CompatibleRelationGroupTest extends TestCase {
public void testNotUniqueIsNotCompatible() {
Set projections1 = Collections.singleton(new Attribute(null, "table", "unique"));
@@ -21,7 +22,8 @@ public void testNotUniqueIsNotCompatible() {
RelationImpl notUnique = new RelationImpl(
new DummyDB(), AliasMap.NO_ALIASES, Expression.TRUE, Collections.EMPTY_SET,
projections2, false);
- assertTrue(ExecuteCompatibleTripleRelations.areCompatible(unique, unique));
- assertFalse(ExecuteCompatibleTripleRelations.areCompatible(unique, notUnique));
+ assertTrue(new CompatibleRelationGroup(unique, null).isCompatible(unique));
+ assertFalse(new CompatibleRelationGroup(unique, null).isCompatible(notUnique));
+ assertFalse(new CompatibleRelationGroup(notUnique, null).isCompatible(unique));
}
}
diff --git a/test/de/fuberlin/wiwiss/d2rq/plan/AllTests.java b/test/de/fuberlin/wiwiss/d2rq/plan/AllTests.java
deleted file mode 100644
index 44e913a3..00000000
--- a/test/de/fuberlin/wiwiss/d2rq/plan/AllTests.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package de.fuberlin.wiwiss.d2rq.plan;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-public class AllTests {
-
- public static Test suite() {
- TestSuite suite = new TestSuite("Test for de.fuberlin.wiwiss.d2rq.plan");
- //$JUnit-BEGIN$
- suite.addTestSuite(ExecuteCompatibleTripleRelationsTest.class);
- //$JUnit-END$
- return suite;
- }
-
-}
|
2ca004c0298cd87c9a946843ab905154d4d1df65
|
apache$maven-plugins
|
[MINVOKER-22] Add feature to install plugin to a local repository.
o Refactored functionality into distinct mojo
git-svn-id: https://svn.apache.org/repos/asf/maven/plugins/trunk@655034 13f79535-47bb-0310-9956-ffa450edef68
|
p
|
https://github.com/apache/maven-plugins
|
diff --git a/maven-invoker-plugin/pom.xml b/maven-invoker-plugin/pom.xml
index c8a8c694fd..5304fd3f08 100644
--- a/maven-invoker-plugin/pom.xml
+++ b/maven-invoker-plugin/pom.xml
@@ -69,6 +69,11 @@ under the License.
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-artifact</artifactId>
+ <version>2.0</version>
+ </dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-settings</artifactId>
diff --git a/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InstallMojo.java b/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InstallMojo.java
new file mode 100644
index 0000000000..38ab038b23
--- /dev/null
+++ b/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InstallMojo.java
@@ -0,0 +1,176 @@
+package org.apache.maven.plugin.invoker;
+
+/*
+ * 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.
+ */
+
+import java.io.File;
+import java.util.Collection;
+import java.util.Iterator;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.artifact.factory.ArtifactFactory;
+import org.apache.maven.artifact.installer.ArtifactInstallationException;
+import org.apache.maven.artifact.installer.ArtifactInstaller;
+import org.apache.maven.artifact.repository.ArtifactRepository;
+import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * Installs the project artifacts into the local repository as a preparation to run the integration tests.
+ *
+ * @goal install
+ * @phase pre-integration-test
+ * @since 1.2
+ *
+ * @author Paul Gier
+ * @author Benjamin Bentmann
+ * @version $Id$
+ */
+public class InstallMojo
+ extends AbstractMojo
+{
+
+ /**
+ * Maven artifact install component to copy artifacts to the local repository.
+ *
+ * @component
+ */
+ private ArtifactInstaller installer;
+
+ /**
+ * The component used to create artifacts.
+ *
+ * @component
+ */
+ private ArtifactFactory artifactFactory;
+
+ /**
+ * The component used to create artifacts.
+ *
+ * @component
+ */
+ private ArtifactRepositoryFactory repositoryFactory;
+
+ /**
+ * @parameter expression="${localRepository}"
+ * @required
+ * @readonly
+ */
+ protected ArtifactRepository localRepository;
+
+ /**
+ * The path to the local repository into which the project artifacts should be installed for the integration tests.
+ * If not set, the regular local repository will be used.
+ *
+ * @parameter expression="${invoker.localRepositoryPath}"
+ */
+ private File localRepositoryPath;
+
+ /**
+ * The current Maven project.
+ *
+ * @parameter expression="${project}"
+ * @required
+ * @readonly
+ */
+ private MavenProject project;
+
+ /**
+ * Performs this mojo's tasks.
+ */
+ public void execute()
+ throws MojoExecutionException, MojoFailureException
+ {
+ ArtifactRepository testRepository = createTestRepository();
+ installProjectArtifacts( testRepository );
+ }
+
+ /**
+ * Installs the main project artifact and any attached artifacts to the local repository.
+ *
+ * @param testRepository The local repository to install the artifacts into, must not be <code>null</code>.
+ * @throws MojoExecutionException If any artifact could not be installed.
+ */
+ private void installProjectArtifacts( ArtifactRepository testRepository )
+ throws MojoExecutionException
+ {
+ try
+ {
+ // Install the pom
+ Artifact pomArtifact =
+ artifactFactory.createArtifact( project.getGroupId(), project.getArtifactId(), project.getVersion(),
+ null, "pom" );
+ installer.install( project.getFile(), pomArtifact, testRepository );
+
+ // Install the main project artifact
+ installer.install( project.getArtifact().getFile(), project.getArtifact(), testRepository );
+
+ // Install any attached project artifacts
+ Collection attachedArtifacts = project.getAttachedArtifacts();
+ for ( Iterator artifactIter = attachedArtifacts.iterator(); artifactIter.hasNext(); )
+ {
+ Artifact theArtifact = (Artifact) artifactIter.next();
+ installer.install( theArtifact.getFile(), theArtifact, testRepository );
+ }
+ }
+ catch ( ArtifactInstallationException e )
+ {
+ throw new MojoExecutionException( "Failed to install project artifacts", e );
+ }
+ }
+
+ /**
+ * Creates the local repository for the integration tests.
+ *
+ * @return The local repository for the integration tests, never <code>null</code>.
+ * @throws MojoExecutionException If the repository could not be created.
+ */
+ private ArtifactRepository createTestRepository()
+ throws MojoExecutionException
+ {
+ ArtifactRepository testRepository = localRepository;
+
+ if ( localRepositoryPath != null )
+ {
+ try
+ {
+ if ( !localRepositoryPath.exists() )
+ {
+ localRepositoryPath.mkdirs();
+ }
+
+ testRepository =
+ repositoryFactory.createArtifactRepository( "it-repo", localRepositoryPath.toURL().toString(),
+ localRepository.getLayout(),
+ localRepository.getSnapshots(),
+ localRepository.getReleases() );
+ }
+ catch ( Exception e )
+ {
+ throw new MojoExecutionException( "Failed to create local repository", e );
+ }
+ }
+
+ return testRepository;
+ }
+
+}
diff --git a/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InvokerMojo.java b/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InvokerMojo.java
index ebb6dd29d5..24e4dbdf28 100644
--- a/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InvokerMojo.java
+++ b/maven-invoker-plugin/src/main/java/org/apache/maven/plugin/invoker/InvokerMojo.java
@@ -28,7 +28,6 @@
import java.io.PrintStream;
import java.io.Reader;
import java.io.Writer;
-import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -39,12 +38,6 @@
import java.util.StringTokenizer;
import java.util.TreeSet;
-import org.apache.maven.artifact.Artifact;
-import org.apache.maven.artifact.factory.ArtifactFactory;
-import org.apache.maven.artifact.installer.ArtifactInstallationException;
-import org.apache.maven.artifact.installer.ArtifactInstaller;
-import org.apache.maven.artifact.repository.ArtifactRepository;
-import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
@@ -85,40 +78,12 @@
*
* @author <a href="mailto:[email protected]">Kenney Westerhof</a>
* @author <a href="mailto:[email protected]">John Casey</a>
+ * @version $Id$
*/
public class InvokerMojo
extends AbstractMojo
{
- /**
- * Maven artifact install component to copy artifacts to the local repository.
- *
- * @component
- */
- protected ArtifactInstaller installer;
-
- /**
- * Used to create artifacts
- *
- * @component
- */
- private ArtifactFactory artifactFactory;
-
- /**
- * Used to create artifacts
- *
- * @component
- */
- private ArtifactRepositoryFactory artifactRepositoryFactory;
- /**
- * Flag to determine if the project artifact(s) should be installed to the
- * local repository.
- *
- * @parameter default-value="false"
- * @since 1.2
- */
- private boolean installProjectArtifacts;
-
/**
* Flag used to suppress certain invocations. This is useful in tailoring the
* build using profiles.
@@ -145,13 +110,6 @@ public class InvokerMojo
*/
private boolean streamLogs;
- /**
- * @parameter expression="${localRepository}"
- * @required
- * @readonly
- */
- protected ArtifactRepository localRepository;
-
/**
* The local repository for caching artifacts.
*
@@ -425,11 +383,6 @@ public void execute()
return;
}
- if ( installProjectArtifacts )
- {
- installProjectArtifacts();
- }
-
String[] includedPoms;
if ( pom != null )
{
@@ -555,60 +508,6 @@ private Reader newReader( File file )
}
}
- /**
- * Install the main project artifact and any attached artifacts to the local repository.
- *
- * @throws MojoExecutionException
- */
- private void installProjectArtifacts()
- throws MojoExecutionException
- {
- ArtifactRepository integrationTestRepository = localRepository;
-
- try
- {
- if ( localRepositoryPath != null )
- {
- if ( ! localRepositoryPath.exists() )
- {
- localRepositoryPath.mkdirs();
- }
- integrationTestRepository =
- artifactRepositoryFactory.createArtifactRepository( "it-repo",
- localRepositoryPath.toURL().toString(),
- localRepository.getLayout(),
- localRepository.getSnapshots(),
- localRepository.getReleases() );
- }
-
- // Install the pom
- Artifact pomArtifact = artifactFactory.createArtifact( project.getGroupId(), project.getArtifactId(),
- project.getVersion(), null, "pom" );
- installer.install( project.getFile(), pomArtifact, integrationTestRepository );
-
- // Install the main project artifact
- installer.install( project.getArtifact().getFile(), project.getArtifact(), integrationTestRepository );
-
- // Install any attached project artifacts
- List attachedArtifacts = project.getAttachedArtifacts();
- Iterator artifactIter = attachedArtifacts.iterator();
- while ( artifactIter.hasNext() )
- {
- Artifact theArtifact = (Artifact)artifactIter.next();
- installer.install( theArtifact.getFile(), theArtifact, integrationTestRepository );
- }
- }
- catch ( MalformedURLException e )
- {
- throw new MojoExecutionException( "MalformedURLException: " + e.getMessage(), e );
- }
- catch ( ArtifactInstallationException e )
- {
- throw new MojoExecutionException( "ArtifactInstallationException: " + e.getMessage(), e );
- }
-
- }
-
private void cloneProjects( String[] includedPoms )
throws IOException
{
diff --git a/maven-invoker-plugin/src/site/apt/examples/install-artifacts.apt b/maven-invoker-plugin/src/site/apt/examples/install-artifacts.apt
index c6074d11cd..855f5d355a 100644
--- a/maven-invoker-plugin/src/site/apt/examples/install-artifacts.apt
+++ b/maven-invoker-plugin/src/site/apt/examples/install-artifacts.apt
@@ -8,8 +8,8 @@
Installing Artifacts Example
- The following example shows a plugin configuration with the <<<\<installProjectArtifacts\>>>>
- parameter set to <<<true>>>. This will cause the project artifact(s) to be installed to the local
+ The following example shows a plugin configuration using the <<<{{{../install-mojo.html}invoker:install}}>>>
+ goal. This will cause the project artifact(s) to be installed to the local
repository before executing the projects. This can be helpful if you
want to build you project and test the new artifacts artifact in a single step instead of
installing first and then running tests.
@@ -25,13 +25,12 @@ Installing Artifacts Example
<executions>
<execution>
<id>integration-test</id>
- <phase>integration-test</phase>
<goals>
+ <goal>install</goal>
<goal>run</goal>
</goals>
<configuration>
<localRepositoryPath>target/local-repo</localRepositoryPath>
- <installProjectArtifacts>true</installProjectArtifacts>
<projectsDirectory>src/it</projectsDirectory>
</configuration>
</execution>
diff --git a/maven-invoker-plugin/src/site/apt/index.apt b/maven-invoker-plugin/src/site/apt/index.apt
index 7777c42277..78b5d82bc0 100644
--- a/maven-invoker-plugin/src/site/apt/index.apt
+++ b/maven-invoker-plugin/src/site/apt/index.apt
@@ -14,6 +14,11 @@ Maven 2 Invoker Plugin
* Goals Overview
+ The Invoker Plugin has two goals:
+
+ * {{{install-mojo.html}invoker:install}} copies the project artifacts into the local repository to prepare the
+ execution of the integration tests.
+
* {{{run-mojo.html}invoker:run}} runs a set of Maven projects in a directory and verifies the result.
[]
|
0fdcf884987f1906a6ebfe2a2cb7cc86e05440ed
|
hadoop
|
HDFS-1330 and HADOOP-6889. Added additional unit- tests. Contributed by John George.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1163464 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 595f4678ce6c4..9ddcdf8bfa8c5 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1084,6 +1084,7 @@ Release 0.22.0 - Unreleased
(jghoman)
HDFS-1330. Make RPCs to DataNodes timeout. (hairong)
+ Added additional unit tests per HADOOP-6889. (John George via mattf)
HDFS-202. HDFS support of listLocatedStatus introduced in HADOOP-6870.
HDFS piggyback block locations to each file status when listing a
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java
index 05fa648653a75..714bce7045e3a 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java
@@ -25,7 +25,12 @@
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
+import java.net.SocketTimeoutException;
+import org.apache.hadoop.io.IOUtils;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.LongWritable;
import java.io.IOException;
+import java.net.InetSocketAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
@@ -44,6 +49,8 @@
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
+import org.apache.hadoop.hdfs.protocol.Block;
+import org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
@@ -52,6 +59,11 @@
import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.ipc.RemoteException;
+import org.apache.hadoop.ipc.Client;
+import org.apache.hadoop.ipc.ProtocolSignature;
+import org.apache.hadoop.ipc.RPC;
+import org.apache.hadoop.ipc.Server;
+import org.apache.hadoop.net.NetUtils;
import org.mockito.internal.stubbing.answers.ThrowsException;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -61,9 +73,51 @@
* properly in case of errors.
*/
public class TestDFSClientRetries extends TestCase {
+ private static final String ADDRESS = "0.0.0.0";
+ final static private int PING_INTERVAL = 1000;
+ final static private int MIN_SLEEP_TIME = 1000;
public static final Log LOG =
LogFactory.getLog(TestDFSClientRetries.class.getName());
-
+ final static private Configuration conf = new HdfsConfiguration();
+
+ private static class TestServer extends Server {
+ private boolean sleep;
+ private Class<? extends Writable> responseClass;
+
+ public TestServer(int handlerCount, boolean sleep) throws IOException {
+ this(handlerCount, sleep, LongWritable.class, null);
+ }
+
+ public TestServer(int handlerCount, boolean sleep,
+ Class<? extends Writable> paramClass,
+ Class<? extends Writable> responseClass)
+ throws IOException {
+ super(ADDRESS, 0, paramClass, handlerCount, conf);
+ this.sleep = sleep;
+ this.responseClass = responseClass;
+ }
+
+ @Override
+ public Writable call(Class<?> protocol, Writable param, long receiveTime)
+ throws IOException {
+ if (sleep) {
+ // sleep a bit
+ try {
+ Thread.sleep(PING_INTERVAL + MIN_SLEEP_TIME);
+ } catch (InterruptedException e) {}
+ }
+ if (responseClass != null) {
+ try {
+ return responseClass.newInstance();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ return param; // echo param as result
+ }
+ }
+ }
+
// writes 'len' bytes of data to out.
private static void writeData(OutputStream out, int len) throws IOException {
byte [] buf = new byte[4096*16];
@@ -80,8 +134,6 @@ private static void writeData(OutputStream out, int len) throws IOException {
*/
public void testWriteTimeoutAtDataNode() throws IOException,
InterruptedException {
- Configuration conf = new HdfsConfiguration();
-
final int writeTimeout = 100; //milliseconds.
// set a very short write timeout for datanode, so that tests runs fast.
conf.setInt(DFSConfigKeys.DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY, writeTimeout);
@@ -136,7 +188,6 @@ public void testNotYetReplicatedErrors() throws IOException
{
final String exceptionMsg = "Nope, not replicated yet...";
final int maxRetries = 1; // Allow one retry (total of two calls)
- Configuration conf = new HdfsConfiguration();
conf.setInt(DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY, maxRetries);
NameNode mockNN = mock(NameNode.class);
@@ -182,7 +233,6 @@ public void testFailuresArePerOperation() throws Exception
long fileSize = 4096;
Path file = new Path("/testFile");
- Configuration conf = new Configuration();
// Set short retry timeout so this test runs faster
conf.setInt(DFSConfigKeys.DFS_CLIENT_RETRY_WINDOW_BASE, 10);
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
@@ -379,7 +429,6 @@ private boolean busyTest(int xcievers, int threads, int fileLen, int timeWin, in
long blockSize = 128*1024*1024; // DFS block size
int bufferSize = 4096;
- Configuration conf = new HdfsConfiguration();
conf.setInt(DFSConfigKeys.DFS_DATANODE_MAX_RECEIVER_THREADS_KEY, xcievers);
conf.setInt(DFSConfigKeys.DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY,
retries);
@@ -540,7 +589,6 @@ public void testGetFileChecksum() throws Exception {
final String f = "/testGetFileChecksum";
final Path p = new Path(f);
- final Configuration conf = new Configuration();
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
try {
cluster.waitActive();
@@ -566,5 +614,39 @@ public void testGetFileChecksum() throws Exception {
cluster.shutdown();
}
}
+
+ /** Test that timeout occurs when DN does not respond to RPC.
+ * Start up a server and ask it to sleep for n seconds. Make an
+ * RPC to the server and set rpcTimeout to less than n and ensure
+ * that socketTimeoutException is obtained
+ */
+ public void testClientDNProtocolTimeout() throws IOException {
+ final Server server = new TestServer(1, true);
+ server.start();
+
+ final InetSocketAddress addr = NetUtils.getConnectAddress(server);
+ DatanodeID fakeDnId = new DatanodeID(
+ "localhost:" + addr.getPort(), "fake-storage", 0, addr.getPort());
+
+ ExtendedBlock b = new ExtendedBlock("fake-pool", new Block(12345L));
+ LocatedBlock fakeBlock = new LocatedBlock(b, new DatanodeInfo[0]);
+
+ ClientDatanodeProtocol proxy = null;
+
+ try {
+ proxy = DFSUtil.createClientDatanodeProtocolProxy(
+ fakeDnId, conf, 500, fakeBlock);
+
+ proxy.getReplicaVisibleLength(null);
+ fail ("Did not get expected exception: SocketTimeoutException");
+ } catch (SocketTimeoutException e) {
+ LOG.info("Got the expected Exception: SocketTimeoutException");
+ } finally {
+ if (proxy != null) {
+ RPC.stopProxy(proxy);
+ }
+ server.stop();
+ }
+ }
}
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestInterDatanodeProtocol.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestInterDatanodeProtocol.java
index eb58f7f195afc..b1f1fc911c9a9 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestInterDatanodeProtocol.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestInterDatanodeProtocol.java
@@ -22,6 +22,20 @@
import java.io.IOException;
import java.util.List;
+import java.net.InetSocketAddress;
+
+import java.net.SocketTimeoutException;
+import org.apache.hadoop.io.IOUtils;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.LongWritable;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.util.StringUtils;
+
+import org.apache.hadoop.ipc.Client;
+import org.apache.hadoop.ipc.ProtocolSignature;
+import org.apache.hadoop.ipc.RPC;
+import org.apache.hadoop.ipc.Server;
+import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
@@ -38,6 +52,7 @@
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.protocol.RecoveryInProgressException;
import org.apache.hadoop.hdfs.server.common.HdfsConstants.ReplicaState;
+import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.server.protocol.InterDatanodeProtocol;
import org.apache.hadoop.hdfs.server.protocol.ReplicaRecoveryInfo;
import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand.RecoveringBlock;
@@ -48,6 +63,50 @@
* This tests InterDataNodeProtocol for block handling.
*/
public class TestInterDatanodeProtocol {
+ private static final String ADDRESS = "0.0.0.0";
+ final static private int PING_INTERVAL = 1000;
+ final static private int MIN_SLEEP_TIME = 1000;
+ private static Configuration conf = new HdfsConfiguration();
+
+
+ private static class TestServer extends Server {
+ private boolean sleep;
+ private Class<? extends Writable> responseClass;
+
+ public TestServer(int handlerCount, boolean sleep) throws IOException {
+ this(handlerCount, sleep, LongWritable.class, null);
+ }
+
+ public TestServer(int handlerCount, boolean sleep,
+ Class<? extends Writable> paramClass,
+ Class<? extends Writable> responseClass)
+ throws IOException {
+ super(ADDRESS, 0, paramClass, handlerCount, conf);
+ this.sleep = sleep;
+ this.responseClass = responseClass;
+ }
+
+ @Override
+ public Writable call(Class<?> protocol, Writable param, long receiveTime)
+ throws IOException {
+ if (sleep) {
+ // sleep a bit
+ try {
+ Thread.sleep(PING_INTERVAL + MIN_SLEEP_TIME);
+ } catch (InterruptedException e) {}
+ }
+ if (responseClass != null) {
+ try {
+ return responseClass.newInstance();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ return param; // echo param as result
+ }
+ }
+ }
+
public static void checkMetaInfo(ExtendedBlock b, DataNode dn) throws IOException {
Block metainfo = dn.data.getStoredBlock(b.getBlockPoolId(), b.getBlockId());
Assert.assertEquals(b.getBlockId(), metainfo.getBlockId());
@@ -73,7 +132,6 @@ public static LocatedBlock getLastLocatedBlock(
*/
@Test
public void testBlockMetaDataInfo() throws Exception {
- Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = null;
try {
@@ -222,7 +280,6 @@ public void testInitReplicaRecovery() throws IOException {
* */
@Test
public void testUpdateReplicaUnderRecovery() throws IOException {
- final Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = null;
try {
@@ -291,4 +348,33 @@ public void testUpdateReplicaUnderRecovery() throws IOException {
if (cluster != null) cluster.shutdown();
}
}
+
+ /** Test to verify that InterDatanode RPC timesout as expected when
+ * the server DN does not respond.
+ */
+ @Test
+ public void testInterDNProtocolTimeout() throws Exception {
+ final Server server = new TestServer(1, true);
+ server.start();
+
+ final InetSocketAddress addr = NetUtils.getConnectAddress(server);
+ DatanodeID fakeDnId = new DatanodeID(
+ "localhost:" + addr.getPort(), "fake-storage", 0, addr.getPort());
+ DatanodeInfo dInfo = new DatanodeInfo(fakeDnId);
+ InterDatanodeProtocol proxy = null;
+
+ try {
+ proxy = DataNode.createInterDataNodeProtocolProxy(
+ dInfo, conf, 500);
+ proxy.initReplicaRecovery(null);
+ fail ("Expected SocketTimeoutException exception, but did not get.");
+ } catch (SocketTimeoutException e) {
+ DataNode.LOG.info("Got expected Exception: SocketTimeoutException" + e);
+ } finally {
+ if (proxy != null) {
+ RPC.stopProxy(proxy);
+ }
+ server.stop();
+ }
+ }
}
|
9214f95cf4e5d19f5d226245043ea0669d276e59
|
hbase
|
HBASE-6170 Timeouts for row lock and scan should- be separate (Chris Trezzo)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1354325 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
index 9dac3884c0be..82cf976a1b38 100644
--- a/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
+++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
@@ -536,16 +536,25 @@ public static enum Modify {
public static String HBASE_CLIENT_INSTANCE_ID = "hbase.client.instance.id";
/**
- * HRegion server lease period in milliseconds. Clients must report in within this period
- * else they are considered dead. Unit measured in ms (milliseconds).
+ * The row lock timeout period in milliseconds.
*/
- public static String HBASE_REGIONSERVER_LEASE_PERIOD_KEY =
- "hbase.regionserver.lease.period";
+ public static String HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD =
+ "hbase.regionserver.rowlock.timeout.period";
/**
- * Default value of {@link #HBASE_REGIONSERVER_LEASE_PERIOD_KEY}.
+ * Default value of {@link #HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD}.
*/
- public static long DEFAULT_HBASE_REGIONSERVER_LEASE_PERIOD = 60000;
+ public static int DEFAULT_HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD = 60000;
+
+ /**
+ * The client scanner timeout period in milliseconds.
+ */
+ public static String HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD = "hbase.client.scanner.timeout.period";
+
+ /**
+ * Default value of {@link #HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD}.
+ */
+ public static int DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD = 60000;
/**
* timeout for each RPC
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
index 32ddf120c62b..ccb1dc3f79b5 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
@@ -106,9 +106,8 @@ public ClientScanner(final Configuration conf, final Scan scan,
HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY,
HConstants.DEFAULT_HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE);
}
- this.scannerTimeout = (int) conf.getLong(
- HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,
- HConstants.DEFAULT_HBASE_REGIONSERVER_LEASE_PERIOD);
+ this.scannerTimeout = conf.getInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD,
+ HConstants.DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD);
// check if application wants to collect scan metrics
byte[] enableMetrics = scan.getAttribute(
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
index 3556a7c05586..bad1d12df793 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -422,6 +422,16 @@ public class HRegionServer implements ClientProtocol,
*/
private MovedRegionsCleaner movedRegionsCleaner;
+ /**
+ * The lease timeout period for row locks (milliseconds).
+ */
+ private final int rowLockLeaseTimeoutPeriod;
+
+ /**
+ * The lease timeout period for client scanners (milliseconds).
+ */
+ private final int scannerLeaseTimeoutPeriod;
+
/**
* Starts a HRegionServer at the default location
@@ -466,6 +476,13 @@ public HRegionServer(Configuration conf)
this.abortRequested = false;
this.stopped = false;
+ this.rowLockLeaseTimeoutPeriod = conf.getInt(
+ HConstants.HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD,
+ HConstants.DEFAULT_HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD);
+
+ this.scannerLeaseTimeoutPeriod = conf.getInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD,
+ HConstants.DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD);
+
// Server to handle client requests.
String hostname = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
conf.get("hbase.regionserver.dns.interface", "default"),
@@ -705,10 +722,7 @@ private void initializeThreads() throws IOException {
this.compactionChecker = new CompactionChecker(this,
this.threadWakeFrequency * multiplier, this);
- this.leases = new Leases((int) conf.getLong(
- HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,
- HConstants.DEFAULT_HBASE_REGIONSERVER_LEASE_PERIOD),
- this.threadWakeFrequency);
+ this.leases = new Leases(this.threadWakeFrequency);
// Create the thread for the ThriftServer.
if (conf.getBoolean("hbase.regionserver.export.thrift", false)) {
@@ -2658,7 +2672,8 @@ protected long addRowLock(Integer r, HRegion region)
long lockId = nextLong();
String lockName = String.valueOf(lockId);
rowlocks.put(lockName, r);
- this.leases.createLease(lockName, new RowLockListener(lockName, region));
+ this.leases.createLease(lockName, this.rowLockLeaseTimeoutPeriod, new RowLockListener(lockName,
+ region));
return lockId;
}
@@ -2666,7 +2681,8 @@ protected long addScanner(RegionScanner s) throws LeaseStillHeldException {
long scannerId = nextLong();
String scannerName = String.valueOf(scannerId);
scanners.put(scannerName, s);
- this.leases.createLease(scannerName, new ScannerListener(scannerName));
+ this.leases.createLease(scannerName, this.scannerLeaseTimeoutPeriod, new ScannerListener(
+ scannerName));
return scannerId;
}
@@ -2925,7 +2941,7 @@ public ScanResponse scan(final RpcController controller,
}
scannerId = addScanner(scanner);
scannerName = String.valueOf(scannerId);
- ttl = leases.leasePeriod;
+ ttl = this.scannerLeaseTimeoutPeriod;
}
if (rows > 0) {
@@ -2999,7 +3015,7 @@ public ScanResponse scan(final RpcController controller,
// Adding resets expiration time on lease.
if (scanners.containsKey(scannerName)) {
if (lease != null) leases.addLease(lease);
- ttl = leases.leasePeriod;
+ ttl = this.scannerLeaseTimeoutPeriod;
}
}
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Leases.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Leases.java
index 0b7ed0e3861d..f2bd5680487d 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Leases.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Leases.java
@@ -55,7 +55,6 @@
@InterfaceAudience.Private
public class Leases extends HasThread {
private static final Log LOG = LogFactory.getLog(Leases.class.getName());
- protected final int leasePeriod;
private final int leaseCheckFrequency;
private volatile DelayQueue<Lease> leaseQueue = new DelayQueue<Lease>();
protected final Map<String, Lease> leases = new HashMap<String, Lease>();
@@ -63,13 +62,11 @@ public class Leases extends HasThread {
/**
* Creates a lease monitor
- *
- * @param leasePeriod - length of time (milliseconds) that the lease is valid
+ *
* @param leaseCheckFrequency - how often the lease should be checked
- * (milliseconds)
+ * (milliseconds)
*/
- public Leases(final int leasePeriod, final int leaseCheckFrequency) {
- this.leasePeriod = leasePeriod;
+ public Leases(final int leaseCheckFrequency) {
this.leaseCheckFrequency = leaseCheckFrequency;
setDaemon(true);
}
@@ -135,15 +132,16 @@ public void close() {
}
/**
- * Obtain a lease
- *
+ * Obtain a lease.
+ *
* @param leaseName name of the lease
+ * @param leaseTimeoutPeriod length of the lease in milliseconds
* @param listener listener that will process lease expirations
* @throws LeaseStillHeldException
*/
- public void createLease(String leaseName, final LeaseListener listener)
- throws LeaseStillHeldException {
- addLease(new Lease(leaseName, listener));
+ public void createLease(String leaseName, int leaseTimeoutPeriod, final LeaseListener listener)
+ throws LeaseStillHeldException {
+ addLease(new Lease(leaseName, leaseTimeoutPeriod, listener));
}
/**
@@ -155,7 +153,7 @@ public void addLease(final Lease lease) throws LeaseStillHeldException {
if (this.stopRequested) {
return;
}
- lease.setExpirationTime(System.currentTimeMillis() + this.leasePeriod);
+ lease.resetExpirationTime();
synchronized (leaseQueue) {
if (leases.containsKey(lease.getLeaseName())) {
throw new LeaseStillHeldException(lease.getLeaseName());
@@ -202,7 +200,7 @@ public void renewLease(final String leaseName) throws LeaseException {
throw new LeaseException("lease '" + leaseName +
"' does not exist or has already expired");
}
- lease.setExpirationTime(System.currentTimeMillis() + leasePeriod);
+ lease.resetExpirationTime();
leaseQueue.add(lease);
}
}
@@ -241,16 +239,14 @@ Lease removeLease(final String leaseName) throws LeaseException {
static class Lease implements Delayed {
private final String leaseName;
private final LeaseListener listener;
+ private int leaseTimeoutPeriod;
private long expirationTime;
- Lease(final String leaseName, LeaseListener listener) {
- this(leaseName, listener, 0);
- }
-
- Lease(final String leaseName, LeaseListener listener, long expirationTime) {
+ Lease(final String leaseName, int leaseTimeoutPeriod, LeaseListener listener) {
this.leaseName = leaseName;
this.listener = listener;
- this.expirationTime = expirationTime;
+ this.leaseTimeoutPeriod = leaseTimeoutPeriod;
+ this.expirationTime = 0;
}
/** @return the lease name */
@@ -294,9 +290,11 @@ public int compareTo(Delayed o) {
return this.equals(o) ? 0 : (delta > 0 ? 1 : -1);
}
- /** @param expirationTime the expirationTime to set */
- public void setExpirationTime(long expirationTime) {
- this.expirationTime = expirationTime;
+ /**
+ * Resets the expiration time of the lease.
+ */
+ public void resetExpirationTime() {
+ this.expirationTime = System.currentTimeMillis() + this.leaseTimeoutPeriod;
}
}
-}
\ No newline at end of file
+}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestScannerTimeout.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestScannerTimeout.java
index 1f9358324973..362c094ba9e5 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestScannerTimeout.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestScannerTimeout.java
@@ -25,7 +25,9 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hbase.*;
+import org.apache.hadoop.hbase.HBaseTestingUtility;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.LargeTests;
import org.apache.hadoop.hbase.catalog.MetaReader;
import org.apache.hadoop.hbase.regionserver.HRegionServer;
import org.apache.hadoop.hbase.util.Bytes;
@@ -48,7 +50,7 @@ public class TestScannerTimeout {
private final static byte[] SOME_BYTES = Bytes.toBytes("f");
private final static byte[] TABLE_NAME = Bytes.toBytes("t");
private final static int NB_ROWS = 10;
- // Be careful w/ what you set this timer too... it can get in the way of
+ // Be careful w/ what you set this timer to... it can get in the way of
// the mini cluster coming up -- the verification in particular.
private final static int SCANNER_TIMEOUT = 10000;
private final static int SCANNER_CACHING = 5;
@@ -59,7 +61,7 @@ public class TestScannerTimeout {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Configuration c = TEST_UTIL.getConfiguration();
- c.setInt("hbase.regionserver.lease.period", SCANNER_TIMEOUT);
+ c.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, SCANNER_TIMEOUT);
// We need more than one region server for this test
TEST_UTIL.startMiniCluster(2);
HTable table = TEST_UTIL.createTable(TABLE_NAME, SOME_BYTES);
@@ -134,8 +136,7 @@ public void test2772() throws Exception {
// Since the RS is already created, this conf is client-side only for
// this new table
Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
- conf.setInt(
- HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY, SCANNER_TIMEOUT*100);
+ conf.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, SCANNER_TIMEOUT * 100);
HTable higherScanTimeoutTable = new HTable(conf, TABLE_NAME);
ResultScanner r = higherScanTimeoutTable.getScanner(scan);
// This takes way less than SCANNER_TIMEOUT*100
@@ -201,8 +202,7 @@ public void test3686b() throws Exception {
// Since the RS is already created, this conf is client-side only for
// this new table
Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
- conf.setInt(
- HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY, SCANNER_TIMEOUT*100);
+ conf.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, SCANNER_TIMEOUT * 100);
HTable higherScanTimeoutTable = new HTable(conf, TABLE_NAME);
ResultScanner r = higherScanTimeoutTable.getScanner(scan);
int count = 1;
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorInterface.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorInterface.java
index 7951b8a4dd22..25a0c0547483 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorInterface.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorInterface.java
@@ -325,8 +325,9 @@ Configuration initSplit() {
// Make lease timeout longer, lease checks less frequent
TEST_UTIL.getConfiguration().setInt(
"hbase.master.lease.thread.wakefrequency", 5 * 1000);
- TEST_UTIL.getConfiguration().setInt(
- "hbase.regionserver.lease.period", 10 * 1000);
+ TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, 10 * 1000);
+ TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD,
+ 10 * 1000);
// Increase the amount of time between client retries
TEST_UTIL.getConfiguration().setLong("hbase.client.pause", 15 * 1000);
// This size should make it so we always split using the addContent
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java
index 08949facf2a5..fbd17ba89540 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java
@@ -3797,7 +3797,8 @@ private Configuration initSplit() {
// Make lease timeout longer, lease checks less frequent
conf.setInt("hbase.master.lease.thread.wakefrequency", 5 * 1000);
- conf.setInt(HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY, 10 * 1000);
+ conf.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, 10 * 1000);
+ conf.setInt(HConstants.HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD, 10 * 1000);
// Increase the amount of time between client retries
conf.setLong("hbase.client.pause", 15 * 1000);
|
d5c271acf51b504f2316c4a18597dbe81a67c6a9
|
elasticsearch
|
clean-up long values--
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/index/fielddata/DoubleValues.java b/src/main/java/org/elasticsearch/index/fielddata/DoubleValues.java
index d6ab9e6d2e3dc..5382220525179 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/DoubleValues.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/DoubleValues.java
@@ -20,6 +20,7 @@
package org.elasticsearch.index.fielddata;
import org.elasticsearch.ElasticSearchIllegalStateException;
+import org.elasticsearch.index.fielddata.LongValues.Iter;
import org.elasticsearch.index.fielddata.util.DoubleArrayRef;
import org.elasticsearch.index.fielddata.util.IntArrayRef;
import org.elasticsearch.index.fielddata.util.LongArrayRef;
@@ -136,7 +137,6 @@ public static class LongBased implements DoubleValues {
private final LongValues values;
private final ValueIter iter = new ValueIter();
- private final Proc proc = new Proc();
public LongBased(LongValues values) {
this.values = values;
@@ -172,7 +172,14 @@ public Iter getIter(int docId) {
@Override
public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- values.forEachValueInDoc(docId, this.proc.reset(proc));
+ if (values.hasValue(docId)) {
+ final LongValues.Iter longIter = values.getIter(docId);
+ while(longIter.hasNext()) {
+ proc.onValue(docId, longIter.next());
+ }
+ } else {
+ proc.onMissing(docId);
+ }
}
static class ValueIter implements Iter {
@@ -195,26 +202,6 @@ public double next() {
}
}
- static class Proc implements LongValues.ValueInDocProc {
-
- private ValueInDocProc proc;
-
- private Proc reset(ValueInDocProc proc) {
- this.proc = proc;
- return this;
- }
-
- @Override
- public void onValue(int docId, long value) {
- this.proc.onValue(docId, (double) value);
- }
-
- @Override
- public void onMissing(int docId) {
- this.proc.onMissing(docId);
- }
- }
-
}
public static class FilteredDoubleValues implements DoubleValues {
diff --git a/src/main/java/org/elasticsearch/index/fielddata/LongValues.java b/src/main/java/org/elasticsearch/index/fielddata/LongValues.java
index 1dec9ad5cea6b..c32ad15ce47b2 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/LongValues.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/LongValues.java
@@ -20,46 +20,116 @@
package org.elasticsearch.index.fielddata;
import org.elasticsearch.ElasticSearchIllegalStateException;
-import org.elasticsearch.index.fielddata.util.LongArrayRef;
+import org.elasticsearch.index.fielddata.ordinals.Ordinals;
+import org.elasticsearch.index.fielddata.ordinals.Ordinals.Docs;
/**
*/
-public interface LongValues {
+public abstract class LongValues {
- static final LongValues EMPTY = new Empty();
+ public static final LongValues EMPTY = new Empty();
+ private final boolean multiValued;
+ protected final Iter.Single iter = new Iter.Single();
+
+
+ protected LongValues(boolean multiValued) {
+ this.multiValued = multiValued;
+ }
/**
* Is one of the documents in this field data values is multi valued?
*/
- boolean isMultiValued();
+ public final boolean isMultiValued() {
+ return multiValued;
+ }
/**
* Is there a value for this doc?
*/
- boolean hasValue(int docId);
+ public abstract boolean hasValue(int docId);
- long getValue(int docId);
+ public abstract long getValue(int docId);
- long getValueMissing(int docId, long missingValue);
+ public long getValueMissing(int docId, long missingValue) {
+ if (hasValue(docId)) {
+ return getValue(docId);
+ }
+ return missingValue;
+ }
+
+ public Iter getIter(int docId) {
+ assert !isMultiValued();
+ if (hasValue(docId)) {
+ return iter.reset(getValue(docId));
+ } else {
+ return Iter.Empty.INSTANCE;
+ }
+ }
- Iter getIter(int docId);
+
+ public static abstract class DenseLongValues extends LongValues {
+
+
+ protected DenseLongValues(boolean multiValued) {
+ super(multiValued);
+ }
+
+ @Override
+ public final boolean hasValue(int docId) {
+ return true;
+ }
- void forEachValueInDoc(int docId, ValueInDocProc proc);
+ public final long getValueMissing(int docId, long missingValue) {
+ assert hasValue(docId);
+ assert !isMultiValued();
+ return getValue(docId);
+ }
+
+ public final Iter getIter(int docId) {
+ assert hasValue(docId);
+ assert !isMultiValued();
+ return iter.reset(getValue(docId));
+ }
+
+ }
+
+ public static abstract class OrdBasedLongValues extends LongValues {
+
+ protected final Docs ordinals;
+ private final Iter.Multi iter;
+
+ protected OrdBasedLongValues(Ordinals.Docs ordinals) {
+ super(ordinals.isMultiValued());
+ this.ordinals = ordinals;
+ iter = new Iter.Multi(this);
+ }
+
+ @Override
+ public final boolean hasValue(int docId) {
+ return ordinals.getOrd(docId) != 0;
+ }
- static interface ValueInDocProc {
+ @Override
+ public final long getValue(int docId) {
+ return getByOrd(ordinals.getOrd(docId));
+ }
+
+ protected abstract long getByOrd(int ord);
- void onValue(int docId, long value);
+ @Override
+ public final Iter getIter(int docId) {
+ return iter.reset(ordinals.getIter(docId));
+ }
- void onMissing(int docId);
}
- static interface Iter {
+ public static interface Iter {
boolean hasNext();
long next();
- static class Empty implements Iter {
+ public static class Empty implements Iter {
public static final Empty INSTANCE = new Empty();
@@ -74,7 +144,7 @@ public long next() {
}
}
- static class Single implements Iter {
+ static class Single implements Iter {
public long value;
public boolean done;
@@ -97,12 +167,41 @@ public long next() {
return value;
}
}
+
+ static class Multi implements Iter {
+
+ private org.elasticsearch.index.fielddata.ordinals.Ordinals.Docs.Iter ordsIter;
+ private int ord;
+ private OrdBasedLongValues values;
+
+ public Multi(OrdBasedLongValues values) {
+ this.values = values;
+ }
+
+ public Multi reset(Ordinals.Docs.Iter ordsIter) {
+ this.ordsIter = ordsIter;
+ this.ord = ordsIter.next();
+ return this;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return ord != 0;
+ }
+
+ @Override
+ public long next() {
+ long value = values.getByOrd(ord);
+ ord = ordsIter.next();
+ return value;
+ }
+ }
}
- static class Empty implements LongValues {
- @Override
- public boolean isMultiValued() {
- return false;
+ static class Empty extends LongValues {
+
+ public Empty() {
+ super(false);
}
@Override
@@ -115,34 +214,22 @@ public long getValue(int docId) {
throw new ElasticSearchIllegalStateException("Can't retrieve a value from an empty LongValues");
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- return missingValue;
- }
-
@Override
public Iter getIter(int docId) {
return Iter.Empty.INSTANCE;
}
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- proc.onMissing(docId);
- }
}
- public static class FilteredLongValues implements LongValues {
+ public static class FilteredLongValues extends LongValues {
protected final LongValues delegate;
public FilteredLongValues(LongValues delegate) {
+ super(delegate.isMultiValued());
this.delegate = delegate;
}
- public boolean isMultiValued() {
- return delegate.isMultiValued();
- }
-
public boolean hasValue(int docId) {
return delegate.hasValue(docId);
}
@@ -151,17 +238,9 @@ public long getValue(int docId) {
return delegate.getValue(docId);
}
- public long getValueMissing(int docId, long missingValue) {
- return delegate.getValueMissing(docId, missingValue);
- }
-
public Iter getIter(int docId) {
return delegate.getIter(docId);
}
-
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- delegate.forEachValueInDoc(docId, proc);
- }
}
}
diff --git a/src/main/java/org/elasticsearch/index/fielddata/StringValues.java b/src/main/java/org/elasticsearch/index/fielddata/StringValues.java
index 9cf2ca6addb52..77860e1cdd613 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/StringValues.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/StringValues.java
@@ -222,7 +222,6 @@ public static class LongBased implements StringValues {
private final StringArrayRef arrayScratch = new StringArrayRef(new String[1], 1);
private final ValuesIter valuesIter = new ValuesIter();
- private final Proc proc = new Proc();
public LongBased(LongValues values) {
this.values = values;
@@ -254,7 +253,14 @@ public Iter getIter(int docId) {
@Override
public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- values.forEachValueInDoc(docId, this.proc.reset(proc));
+ if (values.hasValue(docId)) {
+ final LongValues.Iter longIter = values.getIter(docId);
+ while(longIter.hasNext()) {
+ proc.onValue(docId, Long.toString(longIter.next()));
+ }
+ } else {
+ proc.onMissing(docId);
+ }
}
static class ValuesIter implements Iter {
@@ -277,25 +283,7 @@ public String next() {
}
}
- static class Proc implements LongValues.ValueInDocProc {
-
- private ValueInDocProc proc;
-
- private Proc reset(ValueInDocProc proc) {
- this.proc = proc;
- return this;
- }
-
- @Override
- public void onValue(int docId, long value) {
- proc.onValue(docId, Long.toString(value));
- }
-
- @Override
- public void onMissing(int docId) {
- proc.onMissing(docId);
- }
- }
+
}
public interface WithOrdinals extends StringValues {
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/ByteArrayAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/ByteArrayAtomicFieldData.java
index 565d0b89ba3eb..d84a072eef05f 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/ByteArrayAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/ByteArrayAtomicFieldData.java
@@ -140,90 +140,20 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values, ordinals.ordinals());
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.OrdBasedLongValues {
private final byte[] values;
- private final Ordinals.Docs ordinals;
-
- private final ValuesIter iter;
LongValues(byte[] values, Ordinals.Docs ordinals) {
+ super(ordinals);
this.values = values;
- this.ordinals = ordinals;
- this.iter = new ValuesIter(values);
- }
-
- @Override
- public boolean isMultiValued() {
- return ordinals.isMultiValued();
- }
-
- @Override
- public boolean hasValue(int docId) {
- return ordinals.getOrd(docId) != 0;
}
@Override
- public long getValue(int docId) {
- return (long) values[ordinals.getOrd(docId)];
+ protected long getByOrd(int ord) {
+ return (long) values[ord];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- int ord = ordinals.getOrd(docId);
- if (ord == 0) {
- return missingValue;
- } else {
- return (long) values[ord];
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset(ordinals.getIter(docId));
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- Ordinals.Docs.Iter iter = ordinals.getIter(docId);
- int ord = iter.next();
- if (ord == 0) {
- proc.onMissing(docId);
- return;
- }
- do {
- proc.onValue(docId, (long) values[ord]);
- } while ((ord = iter.next()) != 0);
- }
-
- static class ValuesIter implements Iter {
-
- private final byte[] values;
- private Ordinals.Docs.Iter ordsIter;
- private int ord;
-
- ValuesIter(byte[] values) {
- this.values = values;
- }
-
- public ValuesIter reset(Ordinals.Docs.Iter ordsIter) {
- this.ordsIter = ordsIter;
- this.ord = ordsIter.next();
- return this;
- }
-
- @Override
- public boolean hasNext() {
- return ord != 0;
- }
-
- @Override
- public long next() {
- byte value = values[ord];
- ord = ordsIter.next();
- return (long) value;
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -370,23 +300,17 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values, set);
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final byte[] values;
private final FixedBitSet set;
- private final Iter.Single iter = new Iter.Single();
-
LongValues(byte[] values, FixedBitSet set) {
+ super(false);
this.values = values;
this.set = set;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
@Override
public boolean hasValue(int docId) {
return set.get(docId);
@@ -397,32 +321,6 @@ public long getValue(int docId) {
return (long) values[docId];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- if (set.get(docId)) {
- return (long) values[docId];
- } else {
- return missingValue;
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- if (set.get(docId)) {
- return iter.reset((long) values[docId]);
- } else {
- return Iter.Empty.INSTANCE;
- }
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- if (set.get(docId)) {
- proc.onValue(docId, (long) values[docId]);
- } else {
- proc.onMissing(docId);
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -538,44 +436,21 @@ public DoubleValues getDoubleValues() {
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.DenseLongValues {
private final byte[] values;
- private final Iter.Single iter = new Iter.Single();
LongValues(byte[] values) {
+ super(false);
this.values = values;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
- @Override
- public boolean hasValue(int docId) {
- return true;
- }
@Override
public long getValue(int docId) {
return (long) values[docId];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- return (long) values[docId];
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset((long) values[docId]);
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- proc.onValue(docId, (long) values[docId]);
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/DoubleArrayAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/DoubleArrayAtomicFieldData.java
index 6e31d5abf9030..11375dbd8c223 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/DoubleArrayAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/DoubleArrayAtomicFieldData.java
@@ -232,88 +232,18 @@ public String next() {
}
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.OrdBasedLongValues {
private final double[] values;
- private final Ordinals.Docs ordinals;
- private final ValuesIter iter;
LongValues(double[] values, Ordinals.Docs ordinals) {
+ super(ordinals);
this.values = values;
- this.ordinals = ordinals;
- this.iter = new ValuesIter(values);
- }
-
- @Override
- public boolean isMultiValued() {
- return ordinals.isMultiValued();
- }
-
- @Override
- public boolean hasValue(int docId) {
- return ordinals.getOrd(docId) != 0;
- }
-
- @Override
- public long getValue(int docId) {
- return (long) values[ordinals.getOrd(docId)];
}
@Override
- public long getValueMissing(int docId, long missingValue) {
- int ord = ordinals.getOrd(docId);
- if (ord == 0) {
- return missingValue;
- } else {
- return (long) values[ord];
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset(ordinals.getIter(docId));
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- Ordinals.Docs.Iter iter = ordinals.getIter(docId);
- int ord = iter.next();
- if (ord == 0) {
- proc.onMissing(docId);
- return;
- }
- do {
- proc.onValue(docId, (long) values[ord]);
- } while ((ord = iter.next()) != 0);
- }
-
- static class ValuesIter implements LongValues.Iter {
-
- private final double[] values;
- private Ordinals.Docs.Iter ordsIter;
- private int ord;
-
- ValuesIter(double[] values) {
- this.values = values;
- }
-
- public ValuesIter reset(Ordinals.Docs.Iter ordsIter) {
- this.ordsIter = ordsIter;
- this.ord = ordsIter.next();
- return this;
- }
-
- @Override
- public boolean hasNext() {
- return ord != 0;
- }
-
- @Override
- public long next() {
- double value = values[ord];
- ord = ordsIter.next();
- return (long) value;
- }
+ protected final long getByOrd(int ord) {
+ return (long)values[ord];
}
}
@@ -459,23 +389,17 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values, set);
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final double[] values;
private final FixedBitSet set;
- private final Iter.Single iter = new Iter.Single();
-
LongValues(double[] values, FixedBitSet set) {
+ super(false);
this.values = values;
this.set = set;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
@Override
public boolean hasValue(int docId) {
return set.get(docId);
@@ -485,31 +409,6 @@ public boolean hasValue(int docId) {
public long getValue(int docId) {
return (long) values[docId];
}
-
- @Override
- public long getValueMissing(int docId, long missingValue) {
- if (set.get(docId)) {
- return (long) values[docId];
- } else {
- return missingValue;
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- if (set.get(docId)) {
- return iter.reset((long) values[docId]);
- } else {
- return Iter.Empty.INSTANCE;
- }
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- if (set.get(docId)) {
- proc.onValue(docId, (long) values[docId]);
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -656,45 +555,20 @@ public void forEachValueInDoc(int docId, ValueInDocProc proc) {
}
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.DenseLongValues {
private final double[] values;
- private final Iter.Single iter = new Iter.Single();
-
LongValues(double[] values) {
+ super(false);
this.values = values;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
- @Override
- public boolean hasValue(int docId) {
- return true;
- }
-
@Override
public long getValue(int docId) {
return (long) values[docId];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- return (long) values[docId];
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset((long) values[docId]);
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- proc.onValue(docId, (long) values[docId]);
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/FloatArrayAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/FloatArrayAtomicFieldData.java
index 168d1f282b079..af84e156c1460 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/FloatArrayAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/FloatArrayAtomicFieldData.java
@@ -146,88 +146,18 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values, ordinals.ordinals());
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.OrdBasedLongValues {
private final float[] values;
- private final Ordinals.Docs ordinals;
- private final ValuesIter iter;
LongValues(float[] values, Ordinals.Docs ordinals) {
+ super(ordinals);
this.values = values;
- this.ordinals = ordinals;
- this.iter = new ValuesIter(values);
- }
-
- @Override
- public boolean isMultiValued() {
- return ordinals.isMultiValued();
- }
-
- @Override
- public boolean hasValue(int docId) {
- return ordinals.getOrd(docId) != 0;
- }
-
- @Override
- public long getValue(int docId) {
- return (long) values[ordinals.getOrd(docId)];
}
@Override
- public long getValueMissing(int docId, long missingValue) {
- int ord = ordinals.getOrd(docId);
- if (ord == 0) {
- return missingValue;
- } else {
- return (long) values[ord];
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset(ordinals.getIter(docId));
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- Ordinals.Docs.Iter iter = ordinals.getIter(docId);
- int ord = iter.next();
- if (ord == 0) {
- proc.onMissing(docId);
- return;
- }
- do {
- proc.onValue(docId, (long) values[ord]);
- } while ((ord = iter.next()) != 0);
- }
-
- static class ValuesIter implements Iter {
-
- private final float[] values;
- private Ordinals.Docs.Iter ordsIter;
- private int ord;
-
- ValuesIter(float[] values) {
- this.values = values;
- }
-
- public ValuesIter reset(Ordinals.Docs.Iter ordsIter) {
- this.ordsIter = ordsIter;
- this.ord = ordsIter.next();
- return this;
- }
-
- @Override
- public boolean hasNext() {
- return ord != 0;
- }
-
- @Override
- public long next() {
- float value = values[ord];
- ord = ordsIter.next();
- return (long) value;
- }
+ public long getByOrd(int ord) {
+ return (long) values[ord];
}
}
@@ -374,22 +304,17 @@ public DoubleValues getDoubleValues() {
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final float[] values;
private final FixedBitSet set;
- private final Iter.Single iter = new Iter.Single();
LongValues(float[] values, FixedBitSet set) {
+ super(false);
this.values = values;
this.set = set;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
@Override
public boolean hasValue(int docId) {
return set.get(docId);
@@ -399,33 +324,6 @@ public boolean hasValue(int docId) {
public long getValue(int docId) {
return (long) values[docId];
}
-
- @Override
- public long getValueMissing(int docId, long missingValue) {
- if (set.get(docId)) {
- return (long) values[docId];
- } else {
- return missingValue;
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- if (set.get(docId)) {
- return iter.reset((long) values[docId]);
- } else {
- return Iter.Empty.INSTANCE;
- }
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- if (set.get(docId)) {
- proc.onValue(docId, (long) values[docId]);
- } else {
- proc.onMissing(docId);
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -541,44 +439,20 @@ public DoubleValues getDoubleValues() {
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.DenseLongValues {
private final float[] values;
- private final Iter.Single iter = new Iter.Single();
LongValues(float[] values) {
+ super(false);
this.values = values;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
- @Override
- public boolean hasValue(int docId) {
- return true;
- }
-
@Override
public long getValue(int docId) {
return (long) values[docId];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- return (long) values[docId];
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset((long) values[docId]);
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- proc.onValue(docId, (long) values[docId]);
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/IntArrayAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/IntArrayAtomicFieldData.java
index 7b7e8ab706a8c..269a96dc308d1 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/IntArrayAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/IntArrayAtomicFieldData.java
@@ -148,89 +148,20 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values, ordinals.ordinals());
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.OrdBasedLongValues {
private final int[] values;
- private final Ordinals.Docs ordinals;
- private final ValuesIter iter;
LongValues(int[] values, Ordinals.Docs ordinals) {
+ super(ordinals);
this.values = values;
- this.ordinals = ordinals;
- this.iter = new ValuesIter(values);
- }
-
- @Override
- public boolean isMultiValued() {
- return ordinals.isMultiValued();
- }
-
- @Override
- public boolean hasValue(int docId) {
- return ordinals.getOrd(docId) != 0;
- }
-
- @Override
- public long getValue(int docId) {
- return (long) values[ordinals.getOrd(docId)];
}
@Override
- public long getValueMissing(int docId, long missingValue) {
- int ord = ordinals.getOrd(docId);
- if (ord == 0) {
- return missingValue;
- } else {
- return (long) values[ord];
- }
+ public long getByOrd(int ord) {
+ return (long) values[ord];
}
- @Override
- public Iter getIter(int docId) {
- return iter.reset(ordinals.getIter(docId));
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- Ordinals.Docs.Iter iter = ordinals.getIter(docId);
- int ord = iter.next();
- if (ord == 0) {
- proc.onMissing(docId);
- return;
- }
- do {
- proc.onValue(docId, (long) values[ord]);
- } while ((ord = iter.next()) != 0);
- }
-
- static class ValuesIter implements Iter {
-
- private final int[] values;
- private Ordinals.Docs.Iter ordsIter;
- private int ord;
-
- ValuesIter(int[] values) {
- this.values = values;
- }
-
- public ValuesIter reset(Ordinals.Docs.Iter ordsIter) {
- this.ordsIter = ordsIter;
- this.ord = ordsIter.next();
- return this;
- }
-
- @Override
- public boolean hasNext() {
- return ord != 0;
- }
-
- @Override
- public long next() {
- int value = values[ord];
- ord = ordsIter.next();
- return (long) value;
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -375,22 +306,17 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values, set);
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final int[] values;
private final FixedBitSet set;
- private final Iter.Single iter = new Iter.Single();
LongValues(int[] values, FixedBitSet set) {
+ super(false);
this.values = values;
this.set = set;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
@Override
public boolean hasValue(int docId) {
return set.get(docId);
@@ -401,32 +327,6 @@ public long getValue(int docId) {
return (long) values[docId];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- if (set.get(docId)) {
- return (long) values[docId];
- } else {
- return missingValue;
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- if (set.get(docId)) {
- return iter.reset((long) values[docId]);
- } else {
- return Iter.Empty.INSTANCE;
- }
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- if (set.get(docId)) {
- proc.onValue(docId, (long) values[docId]);
- } else {
- proc.onMissing(docId);
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -540,45 +440,21 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values);
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.DenseLongValues {
private final int[] values;
- private final Iter.Single iter = new Iter.Single();
LongValues(int[] values) {
+ super(false);
assert values.length != 0;
this.values = values;
}
-
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
- @Override
- public boolean hasValue(int docId) {
- return true;
- }
-
+
@Override
public long getValue(int docId) {
return (long) values[docId];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- return (long) values[docId];
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset((long) values[docId]);
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- proc.onValue(docId, (long) values[docId]);
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/LongArrayAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/LongArrayAtomicFieldData.java
index 2a4237ec4481a..0b392ed2d7a94 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/LongArrayAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/LongArrayAtomicFieldData.java
@@ -226,88 +226,18 @@ public String next() {
}
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.OrdBasedLongValues {
private final long[] values;
- private final Ordinals.Docs ordinals;
- private final ValuesIter iter;
LongValues(long[] values, Ordinals.Docs ordinals) {
+ super(ordinals);
this.values = values;
- this.ordinals = ordinals;
- this.iter = new ValuesIter(values);
- }
-
- @Override
- public boolean isMultiValued() {
- return ordinals.isMultiValued();
- }
-
- @Override
- public boolean hasValue(int docId) {
- return ordinals.getOrd(docId) != 0;
- }
-
- @Override
- public long getValue(int docId) {
- return values[ordinals.getOrd(docId)];
}
-
+
@Override
- public long getValueMissing(int docId, long missingValue) {
- int ord = ordinals.getOrd(docId);
- if (ord == 0) {
- return missingValue;
- } else {
- return values[ord];
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset(ordinals.getIter(docId));
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- Ordinals.Docs.Iter iter = ordinals.getIter(docId);
- int ord = iter.next();
- if (ord == 0) {
- proc.onMissing(docId);
- return;
- }
- do {
- proc.onValue(docId, values[ord]);
- } while ((ord = iter.next()) != 0);
- }
-
- static class ValuesIter implements Iter {
-
- private final long[] values;
- private Ordinals.Docs.Iter ordsIter;
- private int ord;
-
- ValuesIter(long[] values) {
- this.values = values;
- }
-
- public ValuesIter reset(Ordinals.Docs.Iter ordsIter) {
- this.ordsIter = ordsIter;
- this.ord = ordsIter.next();
- return this;
- }
-
- @Override
- public boolean hasNext() {
- return ord != 0;
- }
-
- @Override
- public long next() {
- long value = values[ord];
- ord = ordsIter.next();
- return value;
- }
+ public long getByOrd(int ord) {
+ return values[ord];
}
}
@@ -502,22 +432,17 @@ public void forEachValueInDoc(int docId, ValueInDocProc proc) {
}
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final long[] values;
private final FixedBitSet set;
- private final Iter.Single iter = new Iter.Single();
LongValues(long[] values, FixedBitSet set) {
+ super(false);
this.values = values;
this.set = set;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
@Override
public boolean hasValue(int docId) {
return set.get(docId);
@@ -527,33 +452,6 @@ public boolean hasValue(int docId) {
public long getValue(int docId) {
return values[docId];
}
-
- @Override
- public long getValueMissing(int docId, long missingValue) {
- if (set.get(docId)) {
- return values[docId];
- } else {
- return missingValue;
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- if (set.get(docId)) {
- return iter.reset(values[docId]);
- } else {
- return Iter.Empty.INSTANCE;
- }
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- if (set.get(docId)) {
- proc.onValue(docId, values[docId]);
- } else {
- proc.onMissing(docId);
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -702,44 +600,21 @@ public void forEachValueInDoc(int docId, ValueInDocProc proc) {
}
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.DenseLongValues {
private final long[] values;
private final Iter.Single iter = new Iter.Single();
LongValues(long[] values) {
+ super(false);
this.values = values;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
- @Override
- public boolean hasValue(int docId) {
- return true;
- }
-
@Override
public long getValue(int docId) {
return values[docId];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- return values[docId];
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset(values[docId]);
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- proc.onValue(docId, values[docId]);
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/ShortArrayAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/ShortArrayAtomicFieldData.java
index ff3ccdfd0477b..68724c71d2442 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/ShortArrayAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/ShortArrayAtomicFieldData.java
@@ -21,11 +21,13 @@
import org.apache.lucene.util.FixedBitSet;
import org.elasticsearch.common.RamUsage;
-import org.elasticsearch.index.fielddata.*;
+import org.elasticsearch.index.fielddata.AtomicNumericFieldData;
+import org.elasticsearch.index.fielddata.BytesValues;
+import org.elasticsearch.index.fielddata.DoubleValues;
+import org.elasticsearch.index.fielddata.LongValues;
+import org.elasticsearch.index.fielddata.ScriptDocValues;
+import org.elasticsearch.index.fielddata.StringValues;
import org.elasticsearch.index.fielddata.ordinals.Ordinals;
-import org.elasticsearch.index.fielddata.util.DoubleArrayRef;
-import org.elasticsearch.index.fielddata.util.IntArrayRef;
-import org.elasticsearch.index.fielddata.util.LongArrayRef;
/**
*/
@@ -146,89 +148,20 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values, ordinals.ordinals());
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.OrdBasedLongValues {
private final short[] values;
- private final Ordinals.Docs ordinals;
- private final ValuesIter iter;
LongValues(short[] values, Ordinals.Docs ordinals) {
+ super(ordinals);
this.values = values;
- this.ordinals = ordinals;
- this.iter = new ValuesIter(values);
- }
-
- @Override
- public boolean isMultiValued() {
- return ordinals.isMultiValued();
- }
-
- @Override
- public boolean hasValue(int docId) {
- return ordinals.getOrd(docId) != 0;
- }
-
- @Override
- public long getValue(int docId) {
- return (long) values[ordinals.getOrd(docId)];
}
@Override
- public long getValueMissing(int docId, long missingValue) {
- int ord = ordinals.getOrd(docId);
- if (ord == 0) {
- return missingValue;
- } else {
- return (long) values[ord];
- }
+ public long getByOrd(int ord) {
+ return (long) values[ord];
}
- @Override
- public Iter getIter(int docId) {
- return iter.reset(ordinals.getIter(docId));
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- Ordinals.Docs.Iter iter = ordinals.getIter(docId);
- int ord = iter.next();
- if (ord == 0) {
- proc.onMissing(docId);
- return;
- }
- do {
- proc.onValue(docId, (long) values[ord]);
- } while ((ord = iter.next()) != 0);
- }
-
- static class ValuesIter implements Iter {
-
- private final short[] values;
- private Ordinals.Docs.Iter ordsIter;
- private int ord;
-
- ValuesIter(short[] values) {
- this.values = values;
- }
-
- public ValuesIter reset(Ordinals.Docs.Iter ordsIter) {
- this.ordsIter = ordsIter;
- this.ord = ordsIter.next();
- return this;
- }
-
- @Override
- public boolean hasNext() {
- return ord != 0;
- }
-
- @Override
- public long next() {
- short value = values[ord];
- ord = ordsIter.next();
- return (long) value;
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -373,22 +306,17 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values, set);
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final short[] values;
private final FixedBitSet set;
- private final Iter.Single iter = new Iter.Single();
LongValues(short[] values, FixedBitSet set) {
+ super(false);
this.values = values;
this.set = set;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
@Override
public boolean hasValue(int docId) {
return set.get(docId);
@@ -398,33 +326,6 @@ public boolean hasValue(int docId) {
public long getValue(int docId) {
return (long) values[docId];
}
-
- @Override
- public long getValueMissing(int docId, long missingValue) {
- if (set.get(docId)) {
- return (long) values[docId];
- } else {
- return missingValue;
- }
- }
-
- @Override
- public Iter getIter(int docId) {
- if (set.get(docId)) {
- return iter.reset((long) values[docId]);
- } else {
- return Iter.Empty.INSTANCE;
- }
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- if (set.get(docId)) {
- proc.onValue(docId, (long) values[docId]);
- } else {
- proc.onMissing(docId);
- }
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
@@ -541,44 +442,20 @@ public DoubleValues getDoubleValues() {
return new DoubleValues(values);
}
- static class LongValues implements org.elasticsearch.index.fielddata.LongValues {
+ static class LongValues extends org.elasticsearch.index.fielddata.LongValues.DenseLongValues {
private final short[] values;
- private final Iter.Single iter = new Iter.Single();
LongValues(short[] values) {
+ super(false);
this.values = values;
}
- @Override
- public boolean isMultiValued() {
- return false;
- }
-
- @Override
- public boolean hasValue(int docId) {
- return true;
- }
-
@Override
public long getValue(int docId) {
return (long) values[docId];
}
- @Override
- public long getValueMissing(int docId, long missingValue) {
- return (long) values[docId];
- }
-
- @Override
- public Iter getIter(int docId) {
- return iter.reset((long) values[docId]);
- }
-
- @Override
- public void forEachValueInDoc(int docId, ValueInDocProc proc) {
- proc.onValue(docId, (long) values[docId]);
- }
}
static class DoubleValues implements org.elasticsearch.index.fielddata.DoubleValues {
diff --git a/src/main/java/org/elasticsearch/search/facet/LongFacetAggregatorBase.java b/src/main/java/org/elasticsearch/search/facet/LongFacetAggregatorBase.java
new file mode 100644
index 0000000000000..f356c6e2d37c0
--- /dev/null
+++ b/src/main/java/org/elasticsearch/search/facet/LongFacetAggregatorBase.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to ElasticSearch and Shay Banon 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.search.facet;
+
+import org.elasticsearch.index.fielddata.LongValues;
+import org.elasticsearch.index.fielddata.LongValues.Iter;
+
+/**
+ * Simple Facet aggregator base class for {@link LongValues}
+ */
+public abstract class LongFacetAggregatorBase {
+ private int total;
+ private int missing;
+
+ public void onDoc(int docId, LongValues values) {
+ if (values.hasValue(docId)) {
+ final Iter iter = values.getIter(docId);
+ while(iter.hasNext()) {
+ onValue(docId, iter.next());
+ total++;
+ }
+ } else {
+ missing++;
+ }
+ }
+
+ protected abstract void onValue(int docId, long next);
+
+ public final int total() {
+ return total;
+ }
+
+ public final int missing() {
+ return missing;
+ }
+}
diff --git a/src/main/java/org/elasticsearch/search/facet/datehistogram/CountDateHistogramFacetExecutor.java b/src/main/java/org/elasticsearch/search/facet/datehistogram/CountDateHistogramFacetExecutor.java
index 497b03bdee516..b1ef4169b48ef 100644
--- a/src/main/java/org/elasticsearch/search/facet/datehistogram/CountDateHistogramFacetExecutor.java
+++ b/src/main/java/org/elasticsearch/search/facet/datehistogram/CountDateHistogramFacetExecutor.java
@@ -27,6 +27,7 @@
import org.elasticsearch.index.fielddata.LongValues;
import org.elasticsearch.search.facet.FacetExecutor;
import org.elasticsearch.search.facet.InternalFacet;
+import org.elasticsearch.search.facet.LongFacetAggregatorBase;
import java.io.IOException;
@@ -76,7 +77,7 @@ public void setNextReader(AtomicReaderContext context) throws IOException {
@Override
public void collect(int doc) throws IOException {
- values.forEachValueInDoc(doc, histoProc);
+ histoProc.onDoc(doc, values);
}
@Override
@@ -84,7 +85,7 @@ public void postCollection() {
}
}
- public static class DateHistogramProc implements LongValues.ValueInDocProc {
+ public static class DateHistogramProc extends LongFacetAggregatorBase {
private final TLongLongHashMap counts;
private final TimeZoneRounding tzRounding;
@@ -94,10 +95,6 @@ public DateHistogramProc(TLongLongHashMap counts, TimeZoneRounding tzRounding) {
this.tzRounding = tzRounding;
}
- @Override
- public void onMissing(int docId) {
- }
-
@Override
public void onValue(int docId, long value) {
counts.adjustOrPutValue(tzRounding.calc(value), 1, 1);
diff --git a/src/main/java/org/elasticsearch/search/facet/datehistogram/ValueDateHistogramFacetExecutor.java b/src/main/java/org/elasticsearch/search/facet/datehistogram/ValueDateHistogramFacetExecutor.java
index 19c18cd3c5d86..e723f6239ee3b 100644
--- a/src/main/java/org/elasticsearch/search/facet/datehistogram/ValueDateHistogramFacetExecutor.java
+++ b/src/main/java/org/elasticsearch/search/facet/datehistogram/ValueDateHistogramFacetExecutor.java
@@ -28,6 +28,7 @@
import org.elasticsearch.index.fielddata.LongValues;
import org.elasticsearch.search.facet.FacetExecutor;
import org.elasticsearch.search.facet.InternalFacet;
+import org.elasticsearch.search.facet.LongFacetAggregatorBase;
import java.io.IOException;
@@ -79,7 +80,7 @@ public void setNextReader(AtomicReaderContext context) throws IOException {
@Override
public void collect(int doc) throws IOException {
- keyValues.forEachValueInDoc(doc, histoProc);
+ histoProc.onDoc(doc, keyValues);
}
@Override
@@ -87,7 +88,7 @@ public void postCollection() {
}
}
- public static class DateHistogramProc implements LongValues.ValueInDocProc {
+ public static class DateHistogramProc extends LongFacetAggregatorBase {
final ExtTLongObjectHashMap<InternalFullDateHistogramFacet.FullEntry> entries;
private final TimeZoneRounding tzRounding;
@@ -101,10 +102,6 @@ public DateHistogramProc(TimeZoneRounding tzRounding, ExtTLongObjectHashMap<Inte
this.entries = entries;
}
- @Override
- public void onMissing(int docId) {
- }
-
@Override
public void onValue(int docId, long value) {
long time = tzRounding.calc(value);
diff --git a/src/main/java/org/elasticsearch/search/facet/datehistogram/ValueScriptDateHistogramFacetExecutor.java b/src/main/java/org/elasticsearch/search/facet/datehistogram/ValueScriptDateHistogramFacetExecutor.java
index 0a5528b619889..33977a897e759 100644
--- a/src/main/java/org/elasticsearch/search/facet/datehistogram/ValueScriptDateHistogramFacetExecutor.java
+++ b/src/main/java/org/elasticsearch/search/facet/datehistogram/ValueScriptDateHistogramFacetExecutor.java
@@ -29,6 +29,7 @@
import org.elasticsearch.script.SearchScript;
import org.elasticsearch.search.facet.FacetExecutor;
import org.elasticsearch.search.facet.InternalFacet;
+import org.elasticsearch.search.facet.LongFacetAggregatorBase;
import java.io.IOException;
@@ -86,7 +87,7 @@ public void setNextReader(AtomicReaderContext context) throws IOException {
@Override
public void collect(int doc) throws IOException {
- keyValues.forEachValueInDoc(doc, histoProc);
+ histoProc.onDoc(doc, keyValues);
}
@Override
@@ -94,7 +95,7 @@ public void postCollection() {
}
}
- public static class DateHistogramProc implements LongValues.ValueInDocProc {
+ public static class DateHistogramProc extends LongFacetAggregatorBase {
private final TimeZoneRounding tzRounding;
protected final SearchScript valueScript;
@@ -107,10 +108,6 @@ public DateHistogramProc(TimeZoneRounding tzRounding, SearchScript valueScript,
this.entries = entries;
}
- @Override
- public void onMissing(int docId) {
- }
-
@Override
public void onValue(int docId, long value) {
valueScript.setNextDocId(docId);
diff --git a/src/main/java/org/elasticsearch/search/facet/terms/longs/TermsLongFacetExecutor.java b/src/main/java/org/elasticsearch/search/facet/terms/longs/TermsLongFacetExecutor.java
index 9497638747dfa..0f0ad77556cc4 100644
--- a/src/main/java/org/elasticsearch/search/facet/terms/longs/TermsLongFacetExecutor.java
+++ b/src/main/java/org/elasticsearch/search/facet/terms/longs/TermsLongFacetExecutor.java
@@ -34,6 +34,7 @@
import org.elasticsearch.script.SearchScript;
import org.elasticsearch.search.facet.FacetExecutor;
import org.elasticsearch.search.facet.InternalFacet;
+import org.elasticsearch.search.facet.LongFacetAggregatorBase;
import org.elasticsearch.search.facet.terms.TermsFacet;
import org.elasticsearch.search.facet.terms.support.EntryPriorityQueue;
import org.elasticsearch.search.internal.SearchContext;
@@ -50,7 +51,6 @@ public class TermsLongFacetExecutor extends FacetExecutor {
private final IndexNumericFieldData indexFieldData;
private final TermsFacet.ComparatorType comparatorType;
private final int size;
- private final int numberOfShards;
private final SearchScript script;
private final ImmutableSet<BytesRef> excluded;
@@ -63,7 +63,6 @@ public TermsLongFacetExecutor(IndexNumericFieldData indexFieldData, int size, Te
this.indexFieldData = indexFieldData;
this.size = size;
this.comparatorType = comparatorType;
- this.numberOfShards = context.numberOfShards();
this.script = script;
this.excluded = excluded;
@@ -147,7 +146,7 @@ public void setNextReader(AtomicReaderContext context) throws IOException {
@Override
public void collect(int doc) throws IOException {
- values.forEachValueInDoc(doc, aggregator);
+ aggregator.onDoc(doc, values);
}
@Override
@@ -200,13 +199,10 @@ public void onValue(int docId, long value) {
}
}
- public static class StaticAggregatorValueProc implements LongValues.ValueInDocProc {
+ public static class StaticAggregatorValueProc extends LongFacetAggregatorBase {
private final TLongIntHashMap facets;
- private int missing;
- private int total;
-
public StaticAggregatorValueProc(TLongIntHashMap facets) {
this.facets = facets;
}
@@ -214,24 +210,10 @@ public StaticAggregatorValueProc(TLongIntHashMap facets) {
@Override
public void onValue(int docId, long value) {
facets.adjustOrPutValue(value, 1, 1);
- total++;
- }
-
- @Override
- public void onMissing(int docId) {
- missing++;
}
public final TLongIntHashMap facets() {
return facets;
}
-
- public final int missing() {
- return this.missing;
- }
-
- public final int total() {
- return this.total;
- }
}
}
diff --git a/src/main/java/org/elasticsearch/search/facet/termsstats/longs/TermsStatsLongFacetExecutor.java b/src/main/java/org/elasticsearch/search/facet/termsstats/longs/TermsStatsLongFacetExecutor.java
index 014240fffd163..904be4e63e31c 100644
--- a/src/main/java/org/elasticsearch/search/facet/termsstats/longs/TermsStatsLongFacetExecutor.java
+++ b/src/main/java/org/elasticsearch/search/facet/termsstats/longs/TermsStatsLongFacetExecutor.java
@@ -31,6 +31,7 @@
import org.elasticsearch.script.SearchScript;
import org.elasticsearch.search.facet.FacetExecutor;
import org.elasticsearch.search.facet.InternalFacet;
+import org.elasticsearch.search.facet.LongFacetAggregatorBase;
import org.elasticsearch.search.facet.termsstats.TermsStatsFacet;
import org.elasticsearch.search.internal.SearchContext;
@@ -128,19 +129,18 @@ public void setNextReader(AtomicReaderContext context) throws IOException {
@Override
public void collect(int doc) throws IOException {
- keyValues.forEachValueInDoc(doc, aggregator);
+ aggregator.onDoc(doc, keyValues);
}
@Override
public void postCollection() {
- TermsStatsLongFacetExecutor.this.missing = aggregator.missing;
+ TermsStatsLongFacetExecutor.this.missing = aggregator.missing();
}
}
- public static class Aggregator implements LongValues.ValueInDocProc {
+ public static class Aggregator extends LongFacetAggregatorBase {
final ExtTLongObjectHashMap<InternalTermsStatsLongFacet.LongEntry> entries;
- int missing;
DoubleValues valueValues;
final ValueAggregator valueAggregator = new ValueAggregator();
@@ -160,10 +160,6 @@ public void onValue(int docId, long value) {
valueValues.forEachValueInDoc(docId, valueAggregator);
}
- @Override
- public void onMissing(int docId) {
- missing++;
- }
public static class ValueAggregator implements DoubleValues.ValueInDocProc {
diff --git a/src/test/java/org/elasticsearch/test/unit/index/fielddata/AbstractFieldDataTests.java b/src/test/java/org/elasticsearch/test/unit/index/fielddata/AbstractFieldDataTests.java
index 731c333205f48..dc1797186e200 100644
--- a/src/test/java/org/elasticsearch/test/unit/index/fielddata/AbstractFieldDataTests.java
+++ b/src/test/java/org/elasticsearch/test/unit/index/fielddata/AbstractFieldDataTests.java
@@ -19,26 +19,33 @@
package org.elasticsearch.test.unit.index.fielddata;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.sameInstance;
+
+import java.util.ArrayList;
+import java.util.List;
+
import org.apache.lucene.analysis.standard.StandardAnalyzer;
-import org.apache.lucene.index.*;
+import org.apache.lucene.index.AtomicReader;
+import org.apache.lucene.index.AtomicReaderContext;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.store.RAMDirectory;
-import org.apache.lucene.util.BytesRef;
-import org.elasticsearch.common.lucene.HashedBytesRef;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.index.Index;
-import org.elasticsearch.index.fielddata.*;
+import org.elasticsearch.index.fielddata.DoubleValues;
+import org.elasticsearch.index.fielddata.FieldDataType;
+import org.elasticsearch.index.fielddata.IndexFieldData;
+import org.elasticsearch.index.fielddata.IndexFieldDataService;
+import org.elasticsearch.index.fielddata.StringValues;
import org.elasticsearch.index.mapper.FieldMapper;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.sameInstance;
-
/**
*/
@Test
@@ -115,42 +122,6 @@ public void onMissing(int docId) {
}
}
- public static class LongValuesVerifierProc implements LongValues.ValueInDocProc {
-
- private static final Long MISSING = new Long(0);
-
- private final int docId;
- private final List<Long> expected = new ArrayList<Long>();
-
- private int idx;
-
- LongValuesVerifierProc(int docId) {
- this.docId = docId;
- }
-
- public LongValuesVerifierProc addExpected(long value) {
- expected.add(value);
- return this;
- }
-
- public LongValuesVerifierProc addMissing() {
- expected.add(MISSING);
- return this;
- }
-
- @Override
- public void onValue(int docId, long value) {
- assertThat(docId, equalTo(this.docId));
- assertThat(value, equalTo(expected.get(idx++)));
- }
-
- @Override
- public void onMissing(int docId) {
- assertThat(docId, equalTo(this.docId));
- assertThat(MISSING, sameInstance(expected.get(idx++)));
- }
- }
-
public static class DoubleValuesVerifierProc implements DoubleValues.ValueInDocProc {
private static final Double MISSING = new Double(0);
diff --git a/src/test/java/org/elasticsearch/test/unit/index/fielddata/NumericFieldDataTests.java b/src/test/java/org/elasticsearch/test/unit/index/fielddata/NumericFieldDataTests.java
index 73c24ff975982..999176424cb95 100644
--- a/src/test/java/org/elasticsearch/test/unit/index/fielddata/NumericFieldDataTests.java
+++ b/src/test/java/org/elasticsearch/test/unit/index/fielddata/NumericFieldDataTests.java
@@ -79,10 +79,6 @@ public void testSingleValueAllSetNumber() throws Exception {
assertThat(longValuesIter.next(), equalTo(3l));
assertThat(longValuesIter.hasNext(), equalTo(false));
- longValues.forEachValueInDoc(0, new LongValuesVerifierProc(0).addExpected(2l));
- longValues.forEachValueInDoc(1, new LongValuesVerifierProc(1).addExpected(1l));
- longValues.forEachValueInDoc(2, new LongValuesVerifierProc(2).addExpected(3l));
-
DoubleValues doubleValues = fieldData.getDoubleValues();
assertThat(doubleValues.isMultiValued(), equalTo(false));
@@ -172,10 +168,6 @@ public void testSingleValueWithMissingNumber() throws Exception {
assertThat(longValuesIter.next(), equalTo(3l));
assertThat(longValuesIter.hasNext(), equalTo(false));
- longValues.forEachValueInDoc(0, new LongValuesVerifierProc(0).addExpected(2l));
- longValues.forEachValueInDoc(1, new LongValuesVerifierProc(1).addMissing());
- longValues.forEachValueInDoc(2, new LongValuesVerifierProc(2).addExpected(3l));
-
DoubleValues doubleValues = fieldData.getDoubleValues();
assertThat(doubleValues.isMultiValued(), equalTo(false));
@@ -295,10 +287,6 @@ public void testMultiValueAllSetNumber() throws Exception {
assertThat(longValuesIter.next(), equalTo(3l));
assertThat(longValuesIter.hasNext(), equalTo(false));
- longValues.forEachValueInDoc(0, new LongValuesVerifierProc(0).addExpected(2l).addExpected(4l));
- longValues.forEachValueInDoc(1, new LongValuesVerifierProc(1).addExpected(1l));
- longValues.forEachValueInDoc(2, new LongValuesVerifierProc(2).addExpected(3l));
-
DoubleValues doubleValues = fieldData.getDoubleValues();
assertThat(doubleValues.isMultiValued(), equalTo(true));
@@ -375,10 +363,6 @@ public void testMultiValueWithMissingNumber() throws Exception {
assertThat(longValuesIter.next(), equalTo(3l));
assertThat(longValuesIter.hasNext(), equalTo(false));
- longValues.forEachValueInDoc(0, new LongValuesVerifierProc(0).addExpected(2l).addExpected(4l));
- longValues.forEachValueInDoc(1, new LongValuesVerifierProc(1).addMissing());
- longValues.forEachValueInDoc(2, new LongValuesVerifierProc(2).addExpected(3l));
-
DoubleValues doubleValues = fieldData.getDoubleValues();
assertThat(doubleValues.isMultiValued(), equalTo(true));
@@ -445,10 +429,6 @@ public void testMissingValueForAll() throws Exception {
longValuesIter = longValues.getIter(2);
assertThat(longValuesIter.hasNext(), equalTo(false));
- longValues.forEachValueInDoc(0, new LongValuesVerifierProc(0).addMissing());
- longValues.forEachValueInDoc(1, new LongValuesVerifierProc(1).addMissing());
- longValues.forEachValueInDoc(2, new LongValuesVerifierProc(2).addMissing());
-
// double values
DoubleValues doubleValues = fieldData.getDoubleValues();
|
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;
+ }
}
|
6e15ed3153e6fbcacd2b8798b9c5ebea29768210
|
kotlin
|
WithDeferredResolve removed (it was never used)--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/MutableClassDescriptorLite.java b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/MutableClassDescriptorLite.java
index 01dab6767eb70..da643a50d59df 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/MutableClassDescriptorLite.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/MutableClassDescriptorLite.java
@@ -37,8 +37,7 @@
/**
* @author Stepan Koltsov
*/
-public abstract class MutableClassDescriptorLite extends ClassDescriptorBase
- implements WithDeferredResolve {
+public abstract class MutableClassDescriptorLite extends ClassDescriptorBase {
private List<AnnotationDescriptor> annotations = Lists.newArrayList();
@@ -68,16 +67,6 @@ public MutableClassDescriptorLite(@NotNull DeclarationDescriptor containingDecla
this.kind = kind;
}
- @Override
- public void forceResolve() {
-
- }
-
- @Override
- public boolean isAlreadyResolved() {
- return false;
- }
-
@NotNull
@Override
public DeclarationDescriptor getContainingDeclaration() {
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/NamespaceDescriptorImpl.java b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/NamespaceDescriptorImpl.java
index e97dccd31d767..77345674a3657 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/NamespaceDescriptorImpl.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/NamespaceDescriptorImpl.java
@@ -28,7 +28,7 @@
/**
* @author abreslav
*/
-public class NamespaceDescriptorImpl extends AbstractNamespaceDescriptorImpl implements WithDeferredResolve {
+public class NamespaceDescriptorImpl extends AbstractNamespaceDescriptorImpl {
private WritableScope memberScope;
@@ -102,14 +102,4 @@ public ClassObjectStatus setClassObjectDescriptor(@NotNull MutableClassDescripto
return builder;
}
-
- @Override
- public void forceResolve() {
-
- }
-
- @Override
- public boolean isAlreadyResolved() {
- return false;
- }
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/WithDeferredResolve.java b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/WithDeferredResolve.java
deleted file mode 100644
index da3177fa2e45b..0000000000000
--- a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/WithDeferredResolve.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright 2010-2012 JetBrains s.r.o.
- *
- * 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.jetbrains.jet.lang.descriptors;
-
-/**
- * @author Nikolay Krasko
- */
-public interface WithDeferredResolve {
- void forceResolve();
- boolean isAlreadyResolved();
-}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalysisContext.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalysisContext.java
index bb5ec6502428e..ed81b3ddcba82 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalysisContext.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalysisContext.java
@@ -47,7 +47,7 @@ public class TopDownAnalysisContext implements BodiesResolveContext {
// File scopes - package scope extended with imports
protected final Map<JetFile, WritableScope> namespaceScopes = Maps.newHashMap();
- public final Map<JetDeclarationContainer, WithDeferredResolve> forDeferredResolver = Maps.newHashMap();
+ public final Map<JetDeclarationContainer, DeclarationDescriptor> forDeferredResolver = Maps.newHashMap();
public final Map<JetDeclarationContainer, JetScope> normalScope = Maps.newHashMap();
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
index 09edbc218c6c0..f207cd7a421be 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
@@ -112,7 +112,7 @@ public void process(
JetDeclarationContainer declarationContainer = forDeferredResolve.poll();
assert declarationContainer != null;
- WithDeferredResolve descriptorForDeferredResolve = context.forDeferredResolver.get(declarationContainer);
+ DeclarationDescriptor descriptorForDeferredResolve = context.forDeferredResolver.get(declarationContainer);
JetScope scope = context.normalScope.get(declarationContainer);
// Even more temp code
@@ -668,12 +668,12 @@ private ConstructorDescriptorImpl createPrimaryConstructorForObject(
private void prepareForDeferredCall(
@NotNull JetScope outerScope,
- @NotNull WithDeferredResolve withDeferredResolve,
+ @NotNull DeclarationDescriptor descriptorForDeferredResolve,
@NotNull JetDeclarationContainer container
) {
forDeferredResolve.add(container);
context.normalScope.put(container, outerScope);
- context.forDeferredResolver.put(container, withDeferredResolve);
+ context.forDeferredResolver.put(container, descriptorForDeferredResolve);
}
@Nullable
|
ac26e42d1e85deac0b7bfa50c3ca3e5298493dd4
|
ReactiveX-RxJava
|
use Java Subject<T
|
a
|
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 d5d8fb8297..a14e78329c 100644
--- a/rxjava-core/src/main/java/rx/Observable.java
+++ b/rxjava-core/src/main/java/rx/Observable.java
@@ -397,7 +397,7 @@ public Subscription subscribe(final Action1<? super T> onNext, final Action1<Thr
* @return a {@link ConnectableObservable} that upon connection causes the source Observable to
* push results into the specified {@link Subject}
*/
- public <R> ConnectableObservable<R> multicast(Subject<T, R> subject) {
+ public <R> ConnectableObservable<R> multicast(Subject<? super T, ? extends R> subject) {
return OperationMulticast.multicast(this, subject);
}
diff --git a/rxjava-core/src/main/java/rx/operators/OperationMulticast.java b/rxjava-core/src/main/java/rx/operators/OperationMulticast.java
index e83cfdaa03..e24c24a91a 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationMulticast.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationMulticast.java
@@ -27,7 +27,7 @@
import rx.subjects.Subject;
public class OperationMulticast {
- public static <T, R> ConnectableObservable<R> multicast(Observable<? extends T> source, final Subject<T, R> subject) {
+ public static <T, R> ConnectableObservable<R> multicast(Observable<? extends T> source, final Subject<? super T, ? extends R> subject) {
return new MulticastConnectableObservable<T, R>(source, subject);
}
@@ -35,11 +35,11 @@ private static class MulticastConnectableObservable<T, R> extends ConnectableObs
private final Object lock = new Object();
private final Observable<? extends T> source;
- private final Subject<T, R> subject;
+ private final Subject<? super T, ? extends R> subject;
private Subscription subscription;
- public MulticastConnectableObservable(Observable<? extends T> source, final Subject<T, R> subject) {
+ public MulticastConnectableObservable(Observable<? extends T> source, final Subject<? super T, ? extends R> subject) {
super(new OnSubscribeFunc<R>() {
@Override
public Subscription onSubscribe(Observer<? super R> observer) {
|
d52a7d799c2ab73dbc38de272d173bbe9cf08797
|
orientdb
|
Fixed issue reported by Steven about TX- congruency with nested records. The bug was reported in rollback.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
index 6f4d86d0df7..b873860ec1c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
@@ -795,11 +795,18 @@ public long createRecord(final ORecordId iRid, final byte[] iContent, final byte
ORecordCallback<Long> iCallback) {
checkOpeness();
- iRid.clusterPosition = createRecord(getClusterById(iRid.clusterId), iContent, iRecordType);
+ final OCluster cluster = getClusterById(iRid.clusterId);
+
+ if (txManager.isCommitting())
+ iRid.clusterPosition = txManager
+ .createRecord(txManager.getCurrentTransaction().getId(), cluster, iRid, iContent, iRecordType);
+ else
+ iRid.clusterPosition = createRecord(cluster, iContent, iRecordType);
return iRid.clusterPosition;
}
- public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache, ORecordCallback<ORawBuffer> iCallback) {
+ public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache,
+ ORecordCallback<ORawBuffer> iCallback) {
checkOpeness();
return readRecord(getClusterById(iRid.clusterId), iRid, true);
}
@@ -807,12 +814,24 @@ public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, bool
public int updateRecord(final ORecordId iRid, final byte[] iContent, final int iVersion, final byte iRecordType, final int iMode,
ORecordCallback<Integer> iCallback) {
checkOpeness();
- return updateRecord(getClusterById(iRid.clusterId), iRid, iContent, iVersion, iRecordType);
+
+ final OCluster cluster = getClusterById(iRid.clusterId);
+
+ if (txManager.isCommitting())
+ return txManager.updateRecord(txManager.getCurrentTransaction().getId(), cluster, iRid, iContent, iVersion, iRecordType);
+ else
+ return updateRecord(cluster, iRid, iContent, iVersion, iRecordType);
}
public boolean deleteRecord(final ORecordId iRid, final int iVersion, final int iMode, ORecordCallback<Boolean> iCallback) {
checkOpeness();
- return deleteRecord(getClusterById(iRid.clusterId), iRid, iVersion);
+
+ final OCluster cluster = getClusterById(iRid.clusterId);
+
+ if (txManager.isCommitting())
+ return txManager.deleteRecord(txManager.getCurrentTransaction().getId(), cluster, iRid.clusterPosition, iVersion);
+ else
+ return deleteRecord(cluster, iRid, iVersion);
}
public Set<String> getClusterNames() {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
index 79b7258e7d9..346cfa3307e 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java
@@ -37,6 +37,7 @@
public class OStorageLocalTxExecuter {
private final OStorageLocal storage;
private final OTxSegment txSegment;
+ private OTransaction currentTransaction;
public OStorageLocalTxExecuter(final OStorageLocal iStorage, final OStorageTxConfiguration iConfig) throws IOException {
storage = iStorage;
@@ -59,7 +60,7 @@ public void close() throws IOException {
}
protected long createRecord(final int iTxId, final OCluster iClusterSegment, final ORecordId iRid, final byte[] iContent,
- final byte iRecordType) throws IOException {
+ final byte iRecordType) {
iRid.clusterPosition = -1;
try {
@@ -108,7 +109,7 @@ protected int updateRecord(final int iTxId, final OCluster iClusterSegment, fina
return -1;
}
- protected void deleteRecord(final int iTxId, final OCluster iClusterSegment, final long iPosition, final int iVersion) {
+ protected boolean deleteRecord(final int iTxId, final OCluster iClusterSegment, final long iPosition, final int iVersion) {
try {
final ORecordId rid = new ORecordId(iClusterSegment.getId(), iPosition);
@@ -119,13 +120,14 @@ protected void deleteRecord(final int iTxId, final OCluster iClusterSegment, fin
txSegment.addLog(OTxSegment.OPERATION_DELETE, iTxId, iClusterSegment.getId(), iPosition, buffer.recordType, buffer.version,
buffer.buffer);
- storage.deleteRecord(iClusterSegment, rid, iVersion);
+ return storage.deleteRecord(iClusterSegment, rid, iVersion);
} catch (IOException e) {
OLogManager.instance().error(this, "Error on deleting entry #" + iPosition + " in log segment: " + iClusterSegment, e,
OTransactionException.class);
}
+ return false;
}
public OTxSegment getTxSegment() {
@@ -133,25 +135,30 @@ public OTxSegment getTxSegment() {
}
public void commitAllPendingRecords(final OTransaction iTx) throws IOException {
- // COPY ALL THE ENTRIES IN SEPARATE COLLECTION SINCE DURING THE COMMIT PHASE SOME NEW ENTRIES COULD BE CREATED AND
- // CONCURRENT-EXCEPTION MAY OCCURS
- final List<ORecordOperation> tmpEntries = new ArrayList<ORecordOperation>();
+ currentTransaction = iTx;
+ try {
+ // COPY ALL THE ENTRIES IN SEPARATE COLLECTION SINCE DURING THE COMMIT PHASE SOME NEW ENTRIES COULD BE CREATED AND
+ // CONCURRENT-EXCEPTION MAY OCCURS
+ final List<ORecordOperation> tmpEntries = new ArrayList<ORecordOperation>();
- while (iTx.getCurrentRecordEntries().iterator().hasNext()) {
- for (ORecordOperation txEntry : iTx.getCurrentRecordEntries())
- tmpEntries.add(txEntry);
+ while (iTx.getCurrentRecordEntries().iterator().hasNext()) {
+ for (ORecordOperation txEntry : iTx.getCurrentRecordEntries())
+ tmpEntries.add(txEntry);
- iTx.clearRecordEntries();
+ iTx.clearRecordEntries();
- if (!tmpEntries.isEmpty()) {
- for (ORecordOperation txEntry : tmpEntries)
- // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE
- commitEntry(iTx, txEntry, iTx.isUsingLog());
+ if (!tmpEntries.isEmpty()) {
+ for (ORecordOperation txEntry : tmpEntries)
+ // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE
+ commitEntry(iTx, txEntry, iTx.isUsingLog());
+ }
}
- }
- // UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT
- OTransactionAbstract.updateCacheFromEntries(storage, iTx, iTx.getAllRecordEntries(), true);
+ // UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT
+ OTransactionAbstract.updateCacheFromEntries(storage, iTx, iTx.getAllRecordEntries(), true);
+ } finally {
+ currentTransaction = null;
+ }
}
public void clearLogEntries(final OTransaction iTx) throws IOException {
@@ -273,4 +280,12 @@ private void commitEntry(final OTransaction iTx, final ORecordOperation txEntry,
if (txEntry.getRecord() instanceof OTxListener)
((OTxListener) txEntry.getRecord()).onEvent(txEntry, OTxListener.EVENT.AFTER_COMMIT);
}
+
+ public boolean isCommitting() {
+ return currentTransaction != null;
+ }
+
+ public OTransaction getCurrentTransaction() {
+ return currentTransaction;
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java
index 4d7f1c98259..0e88e90e161 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java
@@ -151,8 +151,8 @@ private void addRecord(final ORecordInternal<?> iRecord, final byte iStatus, fin
// && iRecord.getIdentity().isValid() && allEntries.containsKey(iRecord.getIdentity())) {
// if ((OStorage.CLUSTER_INDEX_NAME.equals(iClusterName) || iRecord.getIdentity().getClusterId() == database.getStorage()
// .getClusterIdByName(OStorage.CLUSTER_INDEX_NAME)) && database.getStorage() instanceof OStorageEmbedded) {
+
// I'M COMMITTING: BYPASS LOCAL BUFFER
-
switch (iStatus) {
case ORecordOperation.CREATED:
case ORecordOperation.UPDATED:
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java
index 0a88593ad2b..88786d54fd1 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java
@@ -21,6 +21,8 @@
import java.util.Vector;
import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
@@ -32,6 +34,7 @@
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
+import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE;
@@ -53,10 +56,17 @@ public class TransactionConsistencyTest {
// }
@Parameters(value = "url")
- public TransactionConsistencyTest(String iURL) throws IOException {
+ public TransactionConsistencyTest(@Optional(value = "memory:test") String iURL) throws IOException {
url = iURL;
}
+ @BeforeClass
+ public void init() {
+ ODatabaseDocumentTx database = new ODatabaseDocumentTx(url);
+ if ("memory:test".equals(database.getURL()))
+ database.create();
+ }
+
@Test
public void test1RollbackOnConcurrentException() throws IOException {
database1 = new ODatabaseDocumentTx(url).open("admin", "admin");
@@ -625,6 +635,7 @@ public void deletesWithinTransactionArentWorking() throws IOException {
db.close();
}
}
+
//
// @SuppressWarnings("unchecked")
// @Test
@@ -674,4 +685,109 @@ public void deletesWithinTransactionArentWorking() throws IOException {
// db.close();
// System.out.println("************ end testTransactionPopulatePartialDelete *******************");
// }
+
+ public void TransactionRollbackConstistencyTest() {
+ System.out.println("**************************TransactionRollbackConsistencyTest***************************************");
+ ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
+ db.open("admin", "admin");
+ OClass vertexClass = db.getMetadata().getSchema().createClass("TRVertex");
+ OClass edgeClass = db.getMetadata().getSchema().createClass("TREdge");
+ vertexClass.createProperty("in", OType.LINKSET, edgeClass);
+ vertexClass.createProperty("out", OType.LINKSET, edgeClass);
+ edgeClass.createProperty("in", OType.LINK, vertexClass);
+ edgeClass.createProperty("out", OType.LINK, vertexClass);
+
+ OClass personClass = db.getMetadata().getSchema().createClass("TRPerson", vertexClass);
+ personClass.createProperty("name", OType.STRING).createIndex(OClass.INDEX_TYPE.UNIQUE);
+ personClass.createProperty("surname", OType.STRING).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
+ personClass.createProperty("version", OType.INTEGER);
+
+ db.getMetadata().getSchema().save();
+ db.close();
+
+ final int cnt = 4;
+
+ db.open("admin", "admin");
+ db.begin();
+ Vector inserted = new Vector();
+
+ for (int i = 0; i < cnt; i++) {
+ ODocument person = new ODocument("TRPerson");
+ person.field("name", Character.toString((char) ('A' + i)));
+ person.field("surname", Character.toString((char) ('A' + (i % 3))));
+ person.field("myversion", 0);
+ person.field("in", new HashSet<ODocument>());
+ person.field("out", new HashSet<ODocument>());
+
+ if (i >= 1) {
+ ODocument edge = new ODocument("TREdge");
+ edge.field("in", person.getIdentity());
+ edge.field("out", inserted.elementAt(i - 1));
+ ((HashSet<ODocument>) person.field("out")).add(edge);
+ ((HashSet<ODocument>) ((ODocument) inserted.elementAt(i - 1)).field("in")).add(edge);
+ edge.save();
+ }
+ inserted.add(person);
+ person.save();
+ }
+ db.commit();
+
+ final List<ODocument> result1 = db.command(new OCommandSQL("select from TRPerson")).execute();
+ Assert.assertNotNull(result1);
+ Assert.assertEquals(result1.size(), 4);
+ System.out.println("Before transaction commit");
+ for (ODocument d : result1)
+ System.out.println(d);
+
+ try {
+ db.begin();
+ Vector inserted2 = new Vector();
+
+ for (int i = 0; i < cnt; i++) {
+ ODocument person = new ODocument("TRPerson");
+ person.field("name", Character.toString((char) ('a' + i)));
+ person.field("surname", Character.toString((char) ('a' + (i % 3))));
+ person.field("myversion", 0);
+ person.field("in", new HashSet<ODocument>());
+ person.field("out", new HashSet<ODocument>());
+
+ if (i >= 1) {
+ ODocument edge = new ODocument("TREdge");
+ edge.field("in", person.getIdentity());
+ edge.field("out", inserted2.elementAt(i - 1));
+ ((HashSet<ODocument>) person.field("out")).add(edge);
+ ((HashSet<ODocument>) ((ODocument) inserted2.elementAt(i - 1)).field("in")).add(edge);
+ edge.save();
+ }
+ inserted2.add(person);
+ person.save();
+ }
+
+ for (int i = 0; i < cnt; i++) {
+ if (i != cnt - 1) {
+ ((ODocument) inserted.elementAt(i)).field("myversion", 2);
+ ((ODocument) inserted.elementAt(i)).save();
+ }
+ }
+
+ ((ODocument) inserted.elementAt(cnt - 1)).delete();
+ ((ODocument) inserted.elementAt(cnt - 2)).setVersion(0);
+ ((ODocument) inserted.elementAt(cnt - 2)).save();
+ db.commit();
+ Assert.assertTrue(false);
+ } catch (OConcurrentModificationException e) {
+ Assert.assertTrue(true);
+ db.rollback();
+ }
+
+ final List<ODocument> result2 = db.command(new OCommandSQL("select from TRPerson")).execute();
+ Assert.assertNotNull(result2);
+ System.out.println("After transaction commit failure/rollback");
+ for (ODocument d : result2)
+ System.out.println(d);
+ Assert.assertEquals(result2.size(), 4);
+
+ db.close();
+ System.out.println("**************************TransactionRollbackConstistencyTest***************************************");
+ }
}
|
575b48a63e55b5216bf78ecf48621ac8f9f80729
|
drools
|
[DROOLS-820] reuse PomModel if already available--
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java
index bd16aa3b148..b710d0ffb6f 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java
@@ -91,6 +91,8 @@ public class KieBuilderImpl
private ClassLoader classLoader;
+ private PomModel pomModel;
+
public KieBuilderImpl(File file) {
this.srcMfs = new DiskResourceReader( file );
}
@@ -127,7 +129,7 @@ private PomModel init() {
// if pomXML is null it will generate a default, using default ReleaseId
// if pomXml is invalid, it assign pomModel to null
- PomModel pomModel = buildPomModel();
+ PomModel pomModel = getPomModel();
// if kModuleModelXML is null it will generate a default kModule, with a default kbase name
// if kModuleModelXML is invalid, it will kModule to null
@@ -283,6 +285,7 @@ private ResourceType getResourceType(String fileName) {
}
void cloneKieModuleForIncrementalCompilation() {
+ pomModel = null;
trgMfs = trgMfs.clone();
init();
kModule = kModule.cloneForIncrementalCompilation( releaseId, kModuleModel, trgMfs );
@@ -412,6 +415,20 @@ public static boolean setDefaultsforEmptyKieModule(KieModuleModel kModuleModel)
return false;
}
+ public PomModel getPomModel() {
+ if (pomModel == null) {
+ pomModel = buildPomModel();
+ }
+ return pomModel;
+ }
+
+ /**
+ * This can be used for performance reason to avoid the recomputation of the pomModel when it is already available
+ */
+ public void setPomModel( PomModel pomModel ) {
+ this.pomModel = pomModel;
+ }
+
private PomModel buildPomModel() {
pomXml = getOrGeneratePomXml( srcMfs );
if ( pomXml == null ) {
diff --git a/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java b/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java
index ff5b94cc5ef..3c0145ddff3 100644
--- a/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java
+++ b/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java
@@ -15,19 +15,16 @@
package org.kie.scanner;
+import org.drools.compiler.kie.builder.impl.InternalKieModule;
+import org.drools.compiler.kproject.models.KieModuleModelImpl;
import org.drools.core.common.ProjectClassLoader;
import org.drools.core.rule.KieModuleMetaInfo;
-import org.drools.compiler.kproject.ReleaseIdImpl;
-import org.drools.compiler.kproject.models.KieModuleModelImpl;
import org.drools.core.rule.TypeMetaInfo;
-import org.kie.api.builder.ReleaseId;
-import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.eclipse.aether.artifact.Artifact;
+import org.kie.api.builder.ReleaseId;
-import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
@@ -78,10 +75,8 @@ public KieModuleMetaDataImpl(File pomFile) {
}
public KieModuleMetaDataImpl(InternalKieModule kieModule) {
- String pomXmlPath = ((ReleaseIdImpl)kieModule.getReleaseId()).getPomXmlPath();
- InputStream pomStream = new ByteArrayInputStream(kieModule.getBytes(pomXmlPath));
- this.artifactResolver = getResolverFor(pomStream);
this.kieModule = kieModule;
+ this.artifactResolver = getResolverFor( kieModule.getPomModel() );
for (String file : kieModule.getFileNames()) {
if (!indexClass(file)) {
if (file.endsWith(KieModuleModelImpl.KMODULE_INFO_JAR_PATH)) {
@@ -148,9 +143,16 @@ private void init() {
if (releaseId != null) {
addArtifact(artifactResolver.resolveArtifact(releaseId));
}
- for (DependencyDescriptor dep : artifactResolver.getAllDependecies()) {
- addArtifact(artifactResolver.resolveArtifact(dep.getReleaseId()));
+ if ( kieModule != null ) {
+ for ( ReleaseId releaseId : kieModule.getPomModel().getDependencies() ) {
+ addArtifact( artifactResolver.resolveArtifact( releaseId ) );
+ }
+ } else {
+ for ( DependencyDescriptor dep : artifactResolver.getAllDependecies() ) {
+ addArtifact( artifactResolver.resolveArtifact( dep.getReleaseId() ) );
+ }
}
+
packages.addAll(classes.keySet());
packages.addAll(rulesByPackage.keySet());
}
|
f6bfcd9709fac61e3c4efe537f0b634bd9f6a09f
|
restlet-framework-java
|
- Continued NIO connector--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
index 79ba5f667b..5a69bb8dda 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
@@ -232,7 +232,7 @@ public void onSelected() {
if (getIoState() == IoState.READ_INTEREST) {
int result = readSocketBytes();
- while (getBuffer().hasRemaining()
+ while (getByteBuffer().hasRemaining()
&& (getMessageState() != MessageState.BODY)) {
if (getMessageState() == MessageState.START_LINE) {
readStartLine();
@@ -241,7 +241,7 @@ public void onSelected() {
}
// Attempt to read more available bytes
- if (!getBuffer().hasRemaining()
+ if (!getByteBuffer().hasRemaining()
&& (getMessageState() != MessageState.BODY)) {
result = readSocketBytes();
}
@@ -268,8 +268,8 @@ public void onSelected() {
* @throws IOException
*/
protected Parameter readHeader() throws IOException {
- Parameter header = HeaderReader.readHeader(getBuilder());
- getBuilder().delete(0, getBuilder().length());
+ Parameter header = HeaderReader.readHeader(getLineBuilder());
+ getLineBuilder().delete(0, getLineBuilder().length());
return header;
}
@@ -349,11 +349,11 @@ protected boolean readLine() throws IOException {
boolean result = false;
int next;
- while (!result && getBuffer().hasRemaining()) {
- next = (int) getBuffer().get();
+ while (!result && getByteBuffer().hasRemaining()) {
+ next = (int) getByteBuffer().get();
if (HeaderUtils.isCarriageReturn(next)) {
- next = (int) getBuffer().get();
+ next = (int) getByteBuffer().get();
if (HeaderUtils.isLineFeed(next)) {
result = true;
@@ -362,7 +362,7 @@ protected boolean readLine() throws IOException {
"Missing carriage return character at the end of HTTP line");
}
} else {
- getBuilder().append((char) next);
+ getLineBuilder().append((char) next);
}
}
@@ -376,9 +376,9 @@ protected boolean readLine() throws IOException {
* @throws IOException
*/
protected int readSocketBytes() throws IOException {
- getBuffer().clear();
- int result = getConnection().getSocketChannel().read(getBuffer());
- getBuffer().flip();
+ getByteBuffer().clear();
+ int result = getConnection().getSocketChannel().read(getByteBuffer());
+ getByteBuffer().flip();
return result;
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
index dc6e4532d2..d2f35bda1a 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
@@ -44,6 +44,9 @@ public enum MessageState {
HEADERS,
/** The body is being processed. */
- BODY;
+ BODY,
+
+ /** The end has been reached. */
+ END;
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
index a06ef2ff30..74a4f294c0 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
@@ -237,48 +237,82 @@ public int getSocketInterestOps() {
@Override
public void onSelected() {
try {
- if (getIoState() == IoState.WRITE_INTEREST) {
- Response message = getMessage();
+ Response message = getMessage();
- if (message != null) {
- boolean canWrite = true;
+ if (message != null) {
+ boolean canWrite = (getIoState() == IoState.WRITE_INTEREST);
+ boolean filling = getByteBuffer().hasRemaining();
- while (canWrite) {
- if (getBuffer().hasRemaining()
- && (getMessageState() != MessageState.BODY)) {
- if (getBuilder().length() == 0) {
+ while (canWrite) {
+ if (filling) {
+ // Before writing the byte buffer, we need to try
+ // to fill it as much as possible
+
+ if (getMessageState() == MessageState.BODY) {
+ // Writing the body doesn't rely on the line builder
+ // ...
+ } else {
+ // Write the start line or the headers relies on the
+ // line builder
+ if (getLineBuilder().length() == 0) {
+ // A new line can be written in the builder
writeLine();
}
- if (getBuilder().length() > 0) {
- int remaining = getBuffer().remaining();
+ if (getLineBuilder().length() > 0) {
+ // We can fill the byte buffer with the
+ // remaining line builder
+ int remaining = getByteBuffer().remaining();
- if (remaining >= getBuilder().length()) {
+ if (remaining >= getLineBuilder().length()) {
// Put the whole builder line in the buffer
- getBuffer()
+ getByteBuffer()
.put(
StringUtils
- .getLatin1Bytes(getBuilder()
+ .getLatin1Bytes(getLineBuilder()
.toString()));
- getBuilder().delete(0,
- getBuilder().length());
+ getLineBuilder().delete(0,
+ getLineBuilder().length());
} else {
- // Fill the buffer with part of the builder
- // line
- getBuffer()
+ // Put the maximum number of characters
+ // into the byte buffer
+ getByteBuffer()
.put(
StringUtils
- .getLatin1Bytes(getBuilder()
+ .getLatin1Bytes(getLineBuilder()
.substring(
0,
remaining)));
- getBuilder().delete(0, remaining);
+ getLineBuilder().delete(0, remaining);
}
}
+ }
+
+ canWrite = (getIoState() == IoState.WRITE_INTEREST);
+ filling = (getMessageState() != MessageState.END)
+ && getByteBuffer().hasRemaining();
+ } else {
+ // After filling the byte buffer, we can now flip it
+ // and start draining it.
+ getByteBuffer().flip();
+ int bytesWritten = getConnection().getSocketChannel()
+ .write(getByteBuffer());
+
+ if (bytesWritten == 0) {
+ // The byte buffer hasn't been written, the socket
+ // channel can't write more. We needs to put the
+ // byte buffer in the filling state again and wait
+ // for a new NIO selection.
+ getByteBuffer().flip();
+ canWrite = false;
+ } else if (getByteBuffer().hasRemaining()) {
+ // All the buffer couldn't be written. Compact the
+ // remaining
+ // bytes so that filling can happen again.
+ getByteBuffer().compact();
} else {
- getBuffer().flip();
- canWrite = (getConnection().getSocketChannel()
- .write(getBuffer()) > 0);
+ // The byte buffer has been fully written, but the
+ // socket channel wants more.
}
}
@@ -493,18 +527,18 @@ protected boolean writeLine() throws IOException {
if (getHeaderIndex() < getHeaders().size()) {
// Write header
Parameter header = getHeaders().get(getHeaderIndex());
- getBuilder().append(header.getName());
- getBuilder().append(": ");
- getBuilder().append(header.getValue());
- getBuilder().append('\r'); // CR
- getBuilder().append('\n'); // LF
+ getLineBuilder().append(header.getName());
+ getLineBuilder().append(": ");
+ getLineBuilder().append(header.getValue());
+ getLineBuilder().append('\r'); // CR
+ getLineBuilder().append('\n'); // LF
// Move to the next header
setHeaderIndex(getHeaderIndex() + 1);
} else {
// Write the end of the headers section
- getBuilder().append('\r'); // CR
- getBuilder().append('\n'); // LF
+ getLineBuilder().append('\r'); // CR
+ getLineBuilder().append('\n'); // LF
// Change state
setMessageState(MessageState.BODY);
@@ -530,18 +564,19 @@ protected void writeStartLine() throws IOException {
String protocolVersion = protocol.getVersion();
String version = protocol.getTechnicalName() + '/'
+ ((protocolVersion == null) ? "1.1" : protocolVersion);
- getBuilder().append(version);
- getBuilder().append(' ');
- getBuilder().append(getMessage().getStatus().getCode());
- getBuilder().append(' ');
+ getLineBuilder().append(version);
+ getLineBuilder().append(' ');
+ getLineBuilder().append(getMessage().getStatus().getCode());
+ getLineBuilder().append(' ');
if (getMessage().getStatus().getDescription() != null) {
- getBuilder().append(getMessage().getStatus().getDescription());
+ getLineBuilder().append(getMessage().getStatus().getDescription());
} else {
- getBuilder().append("Status " + getMessage().getStatus().getCode());
+ getLineBuilder().append(
+ "Status " + getMessage().getStatus().getCode());
}
- getBuilder().append("\r\n");
+ getLineBuilder().append("\r\n");
}
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
index 27cdf3577f..f903b7a56b 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
@@ -67,7 +67,7 @@ protected void readStartLine() throws IOException {
int i = 0;
int start = 0;
- int size = getBuilder().length();
+ int size = getLineBuilder().length();
char next;
if (size == 0) {
@@ -75,10 +75,10 @@ protected void readStartLine() throws IOException {
} else {
// Parse the request method
for (i = start; (requestMethod == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
if (HeaderUtils.isSpace(next)) {
- requestMethod = getBuilder().substring(start, i);
+ requestMethod = getLineBuilder().substring(start, i);
start = i + 1;
}
}
@@ -90,10 +90,10 @@ protected void readStartLine() throws IOException {
// Parse the request URI
for (i = start; (requestUri == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
if (HeaderUtils.isSpace(next)) {
- requestUri = getBuilder().substring(start, i);
+ requestUri = getLineBuilder().substring(start, i);
start = i + 1;
}
}
@@ -109,11 +109,11 @@ protected void readStartLine() throws IOException {
// Parse the protocol version
for (i = start; (version == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
}
if (i == size) {
- version = getBuilder().substring(start, i);
+ version = getLineBuilder().substring(start, i);
start = i + 1;
}
@@ -129,7 +129,7 @@ protected void readStartLine() throws IOException {
setMessage(response);
setMessageState(MessageState.HEADERS);
- getBuilder().delete(0, getBuilder().length());
+ getLineBuilder().delete(0, getLineBuilder().length());
}
} else {
// We need more characters before parsing
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
index 05f73ebf0d..be76f5b3a9 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
@@ -51,10 +51,7 @@
public abstract class Way {
/** The byte buffer. */
- private final ByteBuffer buffer;
-
- /** The line builder. */
- private final StringBuilder builder;
+ private final ByteBuffer byteBuffer;
/** The parent connection. */
private final Connection<?> connection;
@@ -62,6 +59,9 @@ public abstract class Way {
/** The IO state. */
private volatile IoState ioState;
+ /** The line builder. */
+ private final StringBuilder lineBuilder;
+
/** The current message exchanged. */
private volatile Response message;
@@ -84,8 +84,8 @@ public abstract class Way {
* The parent connection.
*/
public Way(Connection<?> connection) {
- this.buffer = ByteBuffer.allocate(NioUtils.BUFFER_SIZE);
- this.builder = new StringBuilder();
+ this.byteBuffer = ByteBuffer.allocate(NioUtils.BUFFER_SIZE);
+ this.lineBuilder = new StringBuilder();
this.connection = connection;
this.messageState = MessageState.START_LINE;
this.ioState = IoState.IDLE;
@@ -99,17 +99,8 @@ public Way(Connection<?> connection) {
*
* @return The byte buffer.
*/
- protected ByteBuffer getBuffer() {
- return buffer;
- }
-
- /**
- * Returns the line builder.
- *
- * @return The line builder.
- */
- protected StringBuilder getBuilder() {
- return builder;
+ protected ByteBuffer getByteBuffer() {
+ return byteBuffer;
}
/**
@@ -139,6 +130,15 @@ protected IoState getIoState() {
return ioState;
}
+ /**
+ * Returns the line builder.
+ *
+ * @return The line builder.
+ */
+ protected StringBuilder getLineBuilder() {
+ return lineBuilder;
+ }
+
/**
* Returns the logger.
*
|
d8fdf6abed4031adfa24a35ab23b78185cad6fc1
|
drools
|
[DROOLS-991] allow to configure maxEventsInMemory- in FileLogger--
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieLoggersTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieLoggersTest.java
index 16a433a6708..be9896a32e3 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieLoggersTest.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieLoggersTest.java
@@ -15,12 +15,6 @@
package org.drools.compiler.integrationtests;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-
import org.drools.compiler.Message;
import org.junit.Test;
import org.kie.api.KieServices;
@@ -31,12 +25,16 @@
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.event.rule.AfterMatchFiredEvent;
import org.kie.api.event.rule.AgendaEventListener;
-import org.kie.api.runtime.KieContainer;
-import org.kie.internal.io.ResourceFactory;
import org.kie.api.io.Resource;
import org.kie.api.logger.KieRuntimeLogger;
+import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
+import org.kie.internal.io.ResourceFactory;
+
+import java.io.File;
+
+import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class KieLoggersTest {
@@ -186,6 +184,45 @@ public void testKieFileLogger() throws Exception {
file = new File( fileName+".log" );
assertTrue( file.exists() );
+ assertTrue( file.length() > 0 );
+ file.delete();
+ }
+
+ @Test
+ public void testKieFileLoggerWithImmediateFlushing() throws Exception {
+ // DROOLS-991
+ String drl = "package org.drools.integrationtests\n" +
+ "import org.drools.compiler.Message;\n" +
+ "rule \"Hello World\"\n" +
+ " when\n" +
+ " m : Message( myMessage : message )\n" +
+ " then\n" +
+ "end";
+ // get the resource
+ Resource dt = ResourceFactory.newByteArrayResource(drl.getBytes()).setTargetPath( "org/drools/integrationtests/hello.drl" );
+
+ // create the builder
+ KieSession ksession = getKieSession(dt);
+
+ String fileName = "testKieFileLogger";
+ File file = new File(fileName+".log");
+ if( file.exists() ) {
+ file.delete();
+ }
+
+ // Setting maxEventsInMemory to 0 makes all events to be immediately flushed to the file
+ KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newFileLogger( ksession, fileName, 0 );
+
+ ksession.insert(new Message("Hello World"));
+ int fired = ksession.fireAllRules();
+ assertEquals( 1, fired );
+
+ // check that the file has been populated before closing it
+ file = new File( fileName+".log" );
+ assertTrue( file.exists() );
+ assertTrue( file.length() > 0 );
+
+ logger.close();
file.delete();
}
diff --git a/drools-core/src/main/java/org/drools/core/audit/KnowledgeRuntimeLoggerProviderImpl.java b/drools-core/src/main/java/org/drools/core/audit/KnowledgeRuntimeLoggerProviderImpl.java
index 99fc0618ba4..70b2b6036f8 100644
--- a/drools-core/src/main/java/org/drools/core/audit/KnowledgeRuntimeLoggerProviderImpl.java
+++ b/drools-core/src/main/java/org/drools/core/audit/KnowledgeRuntimeLoggerProviderImpl.java
@@ -31,7 +31,14 @@ public class KnowledgeRuntimeLoggerProviderImpl
public KnowledgeRuntimeLogger newFileLogger(KieRuntimeEventManager session,
String fileName) {
+ return newFileLogger(session, fileName, WorkingMemoryFileLogger.DEFAULT_MAX_EVENTS_IN_MEMORY);
+ }
+
+ public KnowledgeRuntimeLogger newFileLogger(KieRuntimeEventManager session,
+ String fileName,
+ int maxEventsInMemory) {
WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger( (KnowledgeRuntimeEventManager) session );
+ logger.setMaxEventsInMemory( maxEventsInMemory );
if ( fileName != null ) {
logger.setFileName(fileName);
}
diff --git a/drools-core/src/main/java/org/drools/core/audit/WorkingMemoryFileLogger.java b/drools-core/src/main/java/org/drools/core/audit/WorkingMemoryFileLogger.java
index 92a839e8d4d..493c090e2bf 100644
--- a/drools-core/src/main/java/org/drools/core/audit/WorkingMemoryFileLogger.java
+++ b/drools-core/src/main/java/org/drools/core/audit/WorkingMemoryFileLogger.java
@@ -16,9 +16,16 @@
package org.drools.core.audit;
+import com.thoughtworks.xstream.XStream;
+import org.drools.core.WorkingMemory;
+import org.drools.core.audit.event.LogEvent;
+import org.drools.core.util.IoUtils;
+import org.kie.internal.event.KnowledgeRuntimeEventManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
-import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
@@ -27,19 +34,6 @@
import java.util.ArrayList;
import java.util.List;
-import org.drools.core.WorkingMemory;
-import org.drools.core.audit.event.LogEvent;
-import org.drools.core.util.IoUtils;
-import org.kie.api.event.rule.AgendaGroupPoppedEvent;
-import org.kie.api.event.rule.AgendaGroupPushedEvent;
-import org.kie.api.event.rule.RuleFlowGroupActivatedEvent;
-import org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent;
-import org.kie.internal.event.KnowledgeRuntimeEventManager;
-
-import com.thoughtworks.xstream.XStream;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
/**
* A logger of events generated by a working memory. It stores its information
* in a file that can be specified. All the events logged are written to the
@@ -55,9 +49,11 @@ public class WorkingMemoryFileLogger extends WorkingMemoryLogger {
protected static final transient Logger logger = LoggerFactory.getLogger(WorkingMemoryFileLogger.class);
+ public static final int DEFAULT_MAX_EVENTS_IN_MEMORY = 1000;
+
private List<LogEvent> events = new ArrayList<LogEvent>();
private String fileName = "event";
- private int maxEventsInMemory = 1000;
+ private int maxEventsInMemory = DEFAULT_MAX_EVENTS_IN_MEMORY;
private int nbOfFile = 0;
private boolean split = true;
private boolean initialized = false;
|
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
|
c5eb3ffd538efde455c7f72444094a890fe318a5
|
internetarchive$heritrix3
|
[HER-1053] compressed HTTP fetch: "Accept-encoding: gzip"
[HER-728] Offer replay stream that has been un-chunked (whether because response was HTTP/1.1 or used chunked in HTTP/1.0 against spec)
[HER-1876] Offer HTTP/1.1 option - for chunked transfer-encoding (but not persistent connections)
* FetchHTTP
add 'acceptCompression' and 'useHTTP11' properties, both default false
* Recorder
track whether recorded-input is transfer-encoded (chunked) or content-encoded (gzip etc)
offer alternate replay streams for
(1) raw 'messageBody';
(2) entity (un-chunked if necessary)
(3) content (decompressed if necessary)
always content & GenericReplayCharSequence for CharSequence replays
* GenericReplayCharSequence
always use a stream (rather than random-access buffer)
always decode to prefix buffer first, so short content never touches disk no matter the encoding
* InMemoryReplayCharSequence
deleted; 'Generic' now works similarly for small content and anyway random-access for single-byte-encodings is now rarely possible (given deconding streams)
* RecordingInputStream, RecordingOutputStream
adjust for changed stream names, functionality moved to Recorder
* ReplayCharSequence
use Charset instances rather than names
* ReplayInputStream
add convenience constructor (and tmp-file-destroy) for copying any other inputStream into a seekable ReplayInputStream
|
p
|
https://github.com/internetarchive/heritrix3
|
diff --git a/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java b/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java
index d61d729b7..9294e08a4 100644
--- a/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java
+++ b/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java
@@ -20,26 +20,29 @@
package org.archive.io;
import java.io.BufferedReader;
-import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
-import java.nio.ByteBuffer;
+import java.io.Writer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
+import org.apache.commons.io.IOUtils;
import org.archive.util.DevUtils;
+import com.google.common.base.Charsets;
+import com.google.common.primitives.Ints;
+
/**
* (Replay)CharSequence view on recorded streams.
*
@@ -47,8 +50,8 @@
*
* <p>Call {@link close()} on this class when done to clean up resources.
*
- * @author stack
- * @author nlevitt
+ * @contributor stack
+ * @contributor nlevitt
* @version $Revision$, $Date$
*/
public class GenericReplayCharSequence implements ReplayCharSequence {
@@ -66,7 +69,7 @@ public class GenericReplayCharSequence implements ReplayCharSequence {
*
* <p>See <a ref="http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html">Encoding</a>.
*/
- private static final String WRITE_ENCODING = "UTF-16BE";
+ public static final Charset WRITE_ENCODING = Charsets.UTF_16BE;
private static final long MAP_MAX_BYTES = 64 * 1024 * 1024; // 64M
@@ -78,7 +81,7 @@ public class GenericReplayCharSequence implements ReplayCharSequence {
* <code>MAP_MAX_BYTES - MAP_TARGET_LEFT_PADDING</code>
* bytes to the right of the target.
*/
- private static final long MAP_TARGET_LEFT_PADDING_BYTES = (long) (MAP_MAX_BYTES * 0.2);
+ private static final long MAP_TARGET_LEFT_PADDING_BYTES = (long) (MAP_MAX_BYTES * 0.01);
/**
* Total length of character stream to replay minus the HTTP headers
@@ -108,11 +111,7 @@ public class GenericReplayCharSequence implements ReplayCharSequence {
private long bytesPerChar;
- private ByteBuffer mappedBuffer = null;
-
- private CharsetDecoder decoder = null;
-
- private ByteBuffer tempBuf = null;
+ private CharBuffer mappedBuffer = null;
/**
* File that has decoded content.
@@ -133,90 +132,53 @@ public class GenericReplayCharSequence implements ReplayCharSequence {
/**
* Constructor.
*
- * @param buffer In-memory buffer of recordings prefix. We read from
- * here first and will only go to the backing file if <code>size</code>
- * requested is greater than <code>buffer.length</code>.
- * @param size Total size of stream to replay in bytes. Used to find
- * EOS. This is total length of content including HTTP headers if
- * present.
* @param contentReplayInputStream inputStream of content
- * @param charsetName Encoding to use reading the passed prefix
- * buffer and backing file. For now, should be java canonical name for the
- * encoding. Must not be null.
+ * @param charset Encoding to use reading the passed prefix
+ * buffer and backing file. Must not be null.
* @param backingFilename Path to backing file with content in excess of
* whats in <code>buffer</code>.
*
* @throws IOException
*/
- public GenericReplayCharSequence(
- ReplayInputStream contentReplayInputStream, String backingFilename,
- String charsetName) throws IOException {
+ public GenericReplayCharSequence(InputStream contentReplayInputStream,
+ int prefixMax,
+ String backingFilename,
+ Charset charset) throws IOException {
super();
logger.fine("new GenericReplayCharSequence() characterEncoding="
- + charsetName + " backingFilename=" + backingFilename);
- Charset charset;
- try {
- charset = Charset.forName(charsetName);
- } catch (IllegalArgumentException e) {
- logger.log(Level.WARNING,"charset problem: "+charsetName,e);
- // TODO: better detection or default
- charset = Charset.forName(FALLBACK_CHARSET_NAME);
- }
- if (charset.newEncoder().maxBytesPerChar() == 1.0) {
- logger.fine("charset=" + charsetName
- + ": supports random access, using backing file directly");
- this.bytesPerChar = 1;
- this.backingFileIn = new FileInputStream(backingFilename);
- this.decoder = charset.newDecoder();
- this.prefixBuffer = this.decoder.decode(
- ByteBuffer.wrap(contentReplayInputStream.getBuffer()));
- } else {
- logger.fine("charset=" + charsetName
- + ": may not support random access, decoding to separate file");
-
- // decodes only up to Integer.MAX_VALUE characters
- decodeToFile(contentReplayInputStream, backingFilename, charsetName);
-
- this.bytesPerChar = 2;
- this.backingFileIn = new FileInputStream(decodedFile);
- this.decoder = Charset.forName(WRITE_ENCODING).newDecoder();
- this.prefixBuffer = CharBuffer.wrap("");
+ + charset + " backingFilename=" + backingFilename);
+
+ if(charset==null) {
+ charset = ReplayCharSequence.FALLBACK_CHARSET;
}
+ // decodes only up to Integer.MAX_VALUE characters
+ decode(contentReplayInputStream, prefixMax, backingFilename, charset);
- this.tempBuf = ByteBuffer.wrap(new byte[(int) this.bytesPerChar]);
- this.backingFileChannel = backingFileIn.getChannel();
+ this.bytesPerChar = 2;
- // we only support the first Integer.MAX_VALUE characters
- long wouldBeLength = prefixBuffer.limit() + backingFileChannel.size() / bytesPerChar;
- if (wouldBeLength <= Integer.MAX_VALUE) {
- this.length = (int) wouldBeLength;
- } else {
- logger.warning("input stream is longer than Integer.MAX_VALUE="
- + NumberFormat.getInstance().format(Integer.MAX_VALUE)
- + " characters -- only first "
- + NumberFormat.getInstance().format(Integer.MAX_VALUE)
- + " are accessible through this GenericReplayCharSequence");
- this.length = Integer.MAX_VALUE;
+ if(length>prefixBuffer.position()) {
+ this.backingFileIn = new FileInputStream(decodedFile);
+ this.backingFileChannel = backingFileIn.getChannel();
+ this.mapByteOffset = 0;
+ updateMemoryMappedBuffer();
}
-
- this.mapByteOffset = 0;
- updateMemoryMappedBuffer();
}
private void updateMemoryMappedBuffer() {
- long fileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters
- long mapSize = Math.min(fileLength * bytesPerChar - mapByteOffset, MAP_MAX_BYTES);
+ long charLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters
+ long mapSize = Math.min((charLength * bytesPerChar) - mapByteOffset, MAP_MAX_BYTES);
logger.fine("updateMemoryMappedBuffer: mapOffset="
+ NumberFormat.getInstance().format(mapByteOffset)
+ " mapSize=" + NumberFormat.getInstance().format(mapSize));
try {
- System.gc();
- System.runFinalization();
+ // TODO: stress-test without these possibly-costly requests!
+// System.gc();
+// System.runFinalization();
// TODO: Confirm the READ_ONLY works. I recall it not working.
// The buffers seem to always say that the buffer is writable.
mappedBuffer = backingFileChannel.map(
FileChannel.MapMode.READ_ONLY, mapByteOffset, mapSize)
- .asReadOnlyBuffer();
+ .asReadOnlyBuffer().asCharBuffer();
} catch (IOException e) {
// TODO convert this to a runtime error?
DevUtils.logger.log(Level.SEVERE,
@@ -237,46 +199,65 @@ private void updateMemoryMappedBuffer() {
*
* @throws IOException
*/
- private void decodeToFile(ReplayInputStream inStream,
- String backingFilename, String encoding) throws IOException {
+ protected void decode(InputStream inStream, int prefixMax,
+ String backingFilename, Charset charset) throws IOException {
+ // TODO: consider if BufferedReader is helping any
+ // TODO: consider adding TBW 'LimitReader' to stop reading at
+ // Integer.MAX_VALUE characters because of charAt(int) limit
BufferedReader reader = new BufferedReader(new InputStreamReader(
- inStream, encoding));
-
- this.decodedFile = new File(backingFilename + "." + WRITE_ENCODING);
+ inStream, charset));
logger.fine("decodeToFile: backingFilename=" + backingFilename
- + " encoding=" + encoding + " decodedFile=" + decodedFile);
+ + " encoding=" + charset + " decodedFile=" + decodedFile);
- FileOutputStream fos;
- try {
- fos = new FileOutputStream(this.decodedFile);
- } catch (FileNotFoundException e) {
- // Windows workaround attempt
- System.gc();
- System.runFinalization();
- this.decodedFile = new File(decodedFile.getAbsolutePath()+".win");
- logger.info("Windows 'file with a user-mapped section open' "
- + "workaround gc/finalization/name-extension performed.");
- // try again
- fos = new FileOutputStream(this.decodedFile);
- }
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,
- WRITE_ENCODING));
-
- int c;
+ this.prefixBuffer = CharBuffer.allocate(prefixMax);
+
long count = 0;
- while ((c = reader.read()) >= 0 && count < Integer.MAX_VALUE) {
- writer.write(c);
- count++;
- if (count % 100000000 == 0) {
- logger.fine("wrote " + count + " characters so far...");
+ while(count < prefixMax) {
+ int read = reader.read(prefixBuffer);
+ if(read<0) {
+ break;
+ }
+ count += read;
+ }
+
+ if(reader.ready()) {
+ // more to decode to file overflow
+ this.decodedFile = new File(backingFilename + "." + WRITE_ENCODING);
+
+ FileOutputStream fos;
+ try {
+ fos = new FileOutputStream(this.decodedFile);
+ } catch (FileNotFoundException e) {
+ // Windows workaround attempt
+ System.gc();
+ System.runFinalization();
+ this.decodedFile = new File(decodedFile.getAbsolutePath()+".win");
+ logger.info("Windows 'file with a user-mapped section open' "
+ + "workaround gc/finalization/name-extension performed.");
+ // try again
+ fos = new FileOutputStream(this.decodedFile);
}
+
+ Writer writer = new OutputStreamWriter(fos,WRITE_ENCODING);
+ count += IOUtils.copyLarge(reader, writer);
+ writer.close();
+ reader.close();
+ }
+
+ this.length = Ints.saturatedCast(count);
+ if(count>Integer.MAX_VALUE) {
+ logger.warning("input stream is longer than Integer.MAX_VALUE="
+ + NumberFormat.getInstance().format(Integer.MAX_VALUE)
+ + " characters -- only first "
+ + NumberFormat.getInstance().format(Integer.MAX_VALUE)
+ + " are accessible through this GenericReplayCharSequence");
}
- writer.close();
- logger.fine("decodeToFile: wrote " + count + " characters to "
- + decodedFile);
+ logger.fine("decode: decoded " + count + " characters" +
+ ((decodedFile==null) ? ""
+ : " ("+(count-prefixBuffer.length())+" to "+decodedFile+")"));
}
/**
@@ -296,10 +277,13 @@ public char charAt(int index) {
}
// otherwise we gotta get it from disk via memory map
- long fileIndex = (long) index - (long) prefixBuffer.limit();
- long fileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters
- if (fileIndex * bytesPerChar < mapByteOffset
- || fileIndex * bytesPerChar - mapByteOffset >= mappedBuffer.limit()) {
+ long charFileIndex = (long) index - (long) prefixBuffer.limit();
+ long charFileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters
+ if (charFileIndex * bytesPerChar < mapByteOffset) {
+ logger.log(Level.WARNING,"left-fault; probably don't want to use CharSequence that far backward");
+ }
+ if (charFileIndex * bytesPerChar < mapByteOffset
+ || charFileIndex - (mapByteOffset / bytesPerChar) >= mappedBuffer.limit()) {
// fault
/*
* mapByteOffset is bounded by 0 and file size +/- size of the map,
@@ -307,30 +291,13 @@ public char charAt(int index) {
* MAP_TARGET_LEFT_PADDING_BYTES</code> as it can while also not
* being smaller than it needs to be.
*/
- mapByteOffset = Math.max(0, fileIndex * bytesPerChar - MAP_TARGET_LEFT_PADDING_BYTES);
- mapByteOffset = Math.min(mapByteOffset, fileLength * bytesPerChar - MAP_MAX_BYTES);
+ mapByteOffset = Math.min(charFileIndex * bytesPerChar - MAP_TARGET_LEFT_PADDING_BYTES,
+ charFileLength * bytesPerChar - MAP_MAX_BYTES);
+ mapByteOffset = Math.max(0, mapByteOffset);
updateMemoryMappedBuffer();
}
- // CharsetDecoder always decodes up to the end of the ByteBuffer, so we
- // create a new ByteBuffer with only the bytes we're interested in.
- mappedBuffer.position((int) (fileIndex * bytesPerChar - mapByteOffset));
- mappedBuffer.get(tempBuf.array());
- tempBuf.position(0); // decoder starts at this position
-
- try {
- CharBuffer cbuf = decoder.decode(tempBuf);
- return cbuf.get();
- } catch (CharacterCodingException e) {
- logger.log(Level.FINE,"unable to get character at index=" + index + " (fileIndex=" + fileIndex + "): " + e, e);
- decodingExceptions++;
- if(codingException==null) {
- codingException = e;
- }
- // U+FFFD REPLACEMENT CHARACTER --
- // "used to replace an incoming character whose value is unknown or unrepresentable in Unicode"
- return (char) 0xfffd;
- }
+ return mappedBuffer.get((int)(charFileIndex-(mapByteOffset/bytesPerChar)));
}
public CharSequence subSequence(int start, int end) {
diff --git a/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java b/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java
deleted file mode 100644
index 41f805090..000000000
--- a/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * This file is part of the Heritrix web crawler (crawler.archive.org).
- *
- * Licensed to the Internet Archive (IA) by one or more individual
- * contributors.
- *
- * The IA 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.archive.io;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CodingErrorAction;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class InMemoryReplayCharSequence implements ReplayCharSequence {
-
- protected static Logger logger =
- Logger.getLogger(InMemoryReplayCharSequence.class.getName());
-
- /**
- * CharBuffer of decoded content.
- *
- * Content of this buffer is unicode.
- */
- private CharBuffer charBuffer = null;
-
- protected long decodingExceptionsCount = 0;
- protected CharacterCodingException codingException = null;
-
- /**
- * Constructor for all in-memory operation.
- *
- * @param buffer
- * @param size Total size of stream to replay in bytes. Used to find
- * EOS. This is total length of content including HTTP headers if
- * present.
- * @param responseBodyStart Where the response body starts in bytes.
- * Used to skip over the HTTP headers if present.
- * @param encoding Encoding to use reading the passed prefix buffer and
- * backing file. For now, should be java canonical name for the
- * encoding. Must not be null.
- *
- * @throws IOException
- */
- public InMemoryReplayCharSequence(byte[] buffer, long size,
- long responseBodyStart, String encoding) throws IOException {
- super();
- this.charBuffer = decodeInMemory(buffer, size, responseBodyStart,
- encoding);
- }
-
- /**
- * Decode passed buffer into a CharBuffer.
- *
- * This method decodes a memory buffer returning a memory buffer.
- *
- * @param buffer
- * @param size Total size of stream to replay in bytes. Used to find
- * EOS. This is total length of content including HTTP headers if
- * present.
- * @param responseBodyStart Where the response body starts in bytes.
- * Used to skip over the HTTP headers if present.
- * @param encoding Encoding to use reading the passed prefix buffer and
- * backing file. For now, should be java canonical name for the
- * encoding. Must not be null.
- *
- * @return A CharBuffer view on decodings of the contents of passed
- * buffer.
- */
- private CharBuffer decodeInMemory(byte[] buffer, long size,
- long responseBodyStart, String encoding) {
- ByteBuffer bb = ByteBuffer.wrap(buffer);
- // Move past the HTTP header if present.
- bb.position((int) responseBodyStart);
- bb.mark();
- // Set the end-of-buffer to be end-of-content.
- bb.limit((int) size);
- Charset charset;
- try {
- charset = Charset.forName(encoding);
- } catch (IllegalArgumentException e) {
- logger.log(Level.WARNING,"charset problem: "+encoding,e);
- // TODO: better detection or default
- charset = Charset.forName(FALLBACK_CHARSET_NAME);
- }
- try {
- return charset.newDecoder()
- .onMalformedInput(CodingErrorAction.REPORT)
- .onUnmappableCharacter(CodingErrorAction.REPORT)
- .decode(bb).asReadOnlyBuffer();
- } catch (CharacterCodingException cce) {
- bb.reset();
- decodingExceptionsCount++;
- codingException = cce;
- return charset.decode(bb).asReadOnlyBuffer();
- }
- }
-
- public void close() {
- this.charBuffer = null;
- }
-
- protected void finalize() throws Throwable {
- super.finalize();
- // Maybe TODO: eliminate close here, requiring explicit close instead
- close();
- }
-
- public int length() {
- return this.charBuffer.limit();
- }
-
- public char charAt(int index) {
- return this.charBuffer.get(index);
- }
-
- public CharSequence subSequence(int start, int end) {
- return new CharSubSequence(this, start, end);
- }
-
- public String toString() {
- StringBuffer sb = new StringBuffer(length());
- sb.append(this);
- return sb.toString();
- }
-
- /**
- * Return 1 if there were decoding problems (a full count isn't possible).
- *
- * @see org.archive.io.ReplayCharSequence#getDecodeExceptionCount()
- */
- @Override
- public long getDecodeExceptionCount() {
- return decodingExceptionsCount;
- }
-
- /* (non-Javadoc)
- * @see org.archive.io.ReplayCharSequence#getCodingException()
- */
- @Override
- public CharacterCodingException getCodingException() {
- return codingException;
- }
-
- @Override
- public boolean isOpen() {
- return this.charBuffer != null;
- }
-}
diff --git a/commons/src/main/java/org/archive/io/RecordingInputStream.java b/commons/src/main/java/org/archive/io/RecordingInputStream.java
index 9f3991cc8..f28f3d270 100644
--- a/commons/src/main/java/org/archive/io/RecordingInputStream.java
+++ b/commons/src/main/java/org/archive/io/RecordingInputStream.java
@@ -18,8 +18,6 @@
*/
package org.archive.io;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
@@ -149,8 +147,8 @@ public ReplayInputStream getReplayInputStream() throws IOException {
return this.recordingOutputStream.getReplayInputStream();
}
- public ReplayInputStream getContentReplayInputStream() throws IOException {
- return this.recordingOutputStream.getContentReplayInputStream();
+ public ReplayInputStream getMessageBodyReplayInputStream() throws IOException {
+ return this.recordingOutputStream.getMessageBodyReplayInputStream();
}
public long readFully() throws IOException {
@@ -249,11 +247,11 @@ public long getSize() {
}
public void markContentBegin() {
- this.recordingOutputStream.markContentBegin();
+ this.recordingOutputStream.markMessageBodyBegin();
}
public long getContentBegin() {
- return this.recordingOutputStream.getContentBegin();
+ return this.recordingOutputStream.getMessageBodyBegin();
}
public void startDigest() {
@@ -302,22 +300,6 @@ public byte[] getDigestValue() {
return this.recordingOutputStream.getDigestValue();
}
- public ReplayCharSequence getReplayCharSequence() throws IOException {
- return getReplayCharSequence(null);
- }
-
- /**
- * @param characterEncoding Encoding of recorded stream.
- * @return A ReplayCharSequence Will return null if an IOException. Call
- * close on returned RCS when done.
- * @throws IOException
- */
- public ReplayCharSequence getReplayCharSequence(String characterEncoding)
- throws IOException {
- return this.recordingOutputStream.
- getReplayCharSequence(characterEncoding);
- }
-
public long getResponseContentLength() {
return this.recordingOutputStream.getResponseContentLength();
}
@@ -326,18 +308,6 @@ public void closeRecorder() throws IOException {
this.recordingOutputStream.closeRecorder();
}
- /**
- * @param tempFile
- * @throws IOException
- */
- public void copyContentBodyTo(File tempFile) throws IOException {
- FileOutputStream fos = new FileOutputStream(tempFile);
- ReplayInputStream ris = getContentReplayInputStream();
- ris.readFullyTo(fos);
- fos.close();
- ris.close();
- }
-
/**
* @return True if we've been opened.
*/
diff --git a/commons/src/main/java/org/archive/io/RecordingOutputStream.java b/commons/src/main/java/org/archive/io/RecordingOutputStream.java
index ab211e697..d3756da0a 100644
--- a/commons/src/main/java/org/archive/io/RecordingOutputStream.java
+++ b/commons/src/main/java/org/archive/io/RecordingOutputStream.java
@@ -70,10 +70,10 @@ public class RecordingOutputStream extends OutputStream {
* Later passed to ReplayInputStream on creation. It uses it to know when
* EOS.
*/
- private long size = 0;
+ protected long size = 0;
- private String backingFilename;
- private OutputStream diskStream = null;
+ protected String backingFilename;
+ protected OutputStream diskStream = null;
/**
* Buffer we write recordings to.
@@ -106,7 +106,7 @@ public class RecordingOutputStream extends OutputStream {
private MessageDigest digest = null;
/**
- * Define for SHA1 alogarithm.
+ * Define for SHA1 algarithm.
*/
private static final String SHA1 = "SHA1";
@@ -130,7 +130,7 @@ public class RecordingOutputStream extends OutputStream {
/**
* When recording HTTP, where the content-body starts.
*/
- private long contentBeginMark;
+ protected long messageBodyBeginMark;
/**
* Stream to record.
@@ -186,7 +186,7 @@ public void open(OutputStream wrappedStream) throws IOException {
this.markPosition = 0;
this.maxPosition = 0;
this.size = 0;
- this.contentBeginMark = -1;
+ this.messageBodyBeginMark = -1;
// ensure recording turned on
this.recording = true;
// Always begins false; must use startDigest() to begin
@@ -245,7 +245,7 @@ public void write(byte[] b, int off, int len) throws IOException {
*/
protected void checkLimits() throws RecorderIOException {
// too much material before finding end of headers?
- if (contentBeginMark<0) {
+ if (messageBodyBeginMark<0) {
// no mark yet
if(position>MAX_HEADER_MATERIAL) {
throw new RecorderTooMuchHeaderException();
@@ -344,10 +344,10 @@ private void tailRecord(byte[] b, int off, int len) throws IOException {
}
public void close() throws IOException {
- if(contentBeginMark<0) {
+ if(messageBodyBeginMark<0) {
// if unset, consider 0 posn as content-start
// (so that a -1 never survives to replay step)
- contentBeginMark = 0;
+ messageBodyBeginMark = 0;
}
if (this.out != null) {
this.out.close();
@@ -396,7 +396,7 @@ public ReplayInputStream getReplayInputStream(long skip) throws IOException {
// -- the size will zero so any attempt at a read will get back EOF.
assert this.out == null: "Stream is still open.";
ReplayInputStream replay = new ReplayInputStream(this.buffer,
- this.size, this.contentBeginMark, this.backingFilename);
+ this.size, this.messageBodyBeginMark, this.backingFilename);
replay.skip(skip);
return replay;
}
@@ -407,8 +407,8 @@ public ReplayInputStream getReplayInputStream(long skip) throws IOException {
* @throws IOException
* @return An RIS.
*/
- public ReplayInputStream getContentReplayInputStream() throws IOException {
- return getReplayInputStream(this.contentBeginMark);
+ public ReplayInputStream getMessageBodyReplayInputStream() throws IOException {
+ return getReplayInputStream(this.messageBodyBeginMark);
}
public long getSize() {
@@ -416,20 +416,20 @@ public long getSize() {
}
/**
- * Remember the current position as the start of the "response
+ * Remember the current position as the start of the "message
* body". Useful when recording HTTP traffic as a way to start
* replays after the headers.
*/
- public void markContentBegin() {
- this.contentBeginMark = this.position;
+ public void markMessageBodyBegin() {
+ this.messageBodyBeginMark = this.position;
startDigest();
}
/**
- * Return stored content-begin-mark (which is also end-of-headers)
+ * Return stored message-body-begin-mark (which is also end-of-headers)
*/
- public long getContentBegin() {
- return this.contentBeginMark;
+ public long getMessageBodyBegin() {
+ return this.messageBodyBeginMark;
}
/**
@@ -499,51 +499,8 @@ public byte[] getDigestValue() {
return this.digest.digest();
}
- public ReplayCharSequence getReplayCharSequence() throws IOException {
- return getReplayCharSequence(null);
- }
-
- public ReplayCharSequence getReplayCharSequence(String characterEncoding)
- throws IOException {
- return getReplayCharSequence(characterEncoding, this.contentBeginMark);
- }
-
- /**
- * @param characterEncoding Encoding of recorded stream.
- * @return A ReplayCharSequence Will return null if an IOException. Call
- * close on returned RCS when done.
- * @throws IOException
- */
- public ReplayCharSequence getReplayCharSequence(String characterEncoding,
- long startOffset) throws IOException {
- if (characterEncoding == null) {
- characterEncoding = "UTF-8";
- }
- logger.fine("this.size=" + this.size + " this.buffer.length=" + this.buffer.length);
- if (this.size <= this.buffer.length) {
- logger.fine("using InMemoryReplayCharSequence");
- // raw data is all in memory; do in memory
- return new InMemoryReplayCharSequence(
- this.buffer,
- this.size,
- startOffset,
- characterEncoding);
- }
- else {
- logger.fine("using GenericReplayCharSequence");
- // raw data overflows to disk; use temp file
- ReplayInputStream ris = getReplayInputStream(startOffset);
- ReplayCharSequence rcs = new GenericReplayCharSequence(
- ris,
- this.backingFilename,
- characterEncoding);
- ris.close();
- return rcs;
- }
- }
-
public long getResponseContentLength() {
- return this.size - this.contentBeginMark;
+ return this.size - this.messageBodyBeginMark;
}
/**
@@ -553,6 +510,10 @@ public boolean isOpen() {
return this.out != null;
}
+ public int getBufferLength() {
+ return this.buffer.length;
+ }
+
/**
* When used alongside a mark-supporting RecordingInputStream, remember
* a position reachable by a future reset().
diff --git a/commons/src/main/java/org/archive/io/ReplayCharSequence.java b/commons/src/main/java/org/archive/io/ReplayCharSequence.java
index f5f15176b..99a04ec84 100644
--- a/commons/src/main/java/org/archive/io/ReplayCharSequence.java
+++ b/commons/src/main/java/org/archive/io/ReplayCharSequence.java
@@ -22,6 +22,9 @@
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.CharacterCodingException;
+import java.nio.charset.Charset;
+
+import com.google.common.base.Charsets;
/**
@@ -37,8 +40,7 @@ public interface ReplayCharSequence extends CharSequence, Closeable {
/** charset to use in replay when declared value
* is absent/illegal/unavailable */
-// String FALLBACK_CHARSET_NAME = "UTF-8";
- String FALLBACK_CHARSET_NAME = "ISO8859_1";
+ public Charset FALLBACK_CHARSET = Charsets.ISO_8859_1; // TODO: should this be UTF-8?
/**
* Call this method when done so implementation has chance to clean up
diff --git a/commons/src/main/java/org/archive/io/ReplayInputStream.java b/commons/src/main/java/org/archive/io/ReplayInputStream.java
index 04656d4bd..d50d00673 100644
--- a/commons/src/main/java/org/archive/io/ReplayInputStream.java
+++ b/commons/src/main/java/org/archive/io/ReplayInputStream.java
@@ -21,8 +21,13 @@
import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
+import org.apache.commons.io.IOUtils;
+import org.archive.util.ArchiveUtils;
+import org.archive.util.FileUtils;
+
/**
* Replays the bytes recorded from a RecordingInputStream or
@@ -34,6 +39,7 @@
*/
public class ReplayInputStream extends SeekInputStream
{
+ private static final int DEFAULT_BUFFER_SIZE = 256*1024; // 256KiB
private BufferedSeekInputStream diskStream;
private byte[] buffer;
private long position;
@@ -89,9 +95,43 @@ public ReplayInputStream(byte[] buffer, long size, String backingFilename)
this.buffer = buffer;
this.size = size;
if (size > buffer.length) {
- RandomAccessInputStream rais = new RandomAccessInputStream(
- new File(backingFilename));
- diskStream = new BufferedSeekInputStream(rais, 4096);
+ setupDiskStream(new File(backingFilename));
+ }
+ }
+
+ protected void setupDiskStream(File backingFile) throws IOException {
+ RandomAccessInputStream rais = new RandomAccessInputStream(backingFile);
+ diskStream = new BufferedSeekInputStream(rais, 4096);
+ }
+
+ File backingFile;
+
+ /**
+ * Create a ReplayInputStream from the given source stream. Requires
+ * reading the entire stream (and possibly overflowing to a temporary
+ * file). Primary reason for doing so would be to have a repositionable
+ * version of the original stream's contents.
+ * @param fillStream
+ * @throws IOException
+ */
+ public ReplayInputStream(InputStream fillStream) throws IOException {
+ this.buffer = new byte[DEFAULT_BUFFER_SIZE];
+ long count = ArchiveUtils.readFully(fillStream, buffer);
+ if(fillStream.available()>0) {
+ this.backingFile = File.createTempFile("tid"+Thread.currentThread().getId(), "ris");
+ count += FileUtils.readFullyToFile(fillStream, backingFile);
+ setupDiskStream(backingFile);
+ }
+ this.size = count;
+ }
+
+ /**
+ * Close & destroy any internally-generated temporary files.
+ */
+ public void destroy() {
+ IOUtils.closeQuietly(this);
+ if(backingFile!=null) {
+ FileUtils.deleteSoonerOrLater(backingFile);
}
}
diff --git a/commons/src/main/java/org/archive/util/Recorder.java b/commons/src/main/java/org/archive/util/Recorder.java
index 6247ba837..59ceeec21 100644
--- a/commons/src/main/java/org/archive/util/Recorder.java
+++ b/commons/src/main/java/org/archive/util/Recorder.java
@@ -22,15 +22,26 @@
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import java.io.InputStreamReader;
import java.io.OutputStream;
+import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.zip.DeflaterInputStream;
+import java.util.zip.GZIPInputStream;
+import org.apache.commons.httpclient.ChunkedInputStream;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.StringUtils;
+import org.archive.io.GenericReplayCharSequence;
import org.archive.io.RecordingInputStream;
import org.archive.io.RecordingOutputStream;
import org.archive.io.ReplayCharSequence;
import org.archive.io.ReplayInputStream;
+import com.google.common.base.Charsets;
+
/**
* Pairs together a RecordingInputStream and RecordingOutputStream
@@ -47,8 +58,8 @@ public class Recorder {
protected static Logger logger =
Logger.getLogger("org.archive.util.HttpRecorder");
- private static final int DEFAULT_OUTPUT_BUFFER_SIZE = 4096;
- private static final int DEFAULT_INPUT_BUFFER_SIZE = 65536;
+ private static final int DEFAULT_OUTPUT_BUFFER_SIZE = 16384;
+ private static final int DEFAULT_INPUT_BUFFER_SIZE = 524288;
private RecordingInputStream ris = null;
private RecordingOutputStream ros = null;
@@ -71,10 +82,16 @@ public class Recorder {
private static final String RECORDING_INPUT_STREAM_SUFFIX = ".ris";
/**
- * Response character encoding.
+ * recording-input (ris) content character encoding.
*/
private String characterEncoding = null;
+
+ /** whether recording-input (ris) message-body is chunked */
+ protected boolean inputIsChunked = false;
+ /** recording-input (ris) entity content-encoding (eg gzip, deflate), if any */
+ protected String contentEncoding = null;
+
private ReplayCharSequence replayCharSequence;
@@ -143,6 +160,12 @@ public Recorder(File tempDir, String backingFilenameBase) {
public InputStream inputWrap(InputStream is)
throws IOException {
logger.fine(Thread.currentThread().getName() + " wrapping input");
+
+ // discard any state from previously-recorded input
+ this.characterEncoding = null;
+ this.inputIsChunked = false;
+ this.contentEncoding = null;
+
this.ris.open(is);
return this.ris;
}
@@ -278,12 +301,43 @@ public void setCharacterEncoding(String characterEncoding) {
}
/**
- * @return Returns the characterEncoding.
+ * @return Returns the characterEncoding of input recording.
*/
public String getCharacterEncoding() {
return this.characterEncoding;
}
+
+ /**
+ * @param characterEncoding Character encoding of input recording.
+ */
+ public void setInputIsChunked(boolean chunked) {
+ this.inputIsChunked = chunked;
+ }
+
+ /**
+ * @param contentEncoding declared content-encoding of input recording.
+ */
+ public void setContentEncoding(String contentEncoding) {
+ this.contentEncoding = contentEncoding;
+ }
+
+ /**
+ * @return Returns the characterEncoding.
+ */
+ public String getContentEncoding() {
+ return this.contentEncoding;
+ }
+
+ /**
+ * @return
+ * @throws IOException
+ * @deprecated use getContentReplayCharSequence
+ */
+ public ReplayCharSequence getReplayCharSequence() throws IOException {
+ return getContentReplayCharSequence();
+ }
+
/**
* @return A ReplayCharSequence. Caller may call
* {@link ReplayCharSequence#close()} when finished. However, in
@@ -293,15 +347,50 @@ public String getCharacterEncoding() {
* @throws IOException
* @see {@link #endReplays()}
*/
- public ReplayCharSequence getReplayCharSequence() throws IOException {
+ public ReplayCharSequence getContentReplayCharSequence() throws IOException {
if (replayCharSequence == null || !replayCharSequence.isOpen()) {
- replayCharSequence = getRecordedInput().getReplayCharSequence(this.characterEncoding);
+ replayCharSequence = getContentReplayCharSequence(this.characterEncoding);
}
return replayCharSequence;
}
+
/**
+ * @param characterEncoding Encoding of recorded stream.
+ * @return A ReplayCharSequence Will return null if an IOException. Call
+ * close on returned RCS when done.
+ * @throws IOException
+ */
+ public ReplayCharSequence getContentReplayCharSequence(String encoding) throws IOException {
+ Charset charset = Charsets.UTF_8;
+ if (encoding != null) {
+ try {
+ charset = Charset.forName(encoding);
+ } catch (IllegalArgumentException e) {
+ logger.log(Level.WARNING,"charset problem: "+encoding,e);
+ // TODO: better detection or default
+ charset = ReplayCharSequence.FALLBACK_CHARSET;
+ }
+ }
+
+ logger.fine("using GenericReplayCharSequence");
+ // raw data overflows to disk; use temp file
+ InputStream ris = getContentReplayInputStream();
+ ReplayCharSequence rcs = new GenericReplayCharSequence(
+ ris,
+ this.ros.getBufferLength()/2,
+ this.backingFileBasename + RECORDING_OUTPUT_STREAM_SUFFIX,
+ charset);
+ ris.close();
+ return rcs;
+
+ }
+
+ /**
+ * Get a raw replay of all recorded data (including, for example, HTTP
+ * protocol headers)
+ *
* @return A replay input stream.
* @throws IOException
*/
@@ -309,6 +398,103 @@ public ReplayInputStream getReplayInputStream() throws IOException {
return getRecordedInput().getReplayInputStream();
}
+ /**
+ * Get a raw replay of the 'message-body'. For the common case of
+ * HTTP, this is the raw, possibly chunked-transfer-encoded message
+ * contents not including the leading headers.
+ *
+ * @return A replay input stream.
+ * @throws IOException
+ */
+ public ReplayInputStream getMessageBodyReplayInputStream() throws IOException {
+ return getRecordedInput().getMessageBodyReplayInputStream();
+ }
+
+ /**
+ * Get a raw replay of the 'entity'. For the common case of
+ * HTTP, this is the message-body after any (usually-unnecessary)
+ * transfer-decoding but before any content-encoding (eg gzip) decoding
+ *
+ * @return A replay input stream.
+ * @throws IOException
+ */
+ public InputStream getEntityReplayInputStream() throws IOException {
+ if(inputIsChunked) {
+ return new ChunkedInputStream(getRecordedInput().getMessageBodyReplayInputStream());
+ } else {
+ return getRecordedInput().getMessageBodyReplayInputStream();
+ }
+ }
+
+ /**
+ * Get a replay cued up for the 'content' (after all leading headers)
+ *
+ * TODO: handle chunking
+ * TODO: handle decompression, either here or in a parallel method
+ *
+ * @return A replay input stream.
+ * @throws IOException
+ */
+ public InputStream getContentReplayInputStream() throws IOException {
+ InputStream entityStream = getEntityReplayInputStream();
+ if(StringUtils.isEmpty(contentEncoding)) {
+ return entityStream;
+ } else if ("gzip".equalsIgnoreCase(contentEncoding) || "x-gzip".equalsIgnoreCase(contentEncoding)) {
+ try {
+ return new GZIPInputStream(entityStream);
+ } catch (IOException ioe) {
+ logger.log(Level.WARNING,"gzip problem; using raw entity instead",ioe);
+ IOUtils.closeQuietly(entityStream); // close partially-read stream
+ return getEntityReplayInputStream();
+ }
+ } else if ("deflate".equalsIgnoreCase(contentEncoding)) {
+ return new DeflaterInputStream(entityStream);
+ } else if ("identity".equalsIgnoreCase(contentEncoding)) {
+ return entityStream;
+ } else {
+ logger.log(Level.WARNING,"Unknown content-encoding '"+contentEncoding+"' declared; using raw entity instead");
+ return entityStream;
+ }
+ }
+
+ /**
+ * Return a short prefix of the presumed-textual content as a String.
+ *
+ * @param size max length of String to return
+ * @return String prefix, or empty String (with logged exception) on any error
+ */
+ public String getContentReplayPrefixString(int size) {
+ try {
+ InputStreamReader isr = (characterEncoding == null)
+ ? new InputStreamReader(getContentReplayInputStream(), Charsets.ISO_8859_1)
+ : new InputStreamReader(getContentReplayInputStream(), characterEncoding);
+ char[] chars = new char[size];
+ int count = isr.read(chars);
+ isr.close();
+ return new String(chars,0,count);
+ } catch (IOException e) {
+ logger.log(Level.SEVERE,"unable to get replay prefix string", e);
+ return "";
+ }
+ }
+
+ /**
+ * @param tempFile
+ * @throws IOException
+ */
+ public void copyContentBodyTo(File tempFile) throws IOException {
+ InputStream inStream = null;
+ OutputStream outStream = null;
+ try {
+ inStream = getContentReplayInputStream();
+ outStream = FileUtils.openOutputStream(tempFile);
+ IOUtils.copy(inStream, outStream);
+ } finally {
+ IOUtils.closeQuietly(inStream);
+ IOUtils.closeQuietly(outStream);
+ }
+ }
+
/**
* Record the input stream for later playback by an extractor, etc.
* This is convenience method used to setup an artificial HttpRecorder
diff --git a/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java b/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java
index 28a53bbdd..9e769c296 100644
--- a/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java
+++ b/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java
@@ -195,7 +195,8 @@ public void setMaxLengthBytes(long timeout) {
/**
* Accept Headers to include in each request. Each must be the complete
- * header, e.g., 'Accept-Language: en'.
+ * header, e.g., 'Accept-Language: en'. (Thus, this can also be used to
+ * other headers not beginning 'Accept-' as well.)
*/
{
setAcceptHeaders(new LinkedList<String>());
@@ -322,6 +323,34 @@ public void setShouldFetchBodyRule(DecideRule rule) {
*/
private static final String MIDFETCH_ABORT_LOG = "midFetchAbort";
+ /**
+ * Use HTTP/1.1. Note: even when offering an HTTP/1.1 request,
+ * Heritrix may not properly handle persistent/keep-alive connections,
+ * so the sendConnectionClose parameter should remain 'true'.
+ */
+ {
+ setUseHTTP11(false);
+ }
+ public boolean getUseHTTP11() {
+ return (Boolean) kp.get("useHTTP11");
+ }
+ public void setUseHTTP11(boolean useHTTP11) {
+ kp.put("useHTTP11",useHTTP11);
+ }
+
+ /**
+ * Set headers to accept compressed responses.
+ */
+ {
+ setAcceptCompression(false);
+ }
+ public boolean getAcceptCompression() {
+ return (Boolean) kp.get("acceptCompression");
+ }
+ public void setAcceptCompression(boolean acceptCompression) {
+ kp.put("acceptCompression",acceptCompression);
+ }
+
/**
* Send 'Connection: close' header with every request.
*/
@@ -622,6 +651,7 @@ protected void readResponseBody(HttpState state,
// Set the response charset into the HttpRecord if available.
setCharacterEncoding(curi, rec, method);
setSizes(curi, rec);
+ setOtherCodings(curi, rec, method);
}
if (digestContent) {
@@ -765,6 +795,32 @@ private void setCharacterEncoding(CrawlURI uri, final Recorder rec,
}
rec.setCharacterEncoding(encoding);
}
+
+ /**
+ * Set the transfer, content encodings based on headers (if necessary).
+ *
+ * @param rec
+ * Recorder for this request.
+ * @param method
+ * Method used for the request.
+ */
+ private void setOtherCodings(CrawlURI uri, final Recorder rec,
+ final HttpMethod method) {
+ Header transferCodingHeader = ((HttpMethodBase) method).getResponseHeader("Transfer-Encoding");
+ if (transferCodingHeader !=null) {
+ String te = transferCodingHeader.getValue().trim();
+ if(te.equalsIgnoreCase("chunked")) {
+ rec.setInputIsChunked(true);
+ } else {
+ logger.log(Level.WARNING,"Unknown transfer-encoding '"+te+"' for "+uri.getURI());
+ }
+ }
+ Header contentEncodingHeader = ((HttpMethodBase) method).getResponseHeader("Content-Encoding");
+ if (contentEncodingHeader!=null) {
+ String ce = contentEncodingHeader.getValue().trim();
+ rec.setContentEncoding(ce);
+ }
+ }
/**
* Cleanup after a failed method execute.
@@ -862,8 +918,9 @@ protected HostConfiguration configureMethod(CrawlURI curi,
ignoreCookies ? CookiePolicy.IGNORE_COOKIES
: CookiePolicy.BROWSER_COMPATIBILITY);
- // Use only HTTP/1.0 (to avoid receiving chunked responses)
- method.getParams().setVersion(HttpVersion.HTTP_1_0);
+ method.getParams().setVersion(getUseHTTP11()
+ ? HttpVersion.HTTP_1_1
+ : HttpVersion.HTTP_1_0);
UserAgentProvider uap = getUserAgentProvider();
String from = uap.getFrom();
@@ -1398,6 +1455,11 @@ public String report() {
private void setAcceptHeaders(CrawlURI curi, HttpMethod get) {
+ if(getAcceptCompression()) {
+ // we match the Firefox header exactly (ordering and whitespace)
+ // as a favor to caches
+ get.setRequestHeader("Accept-Encoding","gzip,deflate");
+ }
List<String> acceptHeaders = getAcceptHeaders();
if (acceptHeaders.isEmpty()) {
return;
|
0a9ff21ce61afcf58acc7173e733c8922e79e9af
|
arquillian$arquillian-graphene
|
Created AjaxSeleniumProxy for obtaining AjaxSelenium thread local context; moved unsupported Selenium API methods from TypedSelenium to UnsupportedTypedSelenium
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/library/src/main/java/org/jboss/test/selenium/AbstractTestCase.java b/library/src/main/java/org/jboss/test/selenium/AbstractTestCase.java
index 95cc7453d..c85c58446 100644
--- a/library/src/main/java/org/jboss/test/selenium/AbstractTestCase.java
+++ b/library/src/main/java/org/jboss/test/selenium/AbstractTestCase.java
@@ -34,6 +34,7 @@
import org.jboss.test.selenium.browser.BrowserType;
import org.jboss.test.selenium.encapsulated.JavaScript;
import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumImpl;
import org.jboss.test.selenium.locator.type.LocationStrategy;
import org.jboss.test.selenium.waiting.ajax.AjaxWaiting;
import org.jboss.test.selenium.waiting.conditions.AttributeEquals;
@@ -135,7 +136,7 @@ public void initializeParameters() throws MalformedURLException {
*/
@BeforeClass(dependsOnMethods = {"initializeParameters", "isTestBrowserEnabled"}, alwaysRun = true)
public void initializeBrowser() {
- selenium = new AjaxSelenium(getSeleniumHost(), getSeleniumPort(), browser, contextPath);
+ selenium = new AjaxSeleniumImpl(getSeleniumHost(), getSeleniumPort(), browser, contextPath);
selenium.start();
loadCustomLocationStrategies();
diff --git a/library/src/main/java/org/jboss/test/selenium/actions/Drag.java b/library/src/main/java/org/jboss/test/selenium/actions/Drag.java
index a630285f7..ef2eee12b 100644
--- a/library/src/main/java/org/jboss/test/selenium/actions/Drag.java
+++ b/library/src/main/java/org/jboss/test/selenium/actions/Drag.java
@@ -25,11 +25,11 @@
import org.apache.commons.lang.enums.EnumUtils;
import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.geometry.Point;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.waiting.selenium.SeleniumWaiting;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.waiting.Wait.waitSelenium;
/**
@@ -61,8 +61,13 @@ public class Drag {
/** The Constant FIRST_STEP. */
private static final int FIRST_STEP = 2;
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The point. */
- Point point;
+ private Point point;
// specifies phase in which is dragging state
/** The current phase. */
@@ -97,7 +102,6 @@ public Drag(ElementLocator itemToDrag, ElementLocator dropTarget) {
this.currentPhase = Phase.START;
this.itemToDrag = itemToDrag;
this.dropTarget = dropTarget;
- AjaxSelenium selenium = getCurrentSelenium();
x = selenium.getElementPositionLeft(dropTarget) - selenium.getElementPositionLeft(itemToDrag);
y = selenium.getElementPositionTop(dropTarget) - selenium.getElementPositionTop(itemToDrag);
}
@@ -180,7 +184,6 @@ private void processUntilPhase(Phase request) {
* the phase what should be executed
*/
private void executePhase(Phase phase) {
- AjaxSelenium selenium = getCurrentSelenium();
switch (phase) {
case START:
selenium.mouseDown(itemToDrag);
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/AjaxSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSelenium.java
index 1b5f415cc..553223b77 100644
--- a/library/src/main/java/org/jboss/test/selenium/framework/AjaxSelenium.java
+++ b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSelenium.java
@@ -21,19 +21,13 @@
*/
package org.jboss.test.selenium.framework;
-import java.net.URL;
-
-import org.jboss.test.selenium.browser.Browser;
import org.jboss.test.selenium.framework.internal.PageExtensions;
import org.jboss.test.selenium.framework.internal.SeleniumExtensions;
import org.jboss.test.selenium.interception.InterceptionProxy;
-import com.thoughtworks.selenium.CommandProcessor;
-import com.thoughtworks.selenium.HttpCommandProcessor;
-
/**
* <p>
- * Implementation of {@link TypedSelenium} extended by methods in {@link ExtendedTypedSelenium}.
+ * Implementation of {@link TypedSelenium} extended by methods in {@link ExtendedTypedSeleniumImpl}.
* </p>
*
* <p>
@@ -43,76 +37,7 @@
* @author <a href="mailto:[email protected]">Lukas Fryc</a>
* @version $Revision$
*/
-public class AjaxSelenium extends ExtendedTypedSelenium {
-
- /** The reference. */
- private static final ThreadLocal<AjaxSelenium> REFERENCE = new ThreadLocal<AjaxSelenium>();
-
- /** The JavaScript Extensions to tested page */
- PageExtensions pageExtensions;
-
- /** The JavaScript Extension to Selenium */
- SeleniumExtensions seleniumExtensions;
-
- /**
- * The command interception proxy
- */
- InterceptionProxy interceptionProxy;
-
- /**
- * Instantiates a new ajax selenium.
- */
- private AjaxSelenium() {
- }
-
- /**
- * Instantiates a new ajax selenium.
- *
- * @param serverHost
- * the server host
- * @param serverPort
- * the server port
- * @param browser
- * the browser
- * @param contextPathURL
- * the context path url
- */
- public AjaxSelenium(String serverHost, int serverPort, Browser browser, URL contextPathURL) {
- CommandProcessor commandProcessor =
- new HttpCommandProcessor(serverHost, serverPort, browser.getAsString(), contextPathURL.toString());
- interceptionProxy = new InterceptionProxy(commandProcessor);
- selenium = new ExtendedSelenium(interceptionProxy.getCommandProcessorProxy());
- pageExtensions = new PageExtensions(this);
- seleniumExtensions = new SeleniumExtensions(this);
- setCurrentSelenium(this);
- }
-
- /**
- * <p>
- * Sets the current context.
- * </p>
- *
- * <p>
- * <b>FIXME</b> not safe for multi-instance environment
- * </p>
- *
- * @param selenium
- * the new current context
- */
- public static void setCurrentSelenium(AjaxSelenium selenium) {
- REFERENCE.set(selenium);
- }
-
- /**
- * Gets the current context from Contextual objects.
- *
- * @param inContext
- * the in context
- * @return the current context
- */
- public static AjaxSelenium getCurrentSelenium() {
- return REFERENCE.get();
- }
+public interface AjaxSelenium extends ExtendedTypedSelenium, Cloneable {
/**
* <p>
@@ -125,9 +50,7 @@ public static AjaxSelenium getCurrentSelenium() {
*
* @return the PageExtensions associated with this AjaxSelenium object.
*/
- public PageExtensions getPageExtensions() {
- return pageExtensions;
- }
+ PageExtensions getPageExtensions();
/**
* <p>
@@ -140,30 +63,19 @@ public PageExtensions getPageExtensions() {
*
* @return the SeleniumExtensions associated with this AjaxSelenium object.
*/
- public SeleniumExtensions getSeleniumExtensions() {
- return seleniumExtensions;
- }
+ SeleniumExtensions getSeleniumExtensions();
/**
* Returns associated command interception proxy
*
* @return associated command interception proxy
*/
- public InterceptionProxy getInterceptionProxy() {
- return interceptionProxy;
- }
+ InterceptionProxy getInterceptionProxy();
/**
- * Immutable copy for copying this object.
+ * Immutable clone of this object.
*
- * @return the AjaxSelenium copy
+ * @return immutable clone of this object
*/
- public AjaxSelenium immutableCopy() {
- AjaxSelenium copy = new AjaxSelenium();
- copy.pageExtensions = new PageExtensions(copy);
- copy.seleniumExtensions = new SeleniumExtensions(copy);
- copy.interceptionProxy = this.interceptionProxy.immutableCopy();
- copy.selenium = new ExtendedSelenium(copy.interceptionProxy.getCommandProcessorProxy());
- return copy;
- }
+ AjaxSelenium clone() throws CloneNotSupportedException;
}
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumImpl.java b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumImpl.java
new file mode 100644
index 000000000..bf5727318
--- /dev/null
+++ b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumImpl.java
@@ -0,0 +1,157 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.selenium.framework;
+
+import java.net.URL;
+
+import org.jboss.test.selenium.browser.Browser;
+import org.jboss.test.selenium.framework.internal.PageExtensions;
+import org.jboss.test.selenium.framework.internal.SeleniumExtensions;
+import org.jboss.test.selenium.interception.InterceptionProxy;
+
+import com.thoughtworks.selenium.CommandProcessor;
+import com.thoughtworks.selenium.HttpCommandProcessor;
+
+/**
+ * <p>
+ * Implementation of {@link TypedSelenium} extended by methods in {@link ExtendedTypedSeleniumImpl}.
+ * </p>
+ *
+ * <p>
+ * Internally using {@link AjaxAwareInterceptor} and {@link InterceptionProxy}.
+ * </p>
+ *
+ * @author <a href="mailto:[email protected]">Lukas Fryc</a>
+ * @version $Revision$
+ */
+public class AjaxSeleniumImpl extends ExtendedTypedSeleniumImpl implements AjaxSelenium {
+
+ /** The reference. */
+ private static final ThreadLocal<AjaxSeleniumImpl> REFERENCE = new ThreadLocal<AjaxSeleniumImpl>();
+
+ /** The JavaScript Extensions to tested page */
+ PageExtensions pageExtensions;
+
+ /** The JavaScript Extension to Selenium */
+ SeleniumExtensions seleniumExtensions;
+
+ /**
+ * The command interception proxy
+ */
+ InterceptionProxy interceptionProxy;
+
+ /**
+ * Instantiates a new ajax selenium.
+ */
+ private AjaxSeleniumImpl() {
+ }
+
+ /**
+ * Instantiates a new ajax selenium.
+ *
+ * @param serverHost
+ * the server host
+ * @param serverPort
+ * the server port
+ * @param browser
+ * the browser
+ * @param contextPathURL
+ * the context path url
+ */
+ public AjaxSeleniumImpl(String serverHost, int serverPort, Browser browser, URL contextPathURL) {
+ CommandProcessor commandProcessor =
+ new HttpCommandProcessor(serverHost, serverPort, browser.getAsString(), contextPathURL.toString());
+ interceptionProxy = new InterceptionProxy(commandProcessor);
+ selenium = new ExtendedSelenium(interceptionProxy.getCommandProcessorProxy());
+ pageExtensions = new PageExtensions(this);
+ seleniumExtensions = new SeleniumExtensions(this);
+ setCurrentSelenium(this);
+ }
+
+ /**
+ * <p>
+ * Sets the current context.
+ * </p>
+ *
+ * <p>
+ * <b>FIXME</b> not safe for multi-instance environment
+ * </p>
+ *
+ * @param selenium
+ * the new current context
+ */
+ public static void setCurrentSelenium(AjaxSeleniumImpl selenium) {
+ REFERENCE.set(selenium);
+ }
+
+ /**
+ * Gets the current context from Contextual objects.
+ *
+ * @param inContext
+ * the in context
+ * @return the current context
+ */
+ static AjaxSeleniumImpl getCurrentSelenium() {
+ return REFERENCE.get();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.test.selenium.framework.AjaxSelenium#getPageExtensions()
+ */
+ public PageExtensions getPageExtensions() {
+ return pageExtensions;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.test.selenium.framework.AjaxSelenium#getSeleniumExtensions()
+ */
+ public SeleniumExtensions getSeleniumExtensions() {
+ return seleniumExtensions;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.test.selenium.framework.AjaxSelenium#getInterceptionProxy()
+ */
+ public InterceptionProxy getInterceptionProxy() {
+ return interceptionProxy;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.lang.Object#clone()
+ */
+ @Override
+ public AjaxSelenium clone() throws CloneNotSupportedException {
+ AjaxSeleniumImpl copy = new AjaxSeleniumImpl();
+ copy.pageExtensions = new PageExtensions(copy);
+ copy.seleniumExtensions = new SeleniumExtensions(copy);
+ copy.interceptionProxy = this.interceptionProxy.immutableCopy();
+ copy.selenium = new ExtendedSelenium(copy.interceptionProxy.getCommandProcessorProxy());
+ return copy;
+ }
+}
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumProxy.java b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumProxy.java
new file mode 100644
index 000000000..996c9449f
--- /dev/null
+++ b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumProxy.java
@@ -0,0 +1,62 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.selenium.framework;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+/**
+ * <p>
+ * Proxy to implementation of AjaxSelenium.
+ * </p>
+ *
+ * <p>
+ * Obtains AjaxSelenium from thread local context.
+ * </p>
+ *
+ * @author <a href="mailto:[email protected]">Lukas Fryc</a>
+ * @version $Revision$
+ */
+public final class AjaxSeleniumProxy implements InvocationHandler {
+
+ private AjaxSeleniumProxy() {
+ }
+
+ public static AjaxSelenium getInstance() {
+ return (AjaxSelenium) Proxy.newProxyInstance(AjaxSeleniumImpl.class.getClassLoader(), AjaxSeleniumImpl.class
+ .getInterfaces(), new AjaxSeleniumProxy());
+ }
+
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ Object result;
+ try {
+ result = method.invoke(AjaxSeleniumImpl.getCurrentSelenium(), args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ } catch (Exception e) {
+ throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
+ }
+ return result;
+ }
+}
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSelenium.java
index 7b46646e2..22056356c 100644
--- a/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSelenium.java
+++ b/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSelenium.java
@@ -25,25 +25,16 @@
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.locator.IterableLocator;
-import org.jboss.test.selenium.locator.JQueryLocator;
-import org.jboss.test.selenium.locator.LocatorUtils;
/**
- * Type-safe selenium wrapper for Selenium API with extension of some useful commands defined in
- * {@link ExtendedSelenium}
+ * <p>
+ * Extends the common Selenium API by other useful functions wrapped from {@link ExtendedSelenium}.
+ * </p>
*
* @author <a href="mailto:[email protected]">Lukas Fryc</a>
* @version $Revision$
*/
-public class ExtendedTypedSelenium extends DefaultTypedSelenium {
-
- ExtendedSelenium getExtendedSelenium() {
- if (selenium instanceof ExtendedSelenium) {
- return (ExtendedSelenium) selenium;
- } else {
- throw new UnsupportedOperationException("Assigned Selenium isn't instance of ExtendedSelenium");
- }
- }
+public interface ExtendedTypedSelenium extends TypedSelenium {
/**
* Get current style value of element given by locator.
@@ -62,9 +53,7 @@ ExtendedSelenium getExtendedSelenium() {
* @throws IllegalStateException
* if is caught unrecognized throwable
*/
- public String getStyle(ElementLocator elementLocator, String property) {
- return getExtendedSelenium().getStyle(elementLocator.getAsString(), property);
- }
+ String getStyle(ElementLocator elementLocator, String property);
/**
* Aligns screen to top (resp. bottom) of element given by locator.
@@ -74,9 +63,7 @@ public String getStyle(ElementLocator elementLocator, String property) {
* @param alignToTop
* should be top border of screen aligned to top border of element
*/
- public void scrollIntoView(ElementLocator elementLocator, boolean alignToTop) {
- getExtendedSelenium().scrollIntoView(elementLocator.getAsString(), String.valueOf(alignToTop));
- }
+ void scrollIntoView(ElementLocator elementLocator, boolean alignToTop);
/**
* Simulates a user hovering a mouse over the specified element at specific coordinates relative to element.
@@ -87,9 +74,7 @@ public void scrollIntoView(ElementLocator elementLocator, boolean alignToTop) {
* specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the
* locator.
*/
- public void mouseOverAt(ElementLocator elementLocator, Point point) {
- getExtendedSelenium().mouseOverAt(elementLocator.getAsString(), point.getCoords());
- }
+ void mouseOverAt(ElementLocator elementLocator, Point point);
/**
* Returns whether the element is displayed on the page.
@@ -98,9 +83,7 @@ public void mouseOverAt(ElementLocator elementLocator, Point point) {
* element locator
* @return if style contains "display: none;" returns false, else returns true
*/
- public boolean isDisplayed(ElementLocator elementLocator) {
- return getExtendedSelenium().isDisplayed(elementLocator.getAsString());
- }
+ boolean isDisplayed(ElementLocator elementLocator);
/**
* Checks if element given by locator is member of CSS class given by className.
@@ -111,9 +94,7 @@ public boolean isDisplayed(ElementLocator elementLocator) {
* element's locator
* @return true if element given by locator is member of CSS class given by className
*/
- public boolean belongsClass(ElementLocator elementLocator, String className) {
- return getExtendedSelenium().belongsClass(elementLocator.getAsString(), className);
- }
+ boolean belongsClass(ElementLocator elementLocator, String className);
/**
* Verifies that the specified attribute is defined for the element.
@@ -124,11 +105,7 @@ public boolean belongsClass(ElementLocator elementLocator, String className) {
* @throws SeleniumException
* when element isn't present
*/
- public boolean isAttributePresent(AttributeLocator attributeLocator) {
- final String elementLocator = attributeLocator.getAssociatedElement().getAsString();
- final String attributeName = attributeLocator.getAttribute().getAttributeName();
- return getExtendedSelenium().isAttributePresent(elementLocator, attributeName);
- }
+ boolean isAttributePresent(AttributeLocator attributeLocator);
/*
* (non-Javadoc)
@@ -136,17 +113,5 @@ public boolean isAttributePresent(AttributeLocator attributeLocator) {
* @see
* org.jboss.test.selenium.framework.DefaultTypedSelenium#getCount(org.jboss.test.selenium.locator.IterableLocator)
*/
- @Override
- public int getCount(IterableLocator<?> locator) {
- Object reference = (Object) locator;
- if (reference instanceof JQueryLocator) {
- return getExtendedSelenium().getJQueryCount(LocatorUtils.getRawLocator((JQueryLocator) reference))
- .intValue();
- }
- try {
- return super.getCount(locator);
- } catch (UnsupportedOperationException e) {
- throw new UnsupportedOperationException("Only JQuery and XPath locators are supported for counting");
- }
- }
+ int getCount(IterableLocator<?> locator);
}
\ No newline at end of file
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSeleniumImpl.java b/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSeleniumImpl.java
new file mode 100644
index 000000000..8ff07d504
--- /dev/null
+++ b/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSeleniumImpl.java
@@ -0,0 +1,125 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.selenium.framework;
+
+import org.jboss.test.selenium.geometry.Point;
+import org.jboss.test.selenium.locator.AttributeLocator;
+import org.jboss.test.selenium.locator.ElementLocator;
+import org.jboss.test.selenium.locator.IterableLocator;
+import org.jboss.test.selenium.locator.JQueryLocator;
+import org.jboss.test.selenium.locator.LocatorUtils;
+
+/**
+ * Type-safe selenium wrapper for Selenium API with extension of some useful commands defined in
+ * {@link ExtendedSelenium}
+ *
+ * @author <a href="mailto:[email protected]">Lukas Fryc</a>
+ * @version $Revision$
+ */
+public class ExtendedTypedSeleniumImpl extends TypedSeleniumImpl implements ExtendedTypedSelenium {
+
+ protected ExtendedSelenium getExtendedSelenium() {
+ if (selenium instanceof ExtendedSelenium) {
+ return (ExtendedSelenium) selenium;
+ } else {
+ throw new UnsupportedOperationException("Assigned Selenium isn't instance of ExtendedSelenium");
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.jboss.test.selenium.framework.ExtendedTypedSelenium#getStyle(org.jboss.test.selenium.locator.ElementLocator,
+ * java.lang.String)
+ */
+ public String getStyle(ElementLocator elementLocator, String property) {
+ return getExtendedSelenium().getStyle(elementLocator.getAsString(), property);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#scrollIntoView(org.jboss.test.selenium.locator.ElementLocator , boolean)
+ */
+ public void scrollIntoView(ElementLocator elementLocator, boolean alignToTop) {
+ getExtendedSelenium().scrollIntoView(elementLocator.getAsString(), String.valueOf(alignToTop));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#mouseOverAt(org.jboss.test.selenium.locator.ElementLocator ,
+ * org.jboss.test.selenium.geometry.Point)
+ */
+ public void mouseOverAt(ElementLocator elementLocator, Point point) {
+ getExtendedSelenium().mouseOverAt(elementLocator.getAsString(), point.getCoords());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#isDisplayed(org.jboss.test.selenium.locator.ElementLocator )
+ */
+ public boolean isDisplayed(ElementLocator elementLocator) {
+ return getExtendedSelenium().isDisplayed(elementLocator.getAsString());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#belongsClass(org.jboss.test.selenium.locator.ElementLocator , java.lang.String)
+ */
+ public boolean belongsClass(ElementLocator elementLocator, String className) {
+ return getExtendedSelenium().belongsClass(elementLocator.getAsString(), className);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#isAttributePresent(org.jboss.test.selenium.locator. AttributeLocator)
+ */
+ public boolean isAttributePresent(AttributeLocator attributeLocator) {
+ final String elementLocator = attributeLocator.getAssociatedElement().getAsString();
+ final String attributeName = attributeLocator.getAttribute().getAttributeName();
+ return getExtendedSelenium().isAttributePresent(elementLocator, attributeName);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see DefaultTypedSelenium#getCount(org.jboss.test.selenium.locator.IterableLocator)
+ */
+ @Override
+ public int getCount(IterableLocator<?> locator) {
+ Object reference = (Object) locator;
+ if (reference instanceof JQueryLocator) {
+ return getExtendedSelenium().getJQueryCount(LocatorUtils.getRawLocator((JQueryLocator) reference))
+ .intValue();
+ }
+ try {
+ return super.getCount(locator);
+ } catch (UnsupportedOperationException e) {
+ throw new UnsupportedOperationException("Only JQuery and XPath locators are supported for counting");
+ }
+ }
+}
\ No newline at end of file
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/TypedSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/TypedSelenium.java
index 713052bfd..8cb712266 100644
--- a/library/src/main/java/org/jboss/test/selenium/framework/TypedSelenium.java
+++ b/library/src/main/java/org/jboss/test/selenium/framework/TypedSelenium.java
@@ -21,28 +21,17 @@
*/
package org.jboss.test.selenium.framework;
-import java.awt.image.BufferedImage;
-import java.io.File;
import java.net.URL;
import java.util.List;
import org.jboss.test.selenium.dom.Event;
-import org.jboss.test.selenium.encapsulated.Cookie;
-import org.jboss.test.selenium.encapsulated.CookieParameters;
-import org.jboss.test.selenium.encapsulated.Frame;
import org.jboss.test.selenium.encapsulated.FrameLocator;
import org.jboss.test.selenium.encapsulated.JavaScript;
-import org.jboss.test.selenium.encapsulated.Kwargs;
import org.jboss.test.selenium.encapsulated.LogLevel;
-import org.jboss.test.selenium.encapsulated.NetworkTraffic;
-import org.jboss.test.selenium.encapsulated.NetworkTrafficType;
-import org.jboss.test.selenium.encapsulated.Window;
-import org.jboss.test.selenium.encapsulated.WindowId;
import org.jboss.test.selenium.encapsulated.XpathLibrary;
import org.jboss.test.selenium.geometry.Dimension;
import org.jboss.test.selenium.geometry.Offset;
import org.jboss.test.selenium.geometry.Point;
-import org.jboss.test.selenium.locator.Attribute;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.locator.IdLocator;
@@ -57,9 +46,6 @@
*/
public interface TypedSelenium {
- /** Sets the per-session extension Javascript */
- void setExtensionJs(JavaScript extensionJs);
-
/** Launches the browser with a new Selenium session */
void start();
@@ -501,101 +487,6 @@ public interface TypedSelenium {
*/
void open(URL url);
- /**
- * Opens a popup window (if a window with that ID isn't already open). After opening the window, you'll need to
- * select it using the selectWindow command.
- *
- * <p>
- * This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept
- * a call to window.open (if the call occurs during or before the "onLoad" event, for example). In those cases, you
- * can force Selenium to notice the open window's name by using the Selenium openWindow command, using an empty
- * (blank) url, like this: openWindow("", "myFunnyWindow").
- * </p>
- *
- * @param url
- * the URL to open, which can be blank
- * @param windowID
- * the JavaScript window ID of the window to select
- */
- void openWindow(URL url, WindowId windowID);
-
- /**
- * Selects a popup window using a window locator; once a popup window has been selected, all commands go to that
- * window. To select the main window again, use null as the target.
- *
- * <p>
- *
- * Window locators provide different ways of specifying the window object: by title, by internal JavaScript "name,"
- * or by JavaScript variable.
- * </p>
- * <ul>
- * <li><strong>title</strong>=<em>My Special Window</em>: Finds the window using the text that appears in the title
- * bar. Be careful; two windows can share the same title. If that happens, this locator will just pick one.</li>
- * <li><strong>name</strong>=<em>myWindow</em>: Finds the window using its internal JavaScript "name" property. This
- * is the second parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures,
- * replaceFlag) (which Selenium intercepts).</li>
- * <li><strong>var</strong>=<em>variableName</em>: Some pop-up windows are unnamed (anonymous), but are associated
- * with a JavaScript variable name in the current application window, e.g. "window.foo = window.open(url);". In
- * those cases, you can open the window using "var=foo".</li>
- * </ul>
- * <p>
- * If no window locator prefix is provided, we'll try to guess what you mean like this:
- * </p>
- * <p>
- * 1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window
- * instantiated by the browser).
- * </p>
- * <p>
- * 2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window,
- * then it is assumed that this variable contains the return value from a call to the JavaScript window.open()
- * method.
- * </p>
- * <p>
- * 3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names".
- * </p>
- * <p>
- * 4.) If <em>that</em> fails, we'll try looping over all of the known windows to try to find the appropriate
- * "title". Since "title" is not necessarily unique, this may have unexpected behavior.
- * </p>
- * <p>
- * If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log
- * messages which identify the names of windows created via window.open (and therefore intercepted by Selenium). You
- * will see messages like the following for each window as it is opened:
- * </p>
- * <p>
- * <code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is
- * "myNewWindow"</code>
- * </p>
- * <p>
- * In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before
- * the "onLoad" event, for example). (This is bug SEL-339.) In those cases, you can force Selenium to notice the
- * open window's name by using the Selenium openWindow command, using an empty (blank) url, like this:
- * openWindow("", "myFunnyWindow").
- * </p>
- *
- * @param windowID
- * the JavaScript window ID of the window to select
- */
- void selectWindow(WindowId windowID);
-
- /**
- * Simplifies the process of selecting a popup window (and does not offer functionality beyond what
- * <code>selectWindow()</code> already provides).
- * <ul>
- * <li>If <code>windowID</code> is either not specified, or specified as "null", the first non-top window is
- * selected. The top window is the one that would be selected by <code>selectWindow()</code> without providing a
- * <code>windowID</code> . This should not be used when more than one popup window is in play.</li>
- * <li>Otherwise, the window will be looked up considering <code>windowID</code> as the following in order: 1) the
- * "name" of the window, as specified to <code>window.open()</code>; 2) a javascript variable which is a reference
- * to a window; and 3) the title of the window. This is the same ordered lookup performed by
- * <code>selectWindow</code> .</li>
- * </ul>
- *
- * @param windowID
- * an identifier for the popup window, which can take on a number of different meanings
- */
- void selectPopUp(WindowId windowID);
-
/**
* Selects the main window. Functionally equivalent to using <code>selectWindow()</code> and specifying no value for
* <code>windowID</code>.
@@ -621,55 +512,6 @@ public interface TypedSelenium {
*/
void selectFrame(FrameLocator frameLocator);
- /**
- * Determine whether current/locator identify the frame containing this running code.
- *
- * <p>
- * This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the
- * selenium server needs to identify the "current" frame. In this case, when the test calls selectFrame, this
- * routine is called for each frame to figure out which one has been selected. The selected frame will return true,
- * while all others will return false.
- * </p>
- *
- * @param currentFrameString
- * starting frame
- * @param target
- * new frame (which might be relative to the current one)
- * @return true if the new frame is this code's window
- */
- boolean getWhetherThisFrameMatchFrameExpression(Frame currentFrame, Frame targetFrame);
-
- /**
- * Determine whether currentWindowString plus target identify the window containing this running code.
- *
- * <p>
- * This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the
- * selenium server needs to identify the "current" window. In this case, when the test calls selectWindow, this
- * routine is called for each window to figure out which one has been selected. The selected window will return
- * true, while all others will return false.
- * </p>
- *
- * @param currentWindowString
- * starting window
- * @param target
- * new window (which might be relative to the current one, e.g., "_parent")
- * @return true if the new window is this code's window
- */
- boolean getWhetherThisWindowMatchWindowExpression(Window currentWindowString, Window target);
-
- /**
- * Waits for a popup window to appear and load up.
- *
- * @param windowID
- * the JavaScript window "name" of the window that will appear (not the text of the title bar) If
- * unspecified, or specified as "null", this command will wait for the first non-top window to appear
- * (don't rely on this if you are working with multiple popups simultaneously).
- * @param timeout
- * a timeout in milliseconds, after which the action will return with an error. If this value is not
- * specified, the default Selenium timeout will be used. See the setTimeout() command.
- */
- void waitForPopUp(WindowId windowId, long timeoutInMilis);
-
/**
* <p>
* By default, Selenium's overridden window.confirm() function will return true, as if the user had manually clicked
@@ -874,8 +716,8 @@ public interface TypedSelenium {
*
* <p>
* Note that, by default, the snippet will run in the context of the "selenium" object itself, so <code>this</code>
- * will refer to the Selenium object. Use <code>window</code> to refer to the window of your application, e.g.
- * <code>window.document.getElementById('foo')</code>
+ * will refer to the Selenium object. Use <code>window</code> to refer to the window of your application,
+ * e.g. <code>window.document.getElementById('foo')</code>
* </p>
* <p>
* If you need to use a locator to refer to a single element in your application page, you can use
@@ -1038,48 +880,6 @@ public interface TypedSelenium {
*/
boolean isEditable(ElementLocator locator);
- /**
- * Returns the IDs of all buttons on the page.
- *
- * <p>
- * If a given button has no ID, it will appear as "" in this array.
- * </p>
- *
- * @return the IDs of all buttons on the page
- */
- List<ElementLocator> getAllButtons();
-
- /**
- * Returns the IDs of all links on the page.
- *
- * <p>
- * If a given link has no ID, it will appear as "" in this array.
- * </p>
- *
- * @return the IDs of all links on the page
- */
- List<ElementLocator> getAllLinks();
-
- /**
- * Returns the IDs of all input fields on the page.
- *
- * <p>
- * If a given field has no ID, it will appear as "" in this array.
- * </p>
- *
- * @return the IDs of all field on the page
- */
- List<ElementLocator> getAllFields();
-
- /**
- * Returns every instance of some attribute from all known windows.
- *
- * @param attributeName
- * name of an attribute on the windows
- * @return the set of values of this attribute from all known windows.
- */
- List<String> getAttributeFromAllWindows(Attribute attribute);
-
/**
* deprecated - use dragAndDrop instead
*
@@ -1145,27 +945,6 @@ public interface TypedSelenium {
*/
void windowMaximize();
- /**
- * Returns the IDs of all windows that the browser knows about.
- *
- * @return the IDs of all windows that the browser knows about.
- */
- List<WindowId> getAllWindowIds();
-
- /**
- * Returns the names of all windows that the browser knows about.
- *
- * @return the names of all windows that the browser knows about.
- */
- List<String> getAllWindowNames();
-
- /**
- * Returns the titles of all windows that the browser knows about.
- *
- * @return the titles of all windows that the browser knows about.
- */
- List<String> getAllWindowTitles();
-
/**
* Returns the entire HTML source between the opening and closing "html" tags.
*
@@ -1278,20 +1057,6 @@ public interface TypedSelenium {
*/
int getCursorPosition(ElementLocator locator);
- /**
- * Returns the specified expression.
- *
- * <p>
- * This is useful because of JavaScript preprocessing. It is used to generate commands like assertExpression and
- * waitForExpression.
- * </p>
- *
- * @param expression
- * the value to return
- * @return the value passed in
- */
- JavaScript getExpression(JavaScript expression);
-
/**
* Returns the number of elements that match the specified locator.
*
@@ -1402,65 +1167,6 @@ public interface TypedSelenium {
*/
void waitForFrameToLoad(URL frameAddress, long timeout);
- /**
- * Return all cookies of the current page under test.
- *
- * @return all cookies of the current page under test
- */
- List<Cookie> getCookie();
-
- /**
- * Returns the value of the cookie with the specified name, or throws an error if the cookie is not present.
- *
- * @param name
- * the name of the cookie
- * @return the value of the cookie
- */
- Cookie getCookieByName(Cookie name);
-
- /**
- * Returns true if a cookie with the specified name is present, or false otherwise.
- *
- * @param name
- * the name of the cookie
- * @return true if a cookie with the specified name is present, or false otherwise.
- */
- boolean isCookiePresent(Cookie name);
-
- /**
- * Create a new cookie whose path and domain are same with those of current page under test, unless you specified a
- * path for this cookie explicitly.
- *
- * @param nameValuePair
- * name and value of the cookie in a format "name=value"
- * @param optionsString
- * options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the
- * optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are
- * irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a
- * subset of the current domain will usually fail.
- */
- void createCookie(Cookie cookie, CookieParameters parameters);
-
- /**
- * Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you need to delete it using
- * the exact same path and domain that were used to create the cookie. If the path is wrong, or the domain is wrong,
- * the cookie simply won't be deleted. Also note that specifying a domain that isn't a subset of the current domain
- * will usually fail.
- *
- * Since there's no way to discover at runtime the original path and domain of a given cookie, we've added an option
- * called 'recurse' to try all sub-domains of the current domain with all paths that are a subset of the current
- * path. Beware; this option can be slow. In big-O notation, it operates in O(n*m) time, where n is the number of
- * dots in the domain name and m is the number of slashes in the path.
- *
- * @param name
- * the name of the cookie to be deleted
- * @param optionsString
- * options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The
- * optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are
- * irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail.
- */
- void deleteCookie(Cookie cookie, CookieParameters parameters);
-
/**
* Calls deleteCookie with recurse=true on all cookies visible to the current page. As noted on the documentation
* for deleteCookie, recurse=true can be much slower than simply deleting the cookies using a known domain/path.
@@ -1511,30 +1217,6 @@ public interface TypedSelenium {
*/
void addLocationStrategy(LocationStrategy strategyName, JavaScript functionDefinition);
- /**
- * Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot
- * command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the
- * monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode,
- * and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from
- * the Screengrab! Firefox extension. Please see http://www.screengrab.org and http://snapsie.sourceforge.net/ for
- * details.
- *
- * @param filename
- * the path to the file to persist the screenshot as. No filename extension will be appended by default.
- * Directories will not be created if they do not exist, and an exception will be thrown, possibly by
- * native code.
- * @param kwargs
- * a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" .
- * Currently valid options:
- * <dl>
- * <dt>background</dt>
- * <dd>the background CSS for the HTML document. This may be useful to set for capturing screenshots of
- * less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas
- * dimension to fail and a black background is exposed (possibly obscuring black text).</dd>
- * </dl>
- */
- void captureEntirePageScreenshot(File filename, Kwargs kwargs);
-
/**
* Loads script content into a new script tag in the Selenium document. This differs from the runScript command in
* that runScript adds the script tag to the document of the AUT, not the Selenium document. The following entities
@@ -1591,84 +1273,6 @@ public interface TypedSelenium {
*/
void logToBrowser(String context);
- /**
- * Sets a file input (upload) field to the file listed in fileLocator
- *
- * @param fieldLocator
- * an element locator
- * @param fileLocator
- * a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator),
- * Selenium RC may need to transfer the file to the local machine before attaching the file in a web page
- * form. This is common in selenium grid configurations where the RC server driving the browser is not
- * the same machine that started the test. Supported Browsers: Firefox ("*chrome") only.
- */
- void attachFile(ElementLocator fieldLocator, File fileLocator);
-
- /**
- * Sets a file input (upload) field to the file listed in fileLocator
- *
- * @param fieldLocator
- * an element locator
- * @param fileLocator
- * a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator),
- * Selenium RC may need to transfer the file to the local machine before attaching the file in a web page
- * form. This is common in selenium grid configurations where the RC server driving the browser is not
- * the same machine that started the test. Supported Browsers: Firefox ("*chrome") only.
- */
- void attachFile(ElementLocator fieldLocator, URL fileLocator);
-
- /**
- * Captures a PNG screenshot to the specified file.
- *
- * @param filename
- * the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"
- */
- void captureScreenshot(File filename);
-
- /**
- * Capture a PNG screenshot. It then returns the file as a base 64 encoded string.
- *
- * @return The BufferedImage
- */
- BufferedImage captureScreenshot();
-
- /**
- * Returns the network traffic seen by the browser, including headers, AJAX requests, status codes, and timings.
- * When this function is called, the traffic log is cleared, so the returned content is only the traffic seen since
- * the last call.
- *
- * @param type
- * The type of data to return the network traffic as. Valid values are: json, xml, or plain.
- * @return A string representation in the defined type of the network traffic seen by the browser.
- */
- NetworkTraffic captureNetworkTraffic(NetworkTrafficType type);
-
- /**
- * Tells the Selenium server to add the specificed key and value as a custom outgoing request header. This only
- * works if the browser is configured to use the built in Selenium proxy.
- *
- * @param key
- * the header name.
- * @param value
- * the header value.
- */
- void addCustomRequestHeader(String key, String value);
-
- /**
- * Downloads a screenshot of the browser current window canvas to a based 64 encoded PNG file. The <em>entire</em>
- * windows canvas is captured, including parts rendered outside of the current view port.
- *
- * Currently this only works in Mozilla and when running in chrome mode.
- *
- * @param kwargs
- * A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This
- * may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute
- * positioning causes the calculation of the canvas dimension to fail and a black background is exposed
- * (possibly obscuring black text).
- * @return The BufferedImage
- */
- BufferedImage captureEntirePageScreenshot(Kwargs kwargs);
-
/**
* Kills the running Selenium Server and all browser sessions. After you run this command, you will no longer be
* able to send commands to the server; you can't remotely start the server once it has been stopped. Normally you
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/DefaultTypedSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/TypedSeleniumImpl.java
similarity index 99%
rename from library/src/main/java/org/jboss/test/selenium/framework/DefaultTypedSelenium.java
rename to library/src/main/java/org/jboss/test/selenium/framework/TypedSeleniumImpl.java
index a47ac77a5..c0ca22b72 100644
--- a/library/src/main/java/org/jboss/test/selenium/framework/DefaultTypedSelenium.java
+++ b/library/src/main/java/org/jboss/test/selenium/framework/TypedSeleniumImpl.java
@@ -41,6 +41,7 @@
import org.jboss.test.selenium.encapsulated.Window;
import org.jboss.test.selenium.encapsulated.WindowId;
import org.jboss.test.selenium.encapsulated.XpathLibrary;
+import org.jboss.test.selenium.framework.internal.UnsupportedTypedSelenium;
import org.jboss.test.selenium.geometry.Dimension;
import org.jboss.test.selenium.geometry.Offset;
import org.jboss.test.selenium.geometry.Point;
@@ -64,7 +65,7 @@
* @author <a href="mailto:[email protected]">Lukas Fryc</a>
* @version $Revision$
*/
-public class DefaultTypedSelenium implements TypedSelenium {
+public class TypedSeleniumImpl implements TypedSelenium, UnsupportedTypedSelenium {
Selenium selenium;
@@ -455,7 +456,7 @@ public boolean isOrdered(ElementLocator elementLocator1, ElementLocator elementL
}
public boolean isPromptPresent() {
- return isPromptPresent();
+ return selenium.isPromptPresent();
}
public boolean isSomethingSelected(ElementLocator selectLocator) {
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/internal/UnsupportedTypedSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/internal/UnsupportedTypedSelenium.java
new file mode 100644
index 000000000..ef469fa23
--- /dev/null
+++ b/library/src/main/java/org/jboss/test/selenium/framework/internal/UnsupportedTypedSelenium.java
@@ -0,0 +1,433 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.selenium.framework.internal;
+
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.net.URL;
+import java.util.List;
+
+import org.jboss.test.selenium.encapsulated.Cookie;
+import org.jboss.test.selenium.encapsulated.CookieParameters;
+import org.jboss.test.selenium.encapsulated.Frame;
+import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.encapsulated.Kwargs;
+import org.jboss.test.selenium.encapsulated.NetworkTraffic;
+import org.jboss.test.selenium.encapsulated.NetworkTrafficType;
+import org.jboss.test.selenium.encapsulated.Window;
+import org.jboss.test.selenium.encapsulated.WindowId;
+import org.jboss.test.selenium.locator.Attribute;
+import org.jboss.test.selenium.locator.ElementLocator;
+
+/**
+ * Unsupported methods from Selenium API didn't exposed to TypedSelenium
+ *
+ * @author <a href="mailto:[email protected]">Lukas Fryc</a>
+ * @version $Revision$
+ */
+public interface UnsupportedTypedSelenium {
+ /**
+ * Tells the Selenium server to add the specificed key and value as a custom outgoing request header. This only
+ * works if the browser is configured to use the built in Selenium proxy.
+ *
+ * @param key
+ * the header name.
+ * @param value
+ * the header value.
+ */
+ void addCustomRequestHeader(String key, String value);
+
+ /**
+ * Sets a file input (upload) field to the file listed in fileLocator
+ *
+ * @param fieldLocator
+ * an element locator
+ * @param fileLocator
+ * a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator),
+ * Selenium RC may need to transfer the file to the local machine before attaching the file in a web page
+ * form. This is common in selenium grid configurations where the RC server driving the browser is not
+ * the same machine that started the test. Supported Browsers: Firefox ("*chrome") only.
+ */
+ void attachFile(ElementLocator fieldLocator, File fileLocator);
+
+ /**
+ * Sets a file input (upload) field to the file listed in fileLocator
+ *
+ * @param fieldLocator
+ * an element locator
+ * @param fileLocator
+ * a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator),
+ * Selenium RC may need to transfer the file to the local machine before attaching the file in a web page
+ * form. This is common in selenium grid configurations where the RC server driving the browser is not
+ * the same machine that started the test. Supported Browsers: Firefox ("*chrome") only.
+ */
+ @Deprecated
+ void attachFile(ElementLocator fieldLocator, URL fileLocator);
+
+ /**
+ * Captures a PNG screenshot to the specified file.
+ *
+ * @param filename
+ * the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"
+ */
+ void captureScreenshot(File filename);
+
+ /**
+ * Capture a PNG screenshot. It then returns the file as a base 64 encoded string.
+ *
+ * @return The BufferedImage
+ */
+ BufferedImage captureScreenshot();
+
+ /**
+ * Returns the network traffic seen by the browser, including headers, AJAX requests, status codes, and timings.
+ * When this function is called, the traffic log is cleared, so the returned content is only the traffic seen since
+ * the last call.
+ *
+ * @param type
+ * The type of data to return the network traffic as. Valid values are: json, xml, or plain.
+ * @return A string representation in the defined type of the network traffic seen by the browser.
+ */
+ NetworkTraffic captureNetworkTraffic(NetworkTrafficType type);
+
+ /**
+ * Downloads a screenshot of the browser current window canvas to a based 64 encoded PNG file. The <em>entire</em>
+ * windows canvas is captured, including parts rendered outside of the current view port.
+ *
+ * Currently this only works in Mozilla and when running in chrome mode.
+ *
+ * @param kwargs
+ * A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This
+ * may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute
+ * positioning causes the calculation of the canvas dimension to fail and a black background is exposed
+ * (possibly obscuring black text).
+ * @return The BufferedImage
+ */
+ BufferedImage captureEntirePageScreenshot(Kwargs kwargs);
+
+ /**
+ * Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot
+ * command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the
+ * monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode,
+ * and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from
+ * the Screengrab! Firefox extension. Please see http://www.screengrab.org and http://snapsie.sourceforge.net/ for
+ * details.
+ *
+ * @param filename
+ * the path to the file to persist the screenshot as. No filename extension will be appended by default.
+ * Directories will not be created if they do not exist, and an exception will be thrown, possibly by
+ * native code.
+ * @param kwargs
+ * a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" .
+ * Currently valid options:
+ * <dl>
+ * <dt>background</dt>
+ * <dd>the background CSS for the HTML document. This may be useful to set for capturing screenshots of
+ * less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas
+ * dimension to fail and a black background is exposed (possibly obscuring black text).</dd>
+ * </dl>
+ */
+ void captureEntirePageScreenshot(File filename, Kwargs kwargs);
+
+ /**
+ * Return all cookies of the current page under test.
+ *
+ * @return all cookies of the current page under test
+ */
+ List<Cookie> getCookie();
+
+ /**
+ * Returns the value of the cookie with the specified name, or throws an error if the cookie is not present.
+ *
+ * @param name
+ * the name of the cookie
+ * @return the value of the cookie
+ */
+ Cookie getCookieByName(Cookie name);
+
+ /**
+ * Returns true if a cookie with the specified name is present, or false otherwise.
+ *
+ * @param name
+ * the name of the cookie
+ * @return true if a cookie with the specified name is present, or false otherwise.
+ */
+ boolean isCookiePresent(Cookie name);
+
+ /**
+ * Create a new cookie whose path and domain are same with those of current page under test, unless you specified a
+ * path for this cookie explicitly.
+ *
+ * @param nameValuePair
+ * name and value of the cookie in a format "name=value"
+ * @param optionsString
+ * options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the
+ * optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are
+ * irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a
+ * subset of the current domain will usually fail.
+ */
+ void createCookie(Cookie cookie, CookieParameters parameters);
+
+ /**
+ * Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you need to delete it using
+ * the exact same path and domain that were used to create the cookie. If the path is wrong, or the domain is wrong,
+ * the cookie simply won't be deleted. Also note that specifying a domain that isn't a subset of the current domain
+ * will usually fail.
+ *
+ * Since there's no way to discover at runtime the original path and domain of a given cookie, we've added an option
+ * called 'recurse' to try all sub-domains of the current domain with all paths that are a subset of the current
+ * path. Beware; this option can be slow. In big-O notation, it operates in O(n*m) time, where n is the number of
+ * dots in the domain name and m is the number of slashes in the path.
+ *
+ * @param name
+ * the name of the cookie to be deleted
+ * @param optionsString
+ * options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The
+ * optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are
+ * irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail.
+ */
+ void deleteCookie(Cookie cookie, CookieParameters parameters);
+
+ /**
+ * Returns the IDs of all buttons on the page.
+ *
+ * <p>
+ * If a given button has no ID, it will appear as "" in this array.
+ * </p>
+ *
+ * @return the IDs of all buttons on the page
+ */
+ List<ElementLocator> getAllButtons();
+
+ /**
+ * Returns the IDs of all links on the page.
+ *
+ * <p>
+ * If a given link has no ID, it will appear as "" in this array.
+ * </p>
+ *
+ * @return the IDs of all links on the page
+ */
+ List<ElementLocator> getAllLinks();
+
+ /**
+ * Returns the IDs of all input fields on the page.
+ *
+ * <p>
+ * If a given field has no ID, it will appear as "" in this array.
+ * </p>
+ *
+ * @return the IDs of all field on the page
+ */
+ List<ElementLocator> getAllFields();
+
+ /**
+ * Returns the IDs of all windows that the browser knows about.
+ *
+ * @return the IDs of all windows that the browser knows about.
+ */
+ List<WindowId> getAllWindowIds();
+
+ /**
+ * Returns the names of all windows that the browser knows about.
+ *
+ * @return the names of all windows that the browser knows about.
+ */
+ List<String> getAllWindowNames();
+
+ /**
+ * Returns the titles of all windows that the browser knows about.
+ *
+ * @return the titles of all windows that the browser knows about.
+ */
+ List<String> getAllWindowTitles();
+
+ /**
+ * Returns every instance of some attribute from all known windows.
+ *
+ * @param attributeName
+ * name of an attribute on the windows
+ * @return the set of values of this attribute from all known windows.
+ */
+ List<String> getAttributeFromAllWindows(Attribute attribute);
+
+ /**
+ * Returns the specified expression.
+ *
+ * <p>
+ * This is useful because of JavaScript preprocessing. It is used to generate commands like assertExpression and
+ * waitForExpression.
+ * </p>
+ *
+ * @param expression
+ * the value to return
+ * @return the value passed in
+ */
+ JavaScript getExpression(JavaScript expression);
+
+ /**
+ * Determine whether current/locator identify the frame containing this running code.
+ *
+ * <p>
+ * This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the
+ * selenium server needs to identify the "current" frame. In this case, when the test calls selectFrame, this
+ * routine is called for each frame to figure out which one has been selected. The selected frame will return true,
+ * while all others will return false.
+ * </p>
+ *
+ * @param currentFrameString
+ * starting frame
+ * @param target
+ * new frame (which might be relative to the current one)
+ * @return true if the new frame is this code's window
+ */
+ boolean getWhetherThisFrameMatchFrameExpression(Frame currentFrame, Frame targetFrame);
+
+ /**
+ * Determine whether currentWindowString plus target identify the window containing this running code.
+ *
+ * <p>
+ * This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the
+ * selenium server needs to identify the "current" window. In this case, when the test calls selectWindow, this
+ * routine is called for each window to figure out which one has been selected. The selected window will return
+ * true, while all others will return false.
+ * </p>
+ *
+ * @param currentWindowString
+ * starting window
+ * @param target
+ * new window (which might be relative to the current one, e.g., "_parent")
+ * @return true if the new window is this code's window
+ */
+ boolean getWhetherThisWindowMatchWindowExpression(Window currentWindowString, Window target);
+
+ /**
+ * Opens a popup window (if a window with that ID isn't already open). After opening the window, you'll need to
+ * select it using the selectWindow command.
+ *
+ * <p>
+ * This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept
+ * a call to window.open (if the call occurs during or before the "onLoad" event, for example). In those cases, you
+ * can force Selenium to notice the open window's name by using the Selenium openWindow command, using an empty
+ * (blank) url, like this: openWindow("", "myFunnyWindow").
+ * </p>
+ *
+ * @param url
+ * the URL to open, which can be blank
+ * @param windowID
+ * the JavaScript window ID of the window to select
+ */
+ void openWindow(URL url, WindowId windowID);
+
+ /**
+ * Simplifies the process of selecting a popup window (and does not offer functionality beyond what
+ * <code>selectWindow()</code> already provides).
+ * <ul>
+ * <li>If <code>windowID</code> is either not specified, or specified as "null", the first non-top window is
+ * selected. The top window is the one that would be selected by <code>selectWindow()</code> without providing a
+ * <code>windowID</code> . This should not be used when more than one popup window is in play.</li>
+ * <li>Otherwise, the window will be looked up considering <code>windowID</code> as the following in order: 1) the
+ * "name" of the window, as specified to <code>window.open()</code>; 2) a javascript variable which is a reference
+ * to a window; and 3) the title of the window. This is the same ordered lookup performed by
+ * <code>selectWindow</code> .</li>
+ * </ul>
+ *
+ * @param windowID
+ * an identifier for the popup window, which can take on a number of different meanings
+ */
+ void selectPopUp(WindowId windowID);
+
+ /**
+ * Selects a popup window using a window locator; once a popup window has been selected, all commands go to that
+ * window. To select the main window again, use null as the target.
+ *
+ * <p>
+ *
+ * Window locators provide different ways of specifying the window object: by title, by internal JavaScript "name,"
+ * or by JavaScript variable.
+ * </p>
+ * <ul>
+ * <li><strong>title</strong>=<em>My Special Window</em>: Finds the window using the text that appears in the title
+ * bar. Be careful; two windows can share the same title. If that happens, this locator will just pick one.</li>
+ * <li><strong>name</strong>=<em>myWindow</em>: Finds the window using its internal JavaScript "name" property. This
+ * is the second parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures,
+ * replaceFlag) (which Selenium intercepts).</li>
+ * <li><strong>var</strong>=<em>variableName</em>: Some pop-up windows are unnamed (anonymous), but are associated
+ * with a JavaScript variable name in the current application window, e.g. "window.foo = window.open(url);". In
+ * those cases, you can open the window using "var=foo".</li>
+ * </ul>
+ * <p>
+ * If no window locator prefix is provided, we'll try to guess what you mean like this:
+ * </p>
+ * <p>
+ * 1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window
+ * instantiated by the browser).
+ * </p>
+ * <p>
+ * 2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window,
+ * then it is assumed that this variable contains the return value from a call to the JavaScript window.open()
+ * method.
+ * </p>
+ * <p>
+ * 3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names".
+ * </p>
+ * <p>
+ * 4.) If <em>that</em> fails, we'll try looping over all of the known windows to try to find the appropriate
+ * "title". Since "title" is not necessarily unique, this may have unexpected behavior.
+ * </p>
+ * <p>
+ * If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log
+ * messages which identify the names of windows created via window.open (and therefore intercepted by Selenium). You
+ * will see messages like the following for each window as it is opened:
+ * </p>
+ * <p>
+ * <code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is
+ * "myNewWindow"</code>
+ * </p>
+ * <p>
+ * In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before
+ * the "onLoad" event, for example). (This is bug SEL-339.) In those cases, you can force Selenium to notice the
+ * open window's name by using the Selenium openWindow command, using an empty (blank) url, like this:
+ * openWindow("", "myFunnyWindow").
+ * </p>
+ *
+ * @param windowID
+ * the JavaScript window ID of the window to select
+ */
+ void selectWindow(WindowId windowID);
+
+ /** Sets the per-session extension Javascript */
+ void setExtensionJs(JavaScript extensionJs);
+
+ /**
+ * Waits for a popup window to appear and load up.
+ *
+ * @param windowID
+ * the JavaScript window "name" of the window that will appear (not the text of the title bar) If
+ * unspecified, or specified as "null", this command will wait for the first non-top window to appear
+ * (don't rely on this if you are working with multiple popups simultaneously).
+ * @param timeout
+ * a timeout in milliseconds, after which the action will return with an error. If this value is not
+ * specified, the default Selenium timeout will be used. See the setTimeout() command.
+ */
+ void waitForPopUp(WindowId windowId, long timeoutInMilis);
+}
diff --git a/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuard.java b/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuard.java
index 7d5ab7e92..b693f6d85 100644
--- a/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuard.java
+++ b/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuard.java
@@ -22,6 +22,8 @@
package org.jboss.test.selenium.guard.request;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.interception.CommandContext;
import org.jboss.test.selenium.interception.CommandInterceptionException;
import org.jboss.test.selenium.interception.CommandInterceptor;
@@ -30,7 +32,6 @@
import com.thoughtworks.selenium.SeleniumException;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.guard.GuardedCommands.INTERACTIVE_COMMANDS;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
@@ -47,7 +48,12 @@ public class RequestTypeGuard implements CommandInterceptor {
private final JavaScript waitRequestChange =
js("((getRFS() === undefined) ? 'HTTP' : getRFS().getRequestDone()) != 'NONE' && "
+ "selenium.browserbot.getCurrentWindow().document.body");
-
+
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/**
* The request what is expected to be done
*/
@@ -84,8 +90,8 @@ public void intercept(CommandContext ctx) throws CommandInterceptionException {
* request type to NONE state.
*/
public void doBeforeCommand() {
- getCurrentSelenium().getPageExtensions().install();
- getCurrentSelenium().getEval(clearRequestDone);
+ selenium.getPageExtensions().install();
+ selenium.getEval(clearRequestDone);
}
/**
@@ -103,7 +109,7 @@ public void doBeforeCommand() {
public void doAfterCommand() {
try {
// FIXME replace with Wait implementation
- getCurrentSelenium().waitForCondition(waitRequestChange, Wait.DEFAULT_TIMEOUT);
+ selenium.waitForCondition(waitRequestChange, Wait.DEFAULT_TIMEOUT);
} catch (SeleniumException e) {
// ignore the timeout exception
}
@@ -122,7 +128,7 @@ public void doAfterCommand() {
* when the unknown type was obtained
*/
private RequestType getRequestDone() {
- String requestDone = getCurrentSelenium().getEval(getRequestDone);
+ String requestDone = selenium.getEval(getRequestDone);
try {
return RequestType.valueOf(requestDone);
} catch (IllegalArgumentException e) {
diff --git a/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuardFactory.java b/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuardFactory.java
index dc571684d..3da734f95 100644
--- a/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuardFactory.java
+++ b/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuardFactory.java
@@ -35,7 +35,12 @@ private RequestTypeGuardFactory() {
}
private static AjaxSelenium guard(AjaxSelenium selenium, RequestType requestExpected) {
- AjaxSelenium copy = selenium.immutableCopy();
+ AjaxSelenium copy;
+ try {
+ copy = selenium.clone();
+ } catch (CloneNotSupportedException e) {
+ throw new IllegalStateException(e);
+ }
copy.getInterceptionProxy().unregisterInterceptorType(RequestTypeGuard.class);
copy.getInterceptionProxy().registerInterceptor(new RequestTypeGuard(requestExpected));
return copy;
diff --git a/library/src/main/java/org/jboss/test/selenium/listener/SeleniumLoggingTestListener.java b/library/src/main/java/org/jboss/test/selenium/listener/SeleniumLoggingTestListener.java
index 4e9ea5c03..511f3526b 100644
--- a/library/src/main/java/org/jboss/test/selenium/listener/SeleniumLoggingTestListener.java
+++ b/library/src/main/java/org/jboss/test/selenium/listener/SeleniumLoggingTestListener.java
@@ -23,12 +23,13 @@
import static org.jboss.test.selenium.utils.testng.TestInfo.STATUSES;
import static org.jboss.test.selenium.utils.testng.TestInfo.getMethodName;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
import org.apache.commons.lang.StringUtils;
import org.jboss.test.selenium.encapsulated.FrameLocator;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
@@ -44,6 +45,11 @@
*/
public class SeleniumLoggingTestListener extends TestListenerAdapter {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
@Override
public void onTestStart(ITestResult result) {
logStatus(result);
@@ -84,11 +90,11 @@ private void logStatus(ITestResult result) {
String message = String.format("%s %s: %s %s", hashes, status.toUpperCase(), methodName, hashes);
String line = StringUtils.repeat("#", message.length());
- if (getCurrentSelenium() != null) {
+ if (selenium != null) {
JavaScript eval = js(String.format("/*\n%s\n%s\n%s\n*/", line, message, line));
try {
- getCurrentSelenium().selectFrame(new FrameLocator("relative=top"));
- getCurrentSelenium().getEval(eval);
+ selenium.selectFrame(new FrameLocator("relative=top"));
+ selenium.getEval(eval);
} catch (Exception e) {
e.printStackTrace();
}
diff --git a/library/src/main/java/org/jboss/test/selenium/locator/iteration/AbstractElementList.java b/library/src/main/java/org/jboss/test/selenium/locator/iteration/AbstractElementList.java
index 8cb8a6dcb..3d4483fb7 100644
--- a/library/src/main/java/org/jboss/test/selenium/locator/iteration/AbstractElementList.java
+++ b/library/src/main/java/org/jboss/test/selenium/locator/iteration/AbstractElementList.java
@@ -21,10 +21,11 @@
*/
package org.jboss.test.selenium.locator.iteration;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import java.util.Iterator;
import java.util.NoSuchElementException;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.IterableLocator;
/**
@@ -45,6 +46,11 @@
*/
public abstract class AbstractElementList<T extends IterableLocator<T>> implements Iterable<T> {
+ /**
+ * Proxy to local selenium instance
+ */
+ protected AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The iterable locator. */
T iterableLocator;
@@ -97,7 +103,7 @@ public ElementIterator() {
* Recounts the actual count of elements by given elementLocator.
*/
private void recount() {
- count = getCurrentSelenium().getCount(iterableLocator);
+ count = selenium.getCount(iterableLocator);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/ajax/AjaxWaiting.java b/library/src/main/java/org/jboss/test/selenium/waiting/ajax/AjaxWaiting.java
index e82ade5d0..e997cafa9 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/ajax/AjaxWaiting.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/ajax/AjaxWaiting.java
@@ -1,10 +1,11 @@
package org.jboss.test.selenium.waiting.ajax;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.waiting.DefaultWaiting;
/**
@@ -22,6 +23,11 @@
*/
public class AjaxWaiting extends DefaultWaiting<AjaxWaiting> {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/**
* Stars loop waiting to satisfy condition.
*
@@ -29,7 +35,7 @@ public class AjaxWaiting extends DefaultWaiting<AjaxWaiting> {
* what wait for to be satisfied
*/
public void until(JavaScriptCondition condition) {
- getCurrentSelenium().waitForCondition(condition.getJavaScriptCondition(), this.getTimeout());
+ selenium.waitForCondition(condition.getJavaScriptCondition(), this.getTimeout());
}
/**
@@ -44,7 +50,7 @@ public void until(JavaScriptCondition condition) {
*/
public <T> void waitForChange(T oldValue, JavaScriptRetriever<T> retrieve) {
JavaScript waitCondition = js(format("{0} != '{1}'", retrieve.getJavaScriptRetrieve().getAsString(), oldValue));
- getCurrentSelenium().waitForCondition(waitCondition, this.getTimeout());
+ selenium.waitForCondition(waitCondition, this.getTimeout());
}
/**
@@ -63,7 +69,7 @@ public <T> T waitForChangeAndReturn(T oldValue, JavaScriptRetriever<T> retrieve)
JavaScript waitingRetriever =
js(format("selenium.waitForCondition({0} != '{1}'); {0}", retrieve.getJavaScriptRetrieve().getAsString(),
oldValueString));
- String retrieved = getCurrentSelenium().getEval(waitingRetriever);
+ String retrieved = selenium.getEval(waitingRetriever);
return retrieve.getConvertor().backwardConversion(retrieved);
}
}
\ No newline at end of file
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributeEquals.java b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributeEquals.java
index 883f8c537..054f13934 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributeEquals.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributeEquals.java
@@ -23,13 +23,14 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptCondition;
import org.jboss.test.selenium.waiting.selenium.SeleniumCondition;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.apache.commons.lang.StringEscapeUtils.escapeJavaScript;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -48,11 +49,16 @@
*/
public class AttributeEquals implements SeleniumCondition, JavaScriptCondition {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- AttributeLocator attributeLocator;
+ private AttributeLocator attributeLocator;
/** The value. */
- String value;
+ private String value;
/**
* Instantiates a new AttributeEquals
@@ -69,7 +75,7 @@ public boolean isTrue() {
Validate.notNull(attributeLocator);
Validate.notNull(value);
- return getCurrentSelenium().getAttribute(attributeLocator).equals(value);
+ return selenium.getAttribute(attributeLocator).equals(value);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributePresent.java b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributePresent.java
index fa1eb4485..18dd4d792 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributePresent.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributePresent.java
@@ -23,13 +23,14 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptCondition;
import org.jboss.test.selenium.waiting.selenium.SeleniumCondition;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.apache.commons.lang.StringEscapeUtils.escapeJavaScript;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -46,8 +47,13 @@
*/
public class AttributePresent implements SeleniumCondition, JavaScriptCondition {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- AttributeLocator attributeLocator;
+ private AttributeLocator attributeLocator;
/**
* Instantiates a new element present.
@@ -63,7 +69,7 @@ protected AttributePresent() {
public boolean isTrue() {
Validate.notNull(attributeLocator);
- return getCurrentSelenium().isAttributePresent(attributeLocator);
+ return selenium.isAttributePresent(attributeLocator);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/ElementPresent.java b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/ElementPresent.java
index 636899f91..2a6a631e0 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/ElementPresent.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/ElementPresent.java
@@ -23,13 +23,14 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptCondition;
import org.jboss.test.selenium.waiting.selenium.SeleniumCondition;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.apache.commons.lang.StringEscapeUtils.escapeJavaScript;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -46,8 +47,13 @@
*/
public class ElementPresent implements SeleniumCondition, JavaScriptCondition {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- ElementLocator elementLocator;
+ private ElementLocator elementLocator;
/**
* Instantiates a new element present.
@@ -63,7 +69,7 @@ protected ElementPresent() {
public boolean isTrue() {
Validate.notNull(elementLocator);
- return getCurrentSelenium().isElementPresent(elementLocator);
+ return selenium.isElementPresent(elementLocator);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/TextEquals.java b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/TextEquals.java
index aa227bb10..c5745cb06 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/TextEquals.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/TextEquals.java
@@ -23,13 +23,14 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptCondition;
import org.jboss.test.selenium.waiting.selenium.SeleniumCondition;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.apache.commons.lang.StringEscapeUtils.escapeJavaScript;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -47,11 +48,16 @@
*/
public class TextEquals implements SeleniumCondition, JavaScriptCondition {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- ElementLocator elementLocator;
+ private ElementLocator elementLocator;
/** The text. */
- String text;
+ private String text;
/**
* Instantiates a new text equals.
@@ -68,7 +74,7 @@ public boolean isTrue() {
Validate.notNull(elementLocator);
Validate.notNull(text);
- return getCurrentSelenium().getText(elementLocator).equals(text);
+ return selenium.getText(elementLocator).equals(text);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/AttributeRetriever.java b/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/AttributeRetriever.java
index 57267175c..d2cc9e5e9 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/AttributeRetriever.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/AttributeRetriever.java
@@ -23,6 +23,8 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptRetriever;
import org.jboss.test.selenium.waiting.conversion.Convertor;
@@ -30,7 +32,6 @@
import org.jboss.test.selenium.waiting.selenium.SeleniumRetriever;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -41,8 +42,13 @@
*/
public class AttributeRetriever implements SeleniumRetriever<String>, JavaScriptRetriever<String> {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The attribute locator. */
- AttributeLocator attributeLocator;
+ private AttributeLocator attributeLocator;
/**
* Instantiates a new attribute retriever.
@@ -56,7 +62,7 @@ protected AttributeRetriever() {
public String retrieve() {
Validate.notNull(attributeLocator);
- return getCurrentSelenium().getAttribute(attributeLocator);
+ return selenium.getAttribute(attributeLocator);
}
/**
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/TextRetriever.java b/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/TextRetriever.java
index 523649b9e..402eff955 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/TextRetriever.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/TextRetriever.java
@@ -23,6 +23,8 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptRetriever;
import org.jboss.test.selenium.waiting.conversion.Convertor;
@@ -30,7 +32,6 @@
import org.jboss.test.selenium.waiting.selenium.SeleniumRetriever;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -41,8 +42,13 @@
*/
public class TextRetriever implements SeleniumRetriever<String>, JavaScriptRetriever<String> {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- ElementLocator elementLocator;
+ private ElementLocator elementLocator;
/**
* Instantiates a new text retriever.
@@ -56,7 +62,7 @@ protected TextRetriever() {
public String retrieve() {
Validate.notNull(elementLocator);
- return getCurrentSelenium().getText(elementLocator);
+ return selenium.getText(elementLocator);
}
/**
|
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;
}
/**
|
710ae3a9d2fbcb6767872656d82b2edaeb6e0656
|
spring-framework
|
SpringJUnit4ClassRunnerAppCtxTests now verifies- seamless support for using @Inject in addition to @Autowired
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.test/.classpath b/org.springframework.test/.classpath
index d35f01db07af..5e5a2e70be5f 100644
--- a/org.springframework.test/.classpath
+++ b/org.springframework.test/.classpath
@@ -15,6 +15,7 @@
<classpathentry combineaccessrules="false" kind="src" path="/org.springframework.web.portlet"/>
<classpathentry combineaccessrules="false" kind="src" path="/org.springframework.web.servlet"/>
<classpathentry kind="var" path="IVY_CACHE/javax.activation/com.springsource.javax.activation/1.1.0/com.springsource.javax.activation-1.1.0.jar" sourcepath="/IVY_CACHE/javax.activation/com.springsource.javax.activation/1.1.0/com.springsource.javax.activation-sources-1.1.0.jar"/>
+ <classpathentry kind="var" path="IVY_CACHE/javax.inject/com.springsource.javax.inject/0.9.0.PFD/com.springsource.javax.inject-0.9.0.PFD.jar" sourcepath="/IVY_CACHE/javax.inject/com.springsource.javax.inject/0.9.0.PFD/com.springsource.javax.inject-sources-0.9.0.PFD.jar"/>
<classpathentry kind="var" path="IVY_CACHE/javax.persistence/com.springsource.javax.persistence/1.0.0/com.springsource.javax.persistence-1.0.0.jar" sourcepath="/IVY_CACHE/javax.persistence/com.springsource.javax.persistence/1.0.0/com.springsource.javax.persistence-sources-1.0.0.jar"/>
<classpathentry kind="var" path="IVY_CACHE/javax.portlet/com.springsource.javax.portlet/2.0.0/com.springsource.javax.portlet-2.0.0.jar"/>
<classpathentry kind="var" path="IVY_CACHE/javax.servlet/com.springsource.javax.servlet/2.5.0/com.springsource.javax.servlet-2.5.0.jar" sourcepath="/IVY_CACHE/javax.servlet/com.springsource.javax.servlet/2.5.0/com.springsource.javax.servlet-sources-2.5.0.jar"/>
diff --git a/org.springframework.test/ivy.xml b/org.springframework.test/ivy.xml
index e64c205bb575..b70e01038eed 100644
--- a/org.springframework.test/ivy.xml
+++ b/org.springframework.test/ivy.xml
@@ -21,6 +21,7 @@
<dependencies>
<dependency org="javax.activation" name="com.springsource.javax.activation" rev="1.1.0" conf="provided->compile"/>
<dependency org="javax.el" name="com.springsource.javax.el" rev="1.0.0" conf="provided->compile"/>
+ <dependency org="javax.inject" name="com.springsource.javax.inject" rev="0.9.0.PFD" conf="test->compile"/>
<dependency org="javax.persistence" name="com.springsource.javax.persistence" rev="1.0.0" conf="provided->compile"/>
<dependency org="javax.portlet" name="com.springsource.javax.portlet" rev="2.0.0" conf="provided->compile"/>
<dependency org="javax.servlet" name="com.springsource.javax.servlet" rev="2.5.0" conf="provided->compile"/>
diff --git a/org.springframework.test/pom.xml b/org.springframework.test/pom.xml
index 3518579246f8..332939c8b645 100644
--- a/org.springframework.test/pom.xml
+++ b/org.springframework.test/pom.xml
@@ -25,6 +25,12 @@
<version>1.0</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>javax.inject</groupId>
+ <artifactId>com.springsource.javax.inject</artifactId>
+ <version>0.9.0.PFD</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
diff --git a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java
index 91b51242bdfc..e23164bcf1f2 100644
--- a/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java
+++ b/org.springframework.test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java
@@ -19,9 +19,11 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import javax.annotation.Resource;
+import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,6 +50,7 @@
* <ul>
* <li>{@link ContextConfiguration @ContextConfiguration}</li>
* <li>{@link Autowired @Autowired}</li>
+ * <li>{@link Inject @Inject}</li>
* <li>{@link Qualifier @Qualifier}</li>
* <li>{@link Resource @Resource}</li>
* <li>{@link ApplicationContextAware}</li>
@@ -59,10 +62,12 @@
* {@link ContextConfiguration#locations() locations} are explicitly declared
* and since the {@link ContextConfiguration#loader() ContextLoader} is left set
* to the default value of {@link GenericXmlContextLoader}, this test class's
- * dependencies will be injected via {@link Autowired @Autowired} and
- * {@link Resource @Resource} from beans defined in the
- * {@link ApplicationContext} loaded from the default classpath resource:
- * <code>"/org/springframework/test/context/junit/SpringJUnit4ClassRunnerAppCtxTests-context.xml"</code>.
+ * dependencies will be injected via {@link Autowired @Autowired},
+ * {@link Inject @Inject}, and {@link Resource @Resource} from beans defined in
+ * the {@link ApplicationContext} loaded from the default classpath resource:
+ *
+ * <code>"/org/springframework/test/context/junit/SpringJUnit4ClassRunnerAppCtxTests-context.xml"</code>
+ * .
* </p>
*
* @author Sam Brannen
@@ -93,12 +98,15 @@ public class SpringJUnit4ClassRunnerAppCtxTests implements ApplicationContextAwa
private Employee employee;
@Autowired
- private Pet pet;
+ private Pet autowiredPet;
+
+ @Inject
+ private Pet injectedPet;
@Autowired(required = false)
protected Long nonrequiredLong;
- @Resource()
+ @Resource
protected String foo;
protected String bar;
@@ -153,11 +161,14 @@ public final void verifyBeanNameSet() {
}
@Test
- public final void verifyAnnotationAutowiredFields() {
+ public final void verifyAnnotationAutowiredAndInjectedFields() {
assertNull("The nonrequiredLong field should NOT have been autowired.", this.nonrequiredLong);
assertEquals("The quux field should have been autowired via @Autowired and @Qualifier.", "Quux", this.quux);
- assertNotNull("The pet field should have been autowired.", this.pet);
- assertEquals("Fido", this.pet.getName());
+ assertNotNull("The pet field should have been autowired.", this.autowiredPet);
+ assertNotNull("The pet field should have been injected.", this.injectedPet);
+ assertEquals("Fido", this.autowiredPet.getName());
+ assertEquals("Fido", this.injectedPet.getName());
+ assertSame("@Autowired and @Inject pet should be the same object.", this.autowiredPet, this.injectedPet);
}
@Test
@@ -176,4 +187,4 @@ public final void verifyResourceAnnotationWiredMethods() {
assertEquals("The bar method should have been wired via @Resource.", "Bar", this.bar);
}
-}
+}
\ No newline at end of file
diff --git a/org.springframework.test/test.iml b/org.springframework.test/test.iml
index a5a65c18b9ae..924d7b776d9d 100644
--- a/org.springframework.test/test.iml
+++ b/org.springframework.test/test.iml
@@ -24,6 +24,7 @@
<orderEntry type="library" name="Commons Logging" level="project" />
<orderEntry type="library" name="EasyMock" level="project" />
<orderEntry type="library" name="javax.el" level="project" />
+ <orderEntry type="library" name="javax.inject" level="project" />
<orderEntry type="library" name="JUnit" level="project" />
<orderEntry type="module-library">
<library>
|
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
|
541aae12ef82767479bcd53afb3681b46dd890a5
|
spring-framework
|
SPR-5802 - NullPointerException when using- @CookieValue annotation--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
index f6b7c4204360..e8fa23d6ac5f 100644
--- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
+++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
@@ -600,9 +600,12 @@ protected Object resolveCookieValue(String cookieName, Class paramType, NativeWe
if (Cookie.class.isAssignableFrom(paramType)) {
return cookieValue;
}
- else {
+ else if (cookieValue != null) {
return cookieValue.getValue();
}
+ else {
+ return null;
+ }
}
@Override
|
b9e1d6c698b589368f4a155134e8b2ba00608dc8
|
hbase
|
HBASE-3653 : Parallelize Server Requests on HBase- Client--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1082648 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 21c60235fb3a..70366e5a2e90 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -77,6 +77,7 @@ Release 0.91.0 - Unreleased
Export (Subbu M Iyer via Stack)
HBASE-3440 Clean out load_table.rb and make sure all roads lead to
completebulkload tool (Vidhyashankar Venkataraman via Stack)
+ HBASE-3653 Parallelize Server Requests on HBase Client
TASK
HBASE-3559 Move report of split to master OFF the heartbeat channel
diff --git a/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java b/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
index 3d2c5ea8b89d..644de1fa6bd3 100644
--- a/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
+++ b/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
@@ -240,6 +240,7 @@ static class HConnectionImplementation implements HConnection {
private final Map<String, HRegionInterface> servers =
new ConcurrentHashMap<String, HRegionInterface>();
+ private final ConcurrentHashMap<String, String> connectionLock = new ConcurrentHashMap<String, String>();
/**
* Map of table to table {@link HRegionLocation}s. The table key is made
@@ -941,21 +942,30 @@ public HRegionInterface getHRegionConnection(
getMaster();
}
HRegionInterface server;
- synchronized (this.servers) {
- // See if we already have a connection
- server = this.servers.get(regionServer.toString());
- if (server == null) { // Get a connection
- try {
- server = (HRegionInterface)HBaseRPC.waitForProxy(
- serverInterfaceClass, HRegionInterface.VERSION,
- regionServer.getInetSocketAddress(), this.conf,
- this.maxRPCAttempts, this.rpcTimeout, this.rpcTimeout);
- } catch (RemoteException e) {
- LOG.warn("RemoteException connecting to RS", e);
- // Throw what the RemoteException was carrying.
- throw RemoteExceptionHandler.decodeRemoteException(e);
+ String rsName = regionServer.toString();
+ // See if we already have a connection (common case)
+ server = this.servers.get(rsName);
+ if (server == null) {
+ // create a unique lock for this RS (if necessary)
+ this.connectionLock.putIfAbsent(rsName, rsName);
+ // get the RS lock
+ synchronized (this.connectionLock.get(rsName)) {
+ // do one more lookup in case we were stalled above
+ server = this.servers.get(rsName);
+ if (server == null) {
+ try {
+ // definitely a cache miss. establish an RPC for this RS
+ server = (HRegionInterface) HBaseRPC.waitForProxy(
+ serverInterfaceClass, HRegionInterface.VERSION,
+ regionServer.getInetSocketAddress(), this.conf,
+ this.maxRPCAttempts, this.rpcTimeout, this.rpcTimeout);
+ this.servers.put(rsName, server);
+ } catch (RemoteException e) {
+ LOG.warn("RemoteException connecting to RS", e);
+ // Throw what the RemoteException was carrying.
+ throw RemoteExceptionHandler.decodeRemoteException(e);
+ }
}
- this.servers.put(regionServer.toString(), server);
}
}
return server;
|
3fbdf05921125b2bff7e4b914e9e060814010a6f
|
kotlin
|
Added some new test for java8--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/java8-tests/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithJava8CodegenTestGenerated.java b/compiler/java8-tests/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithJava8CodegenTestGenerated.java
index 6bae70acab423..4e17e4b4d7a76 100644
--- a/compiler/java8-tests/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithJava8CodegenTestGenerated.java
+++ b/compiler/java8-tests/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithJava8CodegenTestGenerated.java
@@ -35,9 +35,15 @@ public void testAllFilesPresentInBoxWithJava() throws Exception {
JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/java8/boxWithJava"), Pattern.compile("^([^\\.]+)$"), true);
}
- @TestMetadata("defaultMethodCall")
- public void testDefaultMethodCall() throws Exception {
- String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/java8/boxWithJava/defaultMethodCall/");
+ @TestMetadata("defaultMethodCallFromTrait")
+ public void testDefaultMethodCallFromTrait() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/java8/boxWithJava/defaultMethodCallFromTrait/");
+ doTestWithJava(fileName);
+ }
+
+ @TestMetadata("defaultMethodCallViaClass")
+ public void testDefaultMethodCallViaClass() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/java8/boxWithJava/defaultMethodCallViaClass/");
doTestWithJava(fileName);
}
@@ -47,12 +53,24 @@ public void testDefaultMethodCallViaTrait() throws Exception {
doTestWithJava(fileName);
}
+ @TestMetadata("defaultMethodOverride")
+ public void testDefaultMethodOverride() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/java8/boxWithJava/defaultMethodOverride/");
+ doTestWithJava(fileName);
+ }
+
@TestMetadata("dontDelegateToDefaultMethods")
public void testDontDelegateToDefaultMethods() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/java8/boxWithJava/dontDelegateToDefaultMethods/");
doTestWithJava(fileName);
}
+ @TestMetadata("inheritKotlin")
+ public void testInheritKotlin() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/java8/boxWithJava/inheritKotlin/");
+ doTestWithJava(fileName);
+ }
+
@TestMetadata("samOnInterfaceWithDefaultMethod")
public void testSamOnInterfaceWithDefaultMethod() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/java8/boxWithJava/samOnInterfaceWithDefaultMethod/");
diff --git a/compiler/testData/codegen/java8/boxWithJava/defaultMethodCall/Simple.java b/compiler/testData/codegen/java8/boxWithJava/defaultMethodCallFromTrait/Simple.java
similarity index 100%
rename from compiler/testData/codegen/java8/boxWithJava/defaultMethodCall/Simple.java
rename to compiler/testData/codegen/java8/boxWithJava/defaultMethodCallFromTrait/Simple.java
diff --git a/compiler/testData/codegen/java8/boxWithJava/defaultMethodCallFromTrait/defaultCall.kt b/compiler/testData/codegen/java8/boxWithJava/defaultMethodCallFromTrait/defaultCall.kt
new file mode 100644
index 0000000000000..55133e938783c
--- /dev/null
+++ b/compiler/testData/codegen/java8/boxWithJava/defaultMethodCallFromTrait/defaultCall.kt
@@ -0,0 +1,14 @@
+trait KTrait : Simple {
+ fun bar(): String {
+ return test("O") + Simple.testStatic("O")
+ }
+}
+
+class Test : KTrait {}
+
+fun box(): String {
+ val test = Test().bar()
+ if (test != "OKOK") return "fail $test"
+
+ return "OK"
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/java8/boxWithJava/defaultMethodCallViaClass/Simple.java b/compiler/testData/codegen/java8/boxWithJava/defaultMethodCallViaClass/Simple.java
new file mode 100644
index 0000000000000..9e37ab676594c
--- /dev/null
+++ b/compiler/testData/codegen/java8/boxWithJava/defaultMethodCallViaClass/Simple.java
@@ -0,0 +1,9 @@
+interface Simple {
+ default String test(String s) {
+ return s + "K";
+ }
+
+ static String testStatic(String s) {
+ return s + "K";
+ }
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/java8/boxWithJava/defaultMethodCall/Simple.kt b/compiler/testData/codegen/java8/boxWithJava/defaultMethodCallViaClass/defaultCall.kt
similarity index 100%
rename from compiler/testData/codegen/java8/boxWithJava/defaultMethodCall/Simple.kt
rename to compiler/testData/codegen/java8/boxWithJava/defaultMethodCallViaClass/defaultCall.kt
diff --git a/compiler/testData/codegen/java8/boxWithJava/defaultMethodOverride/Simple.java b/compiler/testData/codegen/java8/boxWithJava/defaultMethodOverride/Simple.java
new file mode 100644
index 0000000000000..552a157fcb70b
--- /dev/null
+++ b/compiler/testData/codegen/java8/boxWithJava/defaultMethodOverride/Simple.java
@@ -0,0 +1,5 @@
+interface Simple {
+ default String test(String s) {
+ return s + "Fail";
+ }
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/java8/boxWithJava/defaultMethodOverride/override.kt b/compiler/testData/codegen/java8/boxWithJava/defaultMethodOverride/override.kt
new file mode 100644
index 0000000000000..d834a1f60cb93
--- /dev/null
+++ b/compiler/testData/codegen/java8/boxWithJava/defaultMethodOverride/override.kt
@@ -0,0 +1,13 @@
+trait KTrait: Simple {
+ override fun test(s: String): String {
+ return s + "K"
+ }
+}
+
+class Test : KTrait {
+
+}
+
+fun box(): String {
+ return Test().test("O")
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/java8/boxWithJava/dontDelegateToDefaultMethods/delegation.kt b/compiler/testData/codegen/java8/boxWithJava/dontDelegateToDefaultMethods/dontDelegate.kt
similarity index 100%
rename from compiler/testData/codegen/java8/boxWithJava/dontDelegateToDefaultMethods/delegation.kt
rename to compiler/testData/codegen/java8/boxWithJava/dontDelegateToDefaultMethods/dontDelegate.kt
diff --git a/compiler/testData/codegen/java8/boxWithJava/inheritKotlin/Simple.java b/compiler/testData/codegen/java8/boxWithJava/inheritKotlin/Simple.java
new file mode 100644
index 0000000000000..02c979c1af19a
--- /dev/null
+++ b/compiler/testData/codegen/java8/boxWithJava/inheritKotlin/Simple.java
@@ -0,0 +1,5 @@
+interface Simple extends KTrait {
+ default String test() {
+ return "simple";
+ }
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/java8/boxWithJava/inheritKotlin/defaultCall.kt b/compiler/testData/codegen/java8/boxWithJava/inheritKotlin/defaultCall.kt
new file mode 100644
index 0000000000000..c9572f45f3731
--- /dev/null
+++ b/compiler/testData/codegen/java8/boxWithJava/inheritKotlin/defaultCall.kt
@@ -0,0 +1,23 @@
+trait KTrait {
+ fun test(): String {
+ return "base";
+ }
+}
+
+class Test : Simple {
+
+ fun bar(): String {
+ return super.test()
+ }
+
+}
+
+fun box(): String {
+ val test = Test().test()
+ if (test != "simple") return "fail $test"
+
+ val bar = Test().bar()
+ if (bar != "simple") return "fail 2 $bar"
+
+ return "OK"
+}
\ No newline at end of file
|
0a545cb738de474fb6dd20bdd8e28e939ab62dae
|
camel
|
CAMEL-2919: Debugger API--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@961615 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/impl/BreakpointSupport.java b/camel-core/src/main/java/org/apache/camel/impl/BreakpointSupport.java
index c87280b7bfe64..dace795250a2e 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/BreakpointSupport.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/BreakpointSupport.java
@@ -16,13 +16,17 @@
*/
package org.apache.camel.impl;
+import java.util.EventObject;
+
import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.spi.Breakpoint;
/**
* A support class for {@link Breakpoint} implementations to use as base class.
* <p/>
- * Will be in active state and match any {@link Exchange}s.
+ * Will be in active state.
*
* @version $Revision$
*/
@@ -42,4 +46,15 @@ public void activate() {
state = State.Active;
}
+ public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
+ // noop
+ }
+
+ public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
+ // noop
+ }
+
+ public void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition) {
+ // noop
+ }
}
diff --git a/camel-core/src/main/java/org/apache/camel/impl/ConditionSupport.java b/camel-core/src/main/java/org/apache/camel/impl/ConditionSupport.java
new file mode 100644
index 0000000000000..538f122c1bd38
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/impl/ConditionSupport.java
@@ -0,0 +1,40 @@
+/**
+ * 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 java.util.EventObject;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.model.ProcessorDefinition;
+import org.apache.camel.spi.Condition;
+
+/**
+ * A support class for {@link org.apache.camel.spi.Condition} implementations to use as base class.
+ *
+ * @version $Revision$
+ */
+public class ConditionSupport implements Condition {
+
+ public boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
+ return false;
+ }
+
+ public boolean matchEvent(Exchange exchange, EventObject event) {
+ return false;
+ }
+}
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 42662acaf56f8..086d43f34524e 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
@@ -1023,8 +1023,12 @@ private void doStartCamel() throws Exception {
}
}
+ // register debugger
if (getDebugger() != null) {
LOG.info("Debugger: " + getDebugger() + " is enabled on CamelContext: " + getName());
+ // register this camel context on the debugger
+ getDebugger().setCamelContext(this);
+ startServices(getDebugger());
addInterceptStrategy(new Debug(getDebugger()));
}
@@ -1073,6 +1077,7 @@ private void doStartCamel() throws Exception {
routeDefinitionInitiated = true;
}
+
// starting will continue in the start method
}
diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultDebugger.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultDebugger.java
index 38dec875a0c87..acf6f481f7d88 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/DefaultDebugger.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultDebugger.java
@@ -19,14 +19,23 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.EventObject;
import java.util.List;
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
import org.apache.camel.Exchange;
+import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
+import org.apache.camel.RouteNode;
+import org.apache.camel.management.EventNotifierSupport;
+import org.apache.camel.management.event.AbstractExchangeEvent;
import org.apache.camel.model.ProcessorDefinition;
+import org.apache.camel.processor.interceptor.Tracer;
import org.apache.camel.spi.Breakpoint;
import org.apache.camel.spi.Condition;
import org.apache.camel.spi.Debugger;
+import org.apache.camel.util.ObjectHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -35,10 +44,11 @@
*
* @version $Revision$
*/
-public class DefaultDebugger implements Debugger {
+public class DefaultDebugger implements Debugger, CamelContextAware {
private static final Log LOG = LogFactory.getLog(DefaultDebugger.class);
private final List<BreakpointConditions> breakpoints = new ArrayList<BreakpointConditions>();
+ private CamelContext camelContext;
/**
* Holder class for breakpoint and the associated conditions
@@ -65,6 +75,21 @@ public List<Condition> getConditions() {
}
}
+ public DefaultDebugger() {
+ }
+
+ public DefaultDebugger(CamelContext camelContext) {
+ this.camelContext = camelContext;
+ }
+
+ public CamelContext getCamelContext() {
+ return camelContext;
+ }
+
+ public void setCamelContext(CamelContext camelContext) {
+ this.camelContext = camelContext;
+ }
+
public void addBreakpoint(Breakpoint breakpoint) {
breakpoints.add(new BreakpointConditions(breakpoint));
}
@@ -97,7 +122,24 @@ public List<Breakpoint> getBreakpoints() {
return Collections.unmodifiableList(answer);
}
- public boolean onExchange(Exchange exchange, Processor processor, ProcessorDefinition definition) {
+ public boolean beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
+ boolean match = false;
+
+ // does any of the breakpoints apply?
+ for (BreakpointConditions breakpoint : breakpoints) {
+ // breakpoint must be active
+ if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) {
+ if (matchConditions(exchange, processor, definition, breakpoint)) {
+ match = true;
+ onBeforeProcess(exchange, processor, definition, breakpoint.getBreakpoint());
+ }
+ }
+ }
+
+ return match;
+ }
+
+ public boolean afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
boolean match = false;
// does any of the breakpoints apply?
@@ -106,7 +148,7 @@ public boolean onExchange(Exchange exchange, Processor processor, ProcessorDefin
if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) {
if (matchConditions(exchange, processor, definition, breakpoint)) {
match = true;
- onBreakpoint(exchange, processor, definition, breakpoint.getBreakpoint());
+ onAfterProcess(exchange, processor, definition, breakpoint.getBreakpoint());
}
}
}
@@ -114,10 +156,61 @@ public boolean onExchange(Exchange exchange, Processor processor, ProcessorDefin
return match;
}
- private boolean matchConditions(Exchange exchange, Processor processor, ProcessorDefinition definition, BreakpointConditions breakpoint) {
+ public boolean onEvent(Exchange exchange, EventObject event) {
+ boolean match = false;
+
+ // does any of the breakpoints apply?
+ for (BreakpointConditions breakpoint : breakpoints) {
+ // breakpoint must be active
+ if (Breakpoint.State.Active.equals(breakpoint.getBreakpoint().getState())) {
+ if (matchConditions(exchange, event, breakpoint)) {
+ match = true;
+ onEvent(exchange, event, breakpoint.getBreakpoint());
+ }
+ }
+ }
+
+ return match;
+ }
+
+ protected void onBeforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition, Breakpoint breakpoint) {
+ try {
+ breakpoint.beforeProcess(exchange, processor, definition);
+ } catch (Throwable e) {
+ LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e);
+ }
+ }
+
+ protected void onAfterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition, Breakpoint breakpoint) {
+ try {
+ breakpoint.afterProcess(exchange, processor, definition);
+ } catch (Throwable e) {
+ LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e);
+ }
+ }
+
+ protected void onEvent(Exchange exchange, EventObject event, Breakpoint breakpoint) {
+ ProcessorDefinition definition = null;
+
+ // try to get the last known definition
+ if (exchange.getUnitOfWork() != null && exchange.getUnitOfWork().getTracedRouteNodes() != null) {
+ RouteNode node = exchange.getUnitOfWork().getTracedRouteNodes().getLastNode();
+ if (node != null) {
+ definition = node.getProcessorDefinition();
+ }
+ }
+
+ try {
+ breakpoint.onEvent(exchange, event, definition);
+ } catch (Throwable e) {
+ LOG.warn("Exception occurred in breakpoint: " + breakpoint + ". This exception will be ignored.", e);
+ }
+ }
+
+ private boolean matchConditions(Exchange exchange, Processor processor, ProcessorDefinition definition, BreakpointConditions breakpoint) {
if (breakpoint.getConditions() != null && !breakpoint.getConditions().isEmpty()) {
for (Condition condition : breakpoint.getConditions()) {
- if (!condition.match(exchange, definition)) {
+ if (!condition.matchProcess(exchange, processor, definition)) {
return false;
}
}
@@ -126,21 +219,66 @@ private boolean matchConditions(Exchange exchange, Processor processor, Process
return true;
}
- protected void onBreakpoint(Exchange exchange, Processor processor, ProcessorDefinition definition, Breakpoint breakpoint) {
- breakpoint.onExchange(exchange, processor, definition);
+ private boolean matchConditions(Exchange exchange, EventObject event, BreakpointConditions breakpoint) {
+ if (breakpoint.getConditions() != null && !breakpoint.getConditions().isEmpty()) {
+ for (Condition condition : breakpoint.getConditions()) {
+ if (!condition.matchEvent(exchange, event)) {
+ return false;
+ }
+ }
+ }
+
+ return true;
}
public void start() throws Exception {
- // noop
+ ObjectHelper.notNull(camelContext, "CamelContext", this);
+ // register our event notifier
+ camelContext.getManagementStrategy().addEventNotifier(new DebugEventNotifier());
+ Tracer tracer = Tracer.getTracer(camelContext);
+ if (tracer == null) {
+ // tracer is disabled so enable it silently so we can leverage it to trace the Exchanges for us
+ tracer = Tracer.createTracer(camelContext);
+ tracer.setLogLevel(LoggingLevel.OFF);
+ camelContext.addService(tracer);
+ camelContext.addInterceptStrategy(tracer);
+ }
}
public void stop() throws Exception {
breakpoints.clear();
- // noop
}
@Override
public String toString() {
return "DefaultDebugger";
}
+
+ private final class DebugEventNotifier extends EventNotifierSupport {
+
+ private DebugEventNotifier() {
+ setIgnoreCamelContextEvents(true);
+ setIgnoreServiceEvents(true);
+ }
+
+ public void notify(EventObject event) throws Exception {
+ AbstractExchangeEvent aee = (AbstractExchangeEvent) event;
+ Exchange exchange = aee.getExchange();
+ onEvent(exchange, event);
+ }
+
+ public boolean isEnabled(EventObject event) {
+ return event instanceof AbstractExchangeEvent;
+ }
+
+ @Override
+ protected void doStart() throws Exception {
+ // noop
+ }
+
+ @Override
+ protected void doStop() throws Exception {
+ // noop
+ }
+ }
}
diff --git a/camel-core/src/main/java/org/apache/camel/management/event/AbstractExchangeEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/AbstractExchangeEvent.java
new file mode 100644
index 0000000000000..0a3f2694392aa
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/management/event/AbstractExchangeEvent.java
@@ -0,0 +1,40 @@
+/**
+ * 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.event;
+
+import java.util.EventObject;
+
+import org.apache.camel.Exchange;
+
+/**
+ * Base class for {@link Exchange} events.
+ *
+ * @version $Revision$
+ */
+public abstract class AbstractExchangeEvent extends EventObject {
+
+ private final Exchange exchange;
+
+ public AbstractExchangeEvent(Exchange source) {
+ super(source);
+ this.exchange = source;
+ }
+
+ public Exchange getExchange() {
+ return exchange;
+ }
+}
diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCompletedEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCompletedEvent.java
index e460e609a188d..4b89267d7c5e7 100644
--- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCompletedEvent.java
+++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCompletedEvent.java
@@ -16,29 +16,20 @@
*/
package org.apache.camel.management.event;
-import java.util.EventObject;
-
import org.apache.camel.Exchange;
/**
* @version $Revision$
*/
-public class ExchangeCompletedEvent extends EventObject {
+public class ExchangeCompletedEvent extends AbstractExchangeEvent {
private static final long serialVersionUID = -3231801412021356098L;
- private final Exchange exchange;
-
public ExchangeCompletedEvent(Exchange source) {
super(source);
- this.exchange = source;
- }
-
- public Exchange getExchange() {
- return exchange;
}
@Override
public String toString() {
- return exchange.getExchangeId() + " exchange completed: " + exchange;
+ return getExchange().getExchangeId() + " exchange completed: " + getExchange();
}
}
diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCreatedEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCreatedEvent.java
index 1cf6a50d5dfbc..658d9ba3079aa 100644
--- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCreatedEvent.java
+++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeCreatedEvent.java
@@ -16,29 +16,20 @@
*/
package org.apache.camel.management.event;
-import java.util.EventObject;
-
import org.apache.camel.Exchange;
/**
* @version $Revision$
*/
-public class ExchangeCreatedEvent extends EventObject {
+public class ExchangeCreatedEvent extends AbstractExchangeEvent {
private static final long serialVersionUID = -19248832613958243L;
- private final Exchange exchange;
-
public ExchangeCreatedEvent(Exchange source) {
super(source);
- this.exchange = source;
- }
-
- public Exchange getExchange() {
- return exchange;
}
@Override
public String toString() {
- return exchange.getExchangeId() + " exchange created: " + exchange;
+ return getExchange().getExchangeId() + " exchange created: " + getExchange();
}
}
diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureEvent.java
index 15ff4d57b0d30..85e537b3d45d8 100644
--- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureEvent.java
+++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureEvent.java
@@ -16,34 +16,25 @@
*/
package org.apache.camel.management.event;
-import java.util.EventObject;
-
import org.apache.camel.Exchange;
/**
* @version $Revision$
*/
-public class ExchangeFailureEvent extends EventObject {
+public class ExchangeFailureEvent extends AbstractExchangeEvent {
private static final long serialVersionUID = -8484326904627268101L;
- private final Exchange exchange;
-
public ExchangeFailureEvent(Exchange source) {
super(source);
- this.exchange = source;
- }
-
- public Exchange getExchange() {
- return exchange;
}
@Override
public String toString() {
- Exception cause = exchange.getException();
+ Exception cause = getExchange().getException();
if (cause != null) {
- return exchange.getExchangeId() + " exchange failure: " + exchange + " cause " + cause;
+ return getExchange().getExchangeId() + " exchange failure: " + getExchange() + " cause " + cause;
} else {
- return exchange.getExchangeId() + " exchange failure: " + exchange;
+ return getExchange().getExchangeId() + " exchange failure: " + getExchange();
}
}
}
diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureHandledEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureHandledEvent.java
index 740e3b0890b15..c711e06363f51 100644
--- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureHandledEvent.java
+++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeFailureHandledEvent.java
@@ -16,32 +16,24 @@
*/
package org.apache.camel.management.event;
-import java.util.EventObject;
-
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
/**
* @version $Revision$
*/
-public class ExchangeFailureHandledEvent extends EventObject {
+public class ExchangeFailureHandledEvent extends AbstractExchangeEvent {
private static final long serialVersionUID = -7554809462006009547L;
- private final Exchange exchange;
private final Processor failureHandler;
private final boolean deadLetterChannel;
private final boolean handled;
public ExchangeFailureHandledEvent(Exchange source, Processor failureHandler, boolean deadLetterChannel) {
super(source);
- this.exchange = source;
this.failureHandler = failureHandler;
this.deadLetterChannel = deadLetterChannel;
- this.handled = exchange.getProperty(Exchange.ERRORHANDLER_HANDLED, false, Boolean.class);
- }
-
- public Exchange getExchange() {
- return exchange;
+ this.handled = source.getProperty(Exchange.ERRORHANDLER_HANDLED, false, Boolean.class);
}
public Processor getFailureHandler() {
@@ -59,9 +51,9 @@ public boolean isHandled() {
@Override
public String toString() {
if (isDeadLetterChannel()) {
- return exchange.getExchangeId() + " exchange failed: " + exchange + " but was handled by dead letter channel: " + failureHandler;
+ return getExchange().getExchangeId() + " exchange failed: " + getExchange() + " but was handled by dead letter channel: " + failureHandler;
} else {
- return exchange.getExchangeId() + " exchange failed: " + exchange + " but was processed by: " + failureHandler;
+ return getExchange().getExchangeId() + " exchange failed: " + getExchange() + " but was processed by: " + failureHandler;
}
}
}
diff --git a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeSentEvent.java b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeSentEvent.java
index bbe6f354e5933..d264bc82c43db 100644
--- a/camel-core/src/main/java/org/apache/camel/management/event/ExchangeSentEvent.java
+++ b/camel-core/src/main/java/org/apache/camel/management/event/ExchangeSentEvent.java
@@ -16,32 +16,24 @@
*/
package org.apache.camel.management.event;
-import java.util.EventObject;
-
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
/**
* @version $Revision$
*/
-public class ExchangeSentEvent extends EventObject {
+public class ExchangeSentEvent extends AbstractExchangeEvent {
private static final long serialVersionUID = -19248832613958123L;
- private final Exchange exchange;
private final Endpoint endpoint;
private final long timeTaken;
public ExchangeSentEvent(Exchange source, Endpoint endpoint, long timeTaken) {
super(source);
- this.exchange = source;
this.endpoint = endpoint;
this.timeTaken = timeTaken;
}
- public Exchange getExchange() {
- return exchange;
- }
-
public Endpoint getEndpoint() {
return endpoint;
}
@@ -52,7 +44,7 @@ public long getTimeTaken() {
@Override
public String toString() {
- return exchange.getExchangeId() + " exchange " + exchange + " sent to: " + endpoint.getEndpointUri() + " took: " + timeTaken + " ms.";
+ return getExchange().getExchangeId() + " exchange " + getExchange() + " sent to: " + endpoint.getEndpointUri() + " took: " + timeTaken + " ms.";
}
}
\ No newline at end of file
diff --git a/camel-core/src/main/java/org/apache/camel/processor/interceptor/Debug.java b/camel-core/src/main/java/org/apache/camel/processor/interceptor/Debug.java
index 5f6ddfa1fd180..1733eed3caaee 100644
--- a/camel-core/src/main/java/org/apache/camel/processor/interceptor/Debug.java
+++ b/camel-core/src/main/java/org/apache/camel/processor/interceptor/Debug.java
@@ -26,6 +26,8 @@
import org.apache.camel.spi.InterceptStrategy;
/**
+ * A debug interceptor to notify {@link Debugger} with {@link Exchange}s being processed.
+ *
* @version $Revision$
*/
public class Debug implements InterceptStrategy {
@@ -40,9 +42,16 @@ public Processor wrapProcessorInInterceptors(final CamelContext context, final P
final Processor target, final Processor nextTarget) throws Exception {
return new DelegateAsyncProcessor(target) {
@Override
- public boolean process(Exchange exchange, AsyncCallback callback) {
- debugger.onExchange(exchange, target, definition);
- return super.process(exchange, callback);
+ public boolean process(final Exchange exchange, final AsyncCallback callback) {
+ debugger.beforeProcess(exchange, target, definition);
+
+ return super.process(exchange, new AsyncCallback() {
+ public void done(boolean doneSync) {
+ debugger.afterProcess(exchange, processor, definition);
+ // must notify original callback
+ callback.done(doneSync);
+ }
+ });
}
@Override
diff --git a/camel-core/src/main/java/org/apache/camel/spi/Breakpoint.java b/camel-core/src/main/java/org/apache/camel/spi/Breakpoint.java
index d4f1d98d33a68..8153955073039 100644
--- a/camel-core/src/main/java/org/apache/camel/spi/Breakpoint.java
+++ b/camel-core/src/main/java/org/apache/camel/spi/Breakpoint.java
@@ -16,6 +16,8 @@
*/
package org.apache.camel.spi;
+import java.util.EventObject;
+
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.model.ProcessorDefinition;
@@ -26,20 +28,19 @@
* This allows you to register {@link org.apache.camel.spi.Breakpoint}s to the {@link org.apache.camel.spi.Debugger}
* and have those breakpoints activated when their {@link org.apache.camel.spi.Condition}s match.
* <p/>
- * If any exceptions is thrown from the {@link #onExchange(org.apache.camel.Exchange, org.apache.camel.Processor, org.apache.camel.model.ProcessorDefinition)}
- * method then the {@link org.apache.camel.spi.Debugger} will catch and log those at <tt>WARN</tt> level and continue.
+ * If any exceptions is thrown from the callback methods then the {@link org.apache.camel.spi.Debugger}
+ * will catch and log those at <tt>WARN</tt> level and continue. This ensures Camel can continue to route
+ * the message without having breakpoints causing issues.
*
+ * @version $Revision$
* @see org.apache.camel.spi.Debugger
* @see org.apache.camel.spi.Condition
- * @version $Revision$
*/
public interface Breakpoint {
- // TODO: Hook into the EventNotifier so we can have breakpoints trigger on those conditions as well
- // exceptions, create, done, etc. and a FollowMe condition to follow a single exchange
- // while others are being routed so you can follow one only, eg need an API on Debugger for that
-
- enum State { Active, Suspended }
+ enum State {
+ Active, Suspended
+ }
/**
* Gets the state of this break
@@ -59,12 +60,32 @@ enum State { Active, Suspended }
void activate();
/**
- * Callback invoked when the breakpoint was hit.
+ * Callback invoked when the breakpoint was hit and the {@link Exchange} is about to be processed (before).
+ *
+ * @param exchange the {@link Exchange}
+ * @param processor the {@link Processor} about to be processed
+ * @param definition the {@link org.apache.camel.model.ProcessorDefinition} definition of the processor
+ */
+ void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition);
+
+ /**
+ * Callback invoked when the breakpoint was hit and the {@link Exchange} has been processed (after).
+ *
+ * @param exchange the {@link Exchange}
+ * @param processor the {@link Processor} which was processed
+ * @param definition the {@link org.apache.camel.model.ProcessorDefinition} definition of the processor
+ */
+ void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition);
+
+ /**
+ * Callback invoked when the breakpoint was hit and any of the {@link Exchange} {@link EventObject event}s occurred.
*
- * @param exchange the {@link Exchange}
- * @param processor the {@link Processor} which is the next target
- * @param definition the {@link org.apache.camel.model.ProcessorDefinition} definition of the processor
+ * @param exchange the {@link Exchange}
+ * @param event the event (instance of {@link org.apache.camel.management.event.AbstractExchangeEvent}
+ * @param definition the {@link org.apache.camel.model.ProcessorDefinition} definition of the last processor executed,
+ * may be <tt>null</tt> if not possible to resolve from tracing
+ * @see org.apache.camel.management.event.AbstractExchangeEvent
*/
- void onExchange(Exchange exchange, Processor processor, ProcessorDefinition definition);
+ void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition);
}
diff --git a/camel-core/src/main/java/org/apache/camel/spi/Condition.java b/camel-core/src/main/java/org/apache/camel/spi/Condition.java
index 9773a05e8f378..e5ccd6617e835 100644
--- a/camel-core/src/main/java/org/apache/camel/spi/Condition.java
+++ b/camel-core/src/main/java/org/apache/camel/spi/Condition.java
@@ -16,7 +16,10 @@
*/
package org.apache.camel.spi;
+import java.util.EventObject;
+
import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
import org.apache.camel.model.ProcessorDefinition;
/**
@@ -33,9 +36,20 @@ public interface Condition {
* Does the condition match
*
* @param exchange the exchange
- * @param definition the current node in the route where the Exchange is at
+ * @param processor the {@link Processor}
+ * @param definition the present location in the route where the {@link Exchange} is located at
+ * @return <tt>true</tt> to match, <tt>false</tt> otherwise
+ */
+ boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition);
+
+ /**
+ * Does the condition match
+ *
+ * @param exchange the exchange
+ * @param event the event (instance of {@link org.apache.camel.management.event.AbstractExchangeEvent}
* @return <tt>true</tt> to match, <tt>false</tt> otherwise
+ * @see org.apache.camel.management.event.AbstractExchangeEvent
*/
- boolean match(Exchange exchange, ProcessorDefinition definition);
+ boolean matchEvent(Exchange exchange, EventObject event);
}
diff --git a/camel-core/src/main/java/org/apache/camel/spi/Debugger.java b/camel-core/src/main/java/org/apache/camel/spi/Debugger.java
index f2c6a78f91807..13823e54e8a9e 100644
--- a/camel-core/src/main/java/org/apache/camel/spi/Debugger.java
+++ b/camel-core/src/main/java/org/apache/camel/spi/Debugger.java
@@ -16,8 +16,10 @@
*/
package org.apache.camel.spi;
+import java.util.EventObject;
import java.util.List;
+import org.apache.camel.CamelContextAware;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.Service;
@@ -29,7 +31,7 @@
*
* @version $Revision$
*/
-public interface Debugger extends Service {
+public interface Debugger extends Service, CamelContextAware {
/**
* Add the given breakpoint
@@ -70,15 +72,36 @@ public interface Debugger extends Service {
*/
List<Breakpoint> getBreakpoints();
+ /**
+ * Callback invoked when an {@link Exchange} is about to be processed which allows implementators
+ * to notify breakpoints.
+ *
+ * @param exchange the exchange
+ * @param processor the {@link Processor} about to be processed
+ * @param definition the definition of the processor
+ * @return <tt>true</tt> if any breakpoint was hit, <tt>false</tt> if not breakpoint was hit
+ */
+ boolean beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition);
+
+ /**
+ * Callback invoked when an {@link Exchange} has been processed which allows implementators
+ * to notify breakpoints.
+ *
+ * @param exchange the exchange
+ * @param processor the {@link Processor} which was processed
+ * @param definition the definition of the processor
+ * @return <tt>true</tt> if any breakpoint was hit, <tt>false</tt> if not breakpoint was hit
+ */
+ boolean afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition);
+
/**
* Callback invoked when an {@link Exchange} is being processed which allows implementators
* to notify breakpoints.
*
- * @param exchange the exchange
- * @param processor the target processor (to be processed next)
- * @param definition the definition of the processor
+ * @param exchange the exchange
+ * @param event the event (instance of {@link org.apache.camel.management.event.AbstractExchangeEvent}
* @return <tt>true</tt> if any breakpoint was hit, <tt>false</tt> if not breakpoint was hit
*/
- boolean onExchange(Exchange exchange, Processor processor, ProcessorDefinition definition);
+ boolean onEvent(Exchange exchange, EventObject event);
}
diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionBreakpointTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionBreakpointTest.java
new file mode 100644
index 0000000000000..96a698258ce16
--- /dev/null
+++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionBreakpointTest.java
@@ -0,0 +1,100 @@
+/**
+ * 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.processor.interceptor;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.BreakpointSupport;
+import org.apache.camel.impl.ConditionSupport;
+import org.apache.camel.impl.DefaultDebugger;
+import org.apache.camel.model.ProcessorDefinition;
+import org.apache.camel.spi.Breakpoint;
+import org.apache.camel.spi.Condition;
+
+/**
+ * @version $Revision$
+ */
+public class DebugExceptionBreakpointTest extends ContextTestSupport {
+
+ private List<String> logs = new ArrayList<String>();
+ private Condition exceptionCondition;
+ private Breakpoint breakpoint;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ breakpoint = new BreakpointSupport() {
+ @Override
+ public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
+ Exception e = exchange.getException();
+ logs.add("Breakpoint at " + definition.getShortName() + " caused by: " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]");
+ }
+ };
+
+ exceptionCondition = new ConditionSupport() {
+ @Override
+ public boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
+ return exchange.getException() != null;
+ }
+ };
+ }
+
+ public void testDebug() throws Exception {
+ context.getDebugger().addBreakpoint(breakpoint, exceptionCondition);
+
+ getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
+
+ template.sendBody("direct:start", "Hello World");
+ try {
+ template.sendBody("direct:start", "Hello Camel");
+ fail("Should have thrown exception");
+ } catch (Exception e) {
+ // ignore
+ }
+
+ assertMockEndpointsSatisfied();
+
+ assertEquals(2, logs.size());
+ assertEquals("Breakpoint at when caused by: IllegalArgumentException[Damn]", logs.get(0));
+ assertEquals("Breakpoint at choice caused by: IllegalArgumentException[Damn]", logs.get(1));
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ // use debugger
+ context.setDebugger(new DefaultDebugger());
+
+ from("direct:start")
+ .to("log:foo")
+ .choice()
+ .when(body().contains("Camel")).throwException(new IllegalArgumentException("Damn"))
+ .end()
+ .to("mock:result");
+ }
+ };
+ }
+
+}
\ No newline at end of file
diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionEventBreakpointTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionEventBreakpointTest.java
new file mode 100644
index 0000000000000..2a7c6fc5b9ee8
--- /dev/null
+++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugExceptionEventBreakpointTest.java
@@ -0,0 +1,100 @@
+/**
+ * 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.processor.interceptor;
+
+import java.util.ArrayList;
+import java.util.EventObject;
+import java.util.List;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.BreakpointSupport;
+import org.apache.camel.impl.ConditionSupport;
+import org.apache.camel.impl.DefaultDebugger;
+import org.apache.camel.management.event.AbstractExchangeEvent;
+import org.apache.camel.management.event.ExchangeFailureEvent;
+import org.apache.camel.model.ProcessorDefinition;
+import org.apache.camel.spi.Breakpoint;
+import org.apache.camel.spi.Condition;
+
+/**
+ * @version $Revision$
+ */
+public class DebugExceptionEventBreakpointTest extends ContextTestSupport {
+
+ private List<String> logs = new ArrayList<String>();
+ private Condition exceptionCondition;
+ private Breakpoint breakpoint;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ breakpoint = new BreakpointSupport() {
+ public void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition) {
+ AbstractExchangeEvent aee = (AbstractExchangeEvent) event;
+ Exception e = aee.getExchange().getException();
+ logs.add("Breakpoint at " + definition + " caused by: " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]");
+ }
+ };
+
+ exceptionCondition = new ConditionSupport() {
+ public boolean matchEvent(Exchange exchange, EventObject event) {
+ return event instanceof ExchangeFailureEvent;
+ }
+ };
+ }
+
+ public void testDebug() throws Exception {
+ context.getDebugger().addBreakpoint(breakpoint, exceptionCondition);
+
+ getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
+
+ template.sendBody("direct:start", "Hello World");
+ try {
+ template.sendBody("direct:start", "Hello Camel");
+ fail("Should have thrown exception");
+ } catch (Exception e) {
+ // ignore
+ }
+
+ assertMockEndpointsSatisfied();
+
+ assertEquals(1, logs.size());
+ assertEquals("Breakpoint at ThrowException[java.lang.IllegalArgumentException] caused by: IllegalArgumentException[Damn]", logs.get(0));
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ // use debugger
+ context.setDebugger(new DefaultDebugger());
+
+ from("direct:start")
+ .to("log:foo")
+ .choice()
+ .when(body().contains("Camel")).throwException(new IllegalArgumentException("Damn"))
+ .end()
+ .to("mock:result");
+ }
+ };
+ }
+
+}
\ No newline at end of file
diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugTest.java
index 781d95d0add22..d35e381fe3939 100644
--- a/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugTest.java
+++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugTest.java
@@ -17,6 +17,7 @@
package org.apache.camel.processor.interceptor;
import java.util.ArrayList;
+import java.util.EventObject;
import java.util.List;
import org.apache.camel.ContextTestSupport;
@@ -24,7 +25,9 @@
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.BreakpointSupport;
+import org.apache.camel.impl.ConditionSupport;
import org.apache.camel.impl.DefaultDebugger;
+import org.apache.camel.management.event.ExchangeCompletedEvent;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.ToDefinition;
import org.apache.camel.spi.Breakpoint;
@@ -38,6 +41,7 @@ public class DebugTest extends ContextTestSupport {
private List<String> logs = new ArrayList<String>();
private Condition camelCondition;
private Condition mockCondition;
+ private Condition doneCondition;
private Breakpoint breakpoint;
@Override
@@ -45,20 +49,25 @@ protected void setUp() throws Exception {
super.setUp();
breakpoint = new BreakpointSupport() {
- public void onExchange(Exchange exchange, Processor processor, ProcessorDefinition definition) {
+ public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
String body = exchange.getIn().getBody(String.class);
logs.add("Breakpoint at " + definition + " with body: " + body);
}
+
+ public void onEvent(Exchange exchange, EventObject event, ProcessorDefinition definition) {
+ String body = exchange.getIn().getBody(String.class);
+ logs.add("Breakpoint event " + event.getClass().getSimpleName() + " with body: " + body);
+ }
};
- camelCondition = new Condition() {
- public boolean match(Exchange exchange, ProcessorDefinition definition) {
+ camelCondition = new ConditionSupport() {
+ public boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
return body().contains("Camel").matches(exchange);
}
};
- mockCondition = new Condition() {
- public boolean match(Exchange exchange, ProcessorDefinition definition) {
+ mockCondition = new ConditionSupport() {
+ public boolean matchProcess(Exchange exchange, Processor processor, ProcessorDefinition definition) {
// match when sending to mocks
if (definition instanceof ToDefinition) {
ToDefinition to = (ToDefinition) definition;
@@ -67,6 +76,13 @@ public boolean match(Exchange exchange, ProcessorDefinition definition) {
return false;
}
};
+
+ doneCondition = new ConditionSupport() {
+ @Override
+ public boolean matchEvent(Exchange exchange, EventObject event) {
+ return event instanceof ExchangeCompletedEvent;
+ }
+ };
}
public void testDebug() throws Exception {
@@ -84,6 +100,21 @@ public void testDebug() throws Exception {
assertEquals("Breakpoint at To[mock:result] with body: Hello Camel", logs.get(1));
}
+ public void testDebugEvent() throws Exception {
+ context.getDebugger().addBreakpoint(breakpoint, doneCondition);
+
+ getMockEndpoint("mock:result").expectedBodiesReceived("Hello World", "Hello Camel");
+
+ template.sendBody("direct:start", "Hello World");
+ template.sendBody("direct:start", "Hello Camel");
+
+ assertMockEndpointsSatisfied();
+
+ assertEquals(2, logs.size());
+ assertEquals("Breakpoint event ExchangeCompletedEvent with body: Hello World", logs.get(0));
+ assertEquals("Breakpoint event ExchangeCompletedEvent with body: Hello Camel", logs.get(1));
+ }
+
public void testDebugSuspended() throws Exception {
context.getDebugger().addBreakpoint(breakpoint, mockCondition, camelCondition);
|
a72066f13f76503665abc5d93fcc6edb65ff3f28
|
hbase
|
HBASE-9600 TestColumnSchemaModel and- TestTableSchemaModel test cases are failing with IBM IBM Java 6--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1525179 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/model/ColumnSchemaModel.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/model/ColumnSchemaModel.java
index e7dc05d032e5..05c2dc0d2444 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/model/ColumnSchemaModel.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/model/ColumnSchemaModel.java
@@ -20,7 +20,7 @@
package org.apache.hadoop.hbase.rest.model;
import java.io.Serializable;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAnyAttribute;
@@ -57,7 +57,7 @@ public class ColumnSchemaModel implements Serializable {
private static QName VERSIONS = new QName(HConstants.VERSIONS);
private String name;
- private Map<QName,Object> attrs = new HashMap<QName,Object>();
+ private Map<QName,Object> attrs = new LinkedHashMap<QName,Object>();
/**
* Default constructor
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/model/TableSchemaModel.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/model/TableSchemaModel.java
index 7812c602017b..6241db91c8cd 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/model/TableSchemaModel.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/model/TableSchemaModel.java
@@ -22,7 +22,7 @@
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -74,7 +74,7 @@ public class TableSchemaModel implements Serializable, ProtobufMessageHandler {
new QName(HColumnDescriptor.COMPRESSION);
private String name;
- private Map<QName,Object> attrs = new HashMap<QName,Object>();
+ private Map<QName,Object> attrs = new LinkedHashMap<QName,Object>();
private List<ColumnSchemaModel> columns = new ArrayList<ColumnSchemaModel>();
/**
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/model/TestColumnSchemaModel.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/model/TestColumnSchemaModel.java
index cb022d12c053..15e165285340 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/model/TestColumnSchemaModel.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/model/TestColumnSchemaModel.java
@@ -59,13 +59,13 @@ public TestColumnSchemaModel() throws Exception {
protected ColumnSchemaModel buildTestModel() {
ColumnSchemaModel model = new ColumnSchemaModel();
model.setName(COLUMN_NAME);
- model.__setBlockcache(BLOCKCACHE);
model.__setBlocksize(BLOCKSIZE);
model.__setBloomfilter(BLOOMFILTER);
+ model.__setBlockcache(BLOCKCACHE);
model.__setCompression(COMPRESSION);
- model.__setInMemory(IN_MEMORY);
- model.__setTTL(TTL);
model.__setVersions(VERSIONS);
+ model.__setTTL(TTL);
+ model.__setInMemory(IN_MEMORY);
return model;
}
|
88cb6d10438fe158268c3ad3a6bed65feb95b9d9
|
coremedia$jangaroo-tools
|
re-animated -enableassertions (-ea) conditional compilation flag
including runtime support and integration test
[git-p4: depot-paths = "//coremedia/jangaroo/": change = 142226]
|
a
|
https://github.com/coremedia/jangaroo-tools
|
diff --git a/jooc/src/it-helper/it-parent/pom.xml b/jooc/src/it-helper/it-parent/pom.xml
index 5fe9f8b3b..521e1aecd 100644
--- a/jooc/src/it-helper/it-parent/pom.xml
+++ b/jooc/src/it-helper/it-parent/pom.xml
@@ -109,7 +109,7 @@
<artifactId>maven-antrun-plugin</artifactId>
<executions>
- <!-- compile the test .js2 files in target/joo -->
+ <!-- compile the test .as files in target/joo -->
<execution>
<id>compile-test-joo</id>
<phase>process-test-resources</phase>
diff --git a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
index 03a928574..a8092ce8a 100644
--- a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
+++ b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
@@ -641,10 +641,8 @@ statement ::=
{: RESULT = new ReturnStatement(r,e,s); :}
| DELETE:d lvalue:e SEMICOLON:s
{: RESULT = new DeleteStatement(d,e,s); :}
-/*
- | ASSERT:a exprOrObjectLiteral:e SEMICOLON:s
- {: RESULT = new AssertStatement(a,e,s); :}
-*/
+ | ASSERT:a LPAREN:lp exprOrObjectLiteral:e RPAREN:rp SEMICOLON:s
+ {: RESULT = new AssertStatement(a,lp,e,rp,s); :}
| THROW:t commaExpr:e SEMICOLON:s
{: RESULT = new ThrowStatement(t,e,s); :}
| SUPER:s LPAREN:lp arguments:args RPAREN:rp
diff --git a/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java b/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java
index e0fdf830b..8dff365cd 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java
@@ -22,19 +22,31 @@
*/
class AssertStatement extends KeywordExprStatement {
+ JooSymbol lParen;
+ JooSymbol rParen;
- public AssertStatement(JooSymbol symAssert, Expr expr, JooSymbol symSemicolon) {
+ public AssertStatement(JooSymbol symAssert, JooSymbol lParen, Expr expr, JooSymbol rParen, JooSymbol symSemicolon) {
super(symAssert, expr, symSemicolon);
+ this.lParen = lParen;
+ this.rParen = rParen;
}
public void generateCode(JsWriter out) throws IOException {
if (out.getEnableAssertions()) {
out.writeSymbolWhitespace(symKeyword);
- out.writeToken("_joo_assert(");
+ out.writeToken("assert");
+ out.writeSymbol(lParen);
+ out.write("(");
optExpr.generateCode(out);
+ out.write(")");
out.write(", ");
- out.writeString(symKeyword.getFileName()+"("+symKeyword.getLine()+","+symKeyword.getColumn()+")");
- out.write(");");
+ out.writeString(symKeyword.getFileName());
+ out.write(", ");
+ out.writeInt(symKeyword.getLine());
+ out.write(", ");
+ out.writeInt(symKeyword.getColumn());
+ out.writeSymbol(rParen);
+ out.writeSymbol(symSemicolon);
} else {
out.beginComment();
super.generateCode(out);
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ant/JoocTask.java b/jooc/src/main/java/net/jangaroo/jooc/ant/JoocTask.java
index 9d683c4c9..66603f8d7 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ant/JoocTask.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ant/JoocTask.java
@@ -280,8 +280,8 @@ protected String[] getJoocArgs() {
if (verbose) {
args.add("-v");
}
- // TODO: reenable assertions
- //if (enableAssertions) args.add("-ea");
+ if (enableAssertions)
+ args.add("-ea");
if (destDir != null) {
args.add("-d");
args.add(destDir.getAbsolutePath());
diff --git a/jooc/src/main/java/net/jangaroo/jooc/config/JoocCommandLineParser.java b/jooc/src/main/java/net/jangaroo/jooc/config/JoocCommandLineParser.java
index f850cf2dd..7f35865e0 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/config/JoocCommandLineParser.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/config/JoocCommandLineParser.java
@@ -43,20 +43,16 @@ public JoocConfiguration parse(String[] argv) throws Exception {
.hasArg()
.withDescription("destination directory for generated JavaScript files")
.create("d");
- /*
Option enableAssertionsOption = OptionBuilder.withLongOpt("enableassertions")
.withDescription("enable assertions")
.create("ea");
- */
Options options = new Options();
options.addOption(help);
options.addOption(version);
options.addOption(verboseOption);
options.addOption(debugOption);
options.addOption(destinationDir);
- /*
options.addOption(enableAssertionsOption);
- */
CommandLineParser parser = new GnuParser();
CommandLine line = null;
@@ -84,11 +80,8 @@ public JoocConfiguration parse(String[] argv) throws Exception {
config.setOutputDirectory(destDir);
}
- config.setEnableAssertions(false); // TODO: use option
- /*
if (line.hasOption(enableAssertionsOption.getOpt()))
- enableAssertions = true;
- */
+ config.setEnableAssertions(true);
if (line.hasOption(debugOption.getOpt())) {
String[] values = line.getOptionValues(debugOption.getOpt());
diff --git a/jooc/src/main/js/joo/Class.js b/jooc/src/main/js/joo/Class.js
index d5397f391..3c20f5fcd 100644
--- a/jooc/src/main/js/joo/Class.js
+++ b/jooc/src/main/js/joo/Class.js
@@ -361,7 +361,11 @@ Function.prototype.bind = function(object) {
var superName = classPrefix+"super";
// static part:
var publicConstructor = this.publicConstructor;
- var privateStatic = {_super: superName};
+ var assert = function(cond, file, line, column) {
+ if (!cond)
+ throw new Error(file+"("+line+":"+column+"): assertion failed");
+ }
+ var privateStatic = {_super: superName, assert: assert};
if (this.superClassDescription) {
// init super class:
@@ -567,6 +571,9 @@ Function.prototype.bind = function(object) {
return ClassDescription.$static.dumpClasses();
}
};
+ theGlobalObject.joo.assert = function(condition, filename, line, column, msg) {
+
+ }
})(this);
// alert("runtime loaded!");
joo.typeOf = function typeOf(obj){
diff --git a/jooc/src/test/java/net/jangaroo/test/JooTestCase.java b/jooc/src/test/java/net/jangaroo/test/JooTestCase.java
index 660b6578f..d8fd7211c 100644
--- a/jooc/src/test/java/net/jangaroo/test/JooTestCase.java
+++ b/jooc/src/test/java/net/jangaroo/test/JooTestCase.java
@@ -33,6 +33,8 @@ public JooTestCase(String name) {
}
protected boolean debug = false;
+ protected boolean ea = false;
+
protected String sourceDir = null;
protected String destinationDir = null;
@@ -85,6 +87,7 @@ protected String[] prependSourceDir(String[] fileNames) {
protected int runJooc(String[] fileNames) {
String[] args = prependSourceDir(fileNames);
if (debug) args = concat("-g", args);
+ if (ea) args = concat("-ea", args);
if (destinationDir != null) args = concat(new String[]{"-d", destinationDir}, args);
Jooc compiler = new Jooc();
System.out.println("jooc " + toString(args));
diff --git a/jooc/src/test/java/net/jangaroo/test/integration/JooRuntimeTestCase.java b/jooc/src/test/java/net/jangaroo/test/integration/JooRuntimeTestCase.java
index 1a04e6e37..32f84ac56 100644
--- a/jooc/src/test/java/net/jangaroo/test/integration/JooRuntimeTestCase.java
+++ b/jooc/src/test/java/net/jangaroo/test/integration/JooRuntimeTestCase.java
@@ -15,6 +15,8 @@
package net.jangaroo.test.integration;
+import net.jangaroo.jooc.Jooc;
+import net.jangaroo.test.JooTestCase;
import org.mozilla.javascript.*;
import java.io.File;
@@ -22,9 +24,6 @@
import java.io.Reader;
import java.io.StringReader;
-import net.jangaroo.jooc.Jooc;
-import net.jangaroo.test.JooTestCase;
-
/**
* A JooTestCase to be executed at runtime
*
@@ -98,10 +97,18 @@ protected Object load(File jsFile) throws Exception {
}
protected void loadClass(String qualifiedJooClassName) throws Exception {
- String jsFileName = qualifiedJooClassName.replace('.',File.separatorChar) + Jooc.OUTPUT_FILE_SUFFIX;
+ String jsFileName = jsFileName(qualifiedJooClassName);
load(jsFileName);
}
+ protected String jsFileName(final String qualifiedJooClassName) {
+ return qualifiedJooClassName.replace('.', File.separatorChar) + Jooc.OUTPUT_FILE_SUFFIX;
+ }
+
+ protected String asFileName(final String qualifiedJooClassName) {
+ return qualifiedJooClassName.replace('.', File.separatorChar) + Jooc.AS_SUFFIX;
+ }
+
protected void initClass(String qualifiedJooClassName) throws Exception {
eval(Jooc.CLASS_FULLY_QUALIFIED_NAME + ".init("+qualifiedJooClassName+")");
}
@@ -147,6 +154,17 @@ protected void expectString(String expected, String script) throws Exception {
}
}
+ protected void expectSubstring(String expected, String script) throws Exception {
+ Object result = eval(script);
+ String actual = null;
+ if (result instanceof String)
+ actual = (String)result;
+ else fail("expected string result, found: " + result.getClass().getName());
+ if (!actual.contains(expected)) {
+ fail("expected substring '" + expected + "' not found within: '" + result + "'");
+ }
+ }
+
protected void expectNumber(double expected, String script) throws Exception {
Object result = eval(script);
double actual = 0;
diff --git a/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java b/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java
index 1fffa49d4..f4a90ed41 100644
--- a/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java
+++ b/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java
@@ -15,6 +15,8 @@
package net.jangaroo.test.integration;
+import java.io.File;
+
/**
* Some basic test cases for JangarooScript compiler and runtime correctness.
*
@@ -36,6 +38,29 @@ public void testIdentityMethod() throws Exception {
expectNumber(43, "obj.m(43)");
}
+ public void testAssert() throws Exception {
+ String qualifiedName = "package1.TestAssert";
+ String asFileName = asFileName(qualifiedName);
+ String jsFileName = jsFileName(qualifiedName);
+ loadClass(qualifiedName);
+
+ String canonicalJsFileName = new File(jsFileName).getCanonicalPath();
+ boolean assertionsEnabled = canonicalJsFileName.contains(File.separatorChar + "debug-and-assert" + File.separatorChar);
+
+ final String script = qualifiedName + ".testAssert()";
+ System.out.println("\ncanonicalJsFileName: " + canonicalJsFileName);
+ System.out.println("\nassertions enabled: " + assertionsEnabled);
+
+ if (!assertionsEnabled) {
+ expectString("no exception thrown", script);
+ } else {
+ int line = 30;
+ int column = 9;
+ String expectedErrorMsgTail = asFileName + "(" + line + ":" + column + "): assertion failed";
+ expectSubstring(expectedErrorMsgTail, qualifiedName + ".testAssert()");
+ }
+ }
+
public void testInheritance() throws Exception {
loadClass("package1.TestInheritanceSuperClass");
loadClass("package1.TestInheritanceSubClass");
diff --git a/jooc/src/test/joo/package1/TestAssert.as b/jooc/src/test/joo/package1/TestAssert.as
new file mode 100644
index 000000000..8ca3c8a21
--- /dev/null
+++ b/jooc/src/test/joo/package1/TestAssert.as
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2008 CoreMedia AG
+ *
+ * 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 package1 /*blubber*/ {
+
+/**
+* a comment
+*/
+public class TestAssert {
+
+ public function TestAssert() {
+ }
+
+ static public function testAssert() :String {
+ try {
+ assert(1 < 2);
+ try {
+ assert(2 < 1);
+ return "no exception thrown";
+ } catch(ex) {
+ return ex.message;
+ }
+ } catch(ex) {
+ return ex.message;
+ }
+ }
+
+}
+}
\ No newline at end of file
diff --git a/maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/AbstractCompilerMojo.java b/maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/AbstractCompilerMojo.java
index 8027b7cab..dc6ff2546 100644
--- a/maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/AbstractCompilerMojo.java
+++ b/maven-plugin/src/main/java/net/jangaroo/jooc/mvnplugin/AbstractCompilerMojo.java
@@ -36,6 +36,12 @@ public abstract class AbstractCompilerMojo extends AbstractMojo {
* @parameter expression="${maven.compile.debug}" default-value="true"
*/
private boolean debug;
+ /**
+ * Set "enableAssertions" to "true" in order to generate runtime checks for assert statements.
+ *
+ * @parameter expression="${maven.compile.ea}" default-value="false"
+ */
+ private boolean enableAssertions;
/**
* If set to "true", the compiler will generate more detailed progress information.
* @parameter expression="${maven.compiler.verbose}" default-value="false"
@@ -88,6 +94,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
JoocConfiguration configuration = new JoocConfiguration();
configuration.setDebug(debug);
+ configuration.setEnableAssertions(enableAssertions);
configuration.setVerbose(verbose);
configuration.setOutputDirectory(getOutputDirectory());
|
a9a93876f2ead9468fd50eba715083c9a7e8a52a
|
drools
|
JBRULES-3714 Add capability to configure- date-effective/date-expires for SpreadSheet--
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java
index 73cb78135c8..9fe46429cd8 100644
--- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java
+++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java
@@ -46,6 +46,8 @@ public enum Code {
ACTIVATIONGROUP( "ACTIVATION-GROUP", "X", 1 ),
AGENDAGROUP( "AGENDA-GROUP", "G", 1 ),
RULEFLOWGROUP( "RULEFLOW-GROUP", "R", 1 ),
+ DATEEFFECTIVE( "DATE-EFFECTIVE", "V", 1 ),
+ DATEEXPIRES( "DATE-EXPIRES", "Z", 1 ),
METADATA( "METADATA", "@" );
private String colHeader;
@@ -80,7 +82,7 @@ public int getMaxCount() {
}
}
- public static final EnumSet<Code> ATTRIBUTE_CODE_SET = EnumSet.range( Code.SALIENCE, Code.RULEFLOWGROUP );
+ public static final EnumSet<Code> ATTRIBUTE_CODE_SET = EnumSet.range( Code.SALIENCE, Code.DATEEXPIRES );
private static final Map<String,Code> tag2code = new HashMap<String,Code>();
static {
diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java
index 1e513078472..c5ba2bb178d 100644
--- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java
+++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java
@@ -240,6 +240,12 @@ private Package buildRuleSet() {
case RULEFLOWGROUP:
ruleset.setRuleFlowGroup( value );
break;
+ case DATEEFFECTIVE:
+ ruleset.setDateEffective( value );
+ break;
+ case DATEEXPIRES:
+ ruleset.setDateExpires( value );
+ break;
}
}
}
@@ -648,6 +654,12 @@ private void nextDataCell(final int row,
case CALENDARS:
this._currentRule.setCalendars( value );
break;
+ case DATEEFFECTIVE:
+ this._currentRule.setDateEffective( value );
+ break;
+ case DATEEXPIRES:
+ this._currentRule.setDateExpires( value );
+ break;
}
}
diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java
index 1b6e45ff102..150eac13869 100644
--- a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java
+++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java
@@ -192,6 +192,10 @@ public void testAttributesXLS() {
rule1 ) > -1 );
assertTrue( drl.indexOf( "calendars \"CAL1\"",
rule1 ) > -1 );
+ assertTrue( drl.indexOf( "date-effective \"01-Jan-2007\"",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "date-expires \"31-Dec-2007\"",
+ rule1 ) > -1 );
int rule2 = drl.indexOf( "rule \"N2\"" );
assertFalse( rule2 == -1 );
@@ -216,6 +220,10 @@ public void testAttributesXLS() {
rule2 ) > -1 );
assertTrue( drl.indexOf( "calendars \"CAL2\"",
rule2 ) > -1 );
+ assertTrue( drl.indexOf( "date-effective \"01-Jan-2012\"",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "date-expires \"31-Dec-2015\"",
+ rule2 ) > -1 );
}
@Test
diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java
index cbfc6e9644a..6d7bf450be7 100644
--- a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java
+++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java
@@ -156,6 +156,26 @@ public void testChooseActionType() {
type = (ActionType) actionTypeMap.get( new Integer(0) );
assertEquals(Code.RULEFLOWGROUP, type.getCode());
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "V", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.DATEEFFECTIVE, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "DATE-EFFECTIVE", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.DATEEFFECTIVE, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "Z", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.DATEEXPIRES, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "DATE-EXPIRES", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.DATEEXPIRES, type.getCode());
+
actionTypeMap = new HashMap<Integer, ActionType>();
ActionType.addNewActionType( actionTypeMap, "@", 0, 1 );
type = (ActionType) actionTypeMap.get( new Integer(0) );
diff --git a/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls
index 3159e4ffeb6..1819888649a 100644
Binary files a/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls and b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls differ
diff --git a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java
index b46e25c7c45..3232fb349be 100644
--- a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java
+++ b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java
@@ -105,6 +105,14 @@ public void setAutoFocus(final boolean value) {
this._attr2value.put( "auto-focus", Boolean.toString( value ) );
}
+ public void setDateEffective(final String value) {
+ this._attr2value.put( "date-effective", asStringLiteral( value ) );
+ }
+
+ public void setDateExpires(final String value) {
+ this._attr2value.put( "date-expires", asStringLiteral( value ) );
+ }
+
public String getAttribute( String name ){
return this._attr2value.get( name ).toString();
}
|
cfdb09b7cbb5ea1732416da7ce45c78ac4c0849b
|
hadoop
|
YARN-578. Fixed NM to use SecureIOUtils for reading- and aggregating logs. Contributed by Omkar Vinit Joshi. svn merge- --ignore-ancestry -c 1487672 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1487686 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 ba3068ef40db6..5bd00122d74be 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -348,6 +348,9 @@ Release 2.0.5-beta - UNRELEASED
YARN-715. Fixed unit test failures - TestDistributedShell and
TestUnmanagedAMLauncher. (Vinod Kumar Vavilapalli via sseth)
+ YARN-578. Fixed NM to use SecureIOUtils for reading and aggregating logs.
+ (Omkar Vinit Joshi via vinodkv)
+
BREAKDOWN OF HADOOP-8562 SUBTASKS AND RELATED JIRAS
YARN-158. Yarn creating package-info.java must not depend on sh.
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
index c519f1795957e..185020dc4a3ce 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
@@ -25,8 +25,8 @@
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
-import java.io.InputStreamReader;
import java.io.IOException;
+import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Writer;
import java.security.PrivilegedExceptionAction;
@@ -50,6 +50,7 @@
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.io.SecureIOUtils;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.file.tfile.TFile;
import org.apache.hadoop.security.UserGroupInformation;
@@ -137,12 +138,15 @@ public static class LogValue {
private final List<String> rootLogDirs;
private final ContainerId containerId;
+ private final String user;
// TODO Maybe add a version string here. Instead of changing the version of
// the entire k-v format
- public LogValue(List<String> rootLogDirs, ContainerId containerId) {
+ public LogValue(List<String> rootLogDirs, ContainerId containerId,
+ String user) {
this.rootLogDirs = new ArrayList<String>(rootLogDirs);
this.containerId = containerId;
+ this.user = user;
// Ensure logs are processed in lexical order
Collections.sort(this.rootLogDirs);
@@ -177,18 +181,30 @@ public void write(DataOutputStream out) throws IOException {
// Write the log itself
FileInputStream in = null;
try {
- in = new FileInputStream(logFile);
+ in = SecureIOUtils.openForRead(logFile, getUser(), null);
byte[] buf = new byte[65535];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
+ } catch (IOException e) {
+ String message = "Error aggregating log file. Log file : "
+ + logFile.getAbsolutePath() + e.getMessage();
+ LOG.error(message, e);
+ out.write(message.getBytes());
} finally {
- in.close();
+ if (in != null) {
+ in.close();
+ }
}
}
}
}
+
+ // Added for testing purpose.
+ public String getUser() {
+ return user;
+ }
}
public static class LogWriter {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
index de755a721564e..248ec3145bd75 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
@@ -18,13 +18,21 @@
package org.apache.hadoop.yarn.logaggregation;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
import java.io.Writer;
+import java.util.Arrays;
import java.util.Collections;
import junit.framework.Assert;
@@ -32,11 +40,14 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.io.nativeio.NativeIO;
import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogReader;
@@ -44,6 +55,7 @@
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogWriter;
import org.apache.hadoop.yarn.util.BuilderUtils;
import org.junit.After;
+import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
@@ -97,7 +109,7 @@ public void testReadAcontainerLogs1() throws Exception {
LogKey logKey = new LogKey(testContainerId);
LogValue logValue =
new LogValue(Collections.singletonList(srcFileRoot.toString()),
- testContainerId);
+ testContainerId, ugi.getShortUserName());
logWriter.append(logKey, logValue);
logWriter.closeWriter();
@@ -131,9 +143,115 @@ public void testReadAcontainerLogs1() throws Exception {
Assert.assertEquals(expectedLength, s.length());
}
+ @Test(timeout=10000)
+ public void testContainerLogsFileAccess() throws IOException {
+ // This test will run only if NativeIO is enabled as SecureIOUtils
+ // require it to be enabled.
+ Assume.assumeTrue(NativeIO.isAvailable());
+ Configuration conf = new Configuration();
+ conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
+ "kerberos");
+ UserGroupInformation.setConfiguration(conf);
+ File workDir = new File(testWorkDir, "testContainerLogsFileAccess1");
+ Path remoteAppLogFile =
+ new Path(workDir.getAbsolutePath(), "aggregatedLogFile");
+ Path srcFileRoot = new Path(workDir.getAbsolutePath(), "srcFiles");
+
+ String data = "Log File content for container : ";
+ // Creating files for container1. Log aggregator will try to read log files
+ // with illegal user.
+ ContainerId testContainerId1 = BuilderUtils.newContainerId(1, 1, 1, 1);
+ Path appDir =
+ new Path(srcFileRoot, testContainerId1.getApplicationAttemptId()
+ .getApplicationId().toString());
+ Path srcFilePath1 = new Path(appDir, testContainerId1.toString());
+ String stdout = "stdout";
+ String stderr = "stderr";
+ writeSrcFile(srcFilePath1, stdout, data + testContainerId1.toString()
+ + stdout);
+ writeSrcFile(srcFilePath1, stderr, data + testContainerId1.toString()
+ + stderr);
+
+ UserGroupInformation ugi =
+ UserGroupInformation.getCurrentUser();
+ LogWriter logWriter = new LogWriter(conf, remoteAppLogFile, ugi);
+
+ LogKey logKey = new LogKey(testContainerId1);
+ String randomUser = "randomUser";
+ LogValue logValue =
+ spy(new LogValue(Collections.singletonList(srcFileRoot.toString()),
+ testContainerId1, randomUser));
+
+ // It is trying simulate a situation where first log file is owned by
+ // different user (probably symlink) and second one by the user itself.
+ when(logValue.getUser()).thenReturn(randomUser).thenReturn(
+ ugi.getShortUserName());
+ logWriter.append(logKey, logValue);
+
+ logWriter.closeWriter();
+
+ BufferedReader in =
+ new BufferedReader(new FileReader(new File(remoteAppLogFile
+ .toUri().getRawPath())));
+ String line;
+ StringBuffer sb = new StringBuffer("");
+ while ((line = in.readLine()) != null) {
+ LOG.info(line);
+ sb.append(line);
+ }
+ line = sb.toString();
+
+ String stdoutFile1 =
+ StringUtils.join(
+ Path.SEPARATOR,
+ Arrays.asList(new String[] {
+ srcFileRoot.toUri().toString(),
+ testContainerId1.getApplicationAttemptId().getApplicationId()
+ .toString(), testContainerId1.toString(), stderr }));
+ String message1 =
+ "Owner '" + ugi.getShortUserName() + "' for path " + stdoutFile1
+ + " did not match expected owner '" + randomUser + "'";
+
+ String stdoutFile2 =
+ StringUtils.join(
+ Path.SEPARATOR,
+ Arrays.asList(new String[] {
+ srcFileRoot.toUri().toString(),
+ testContainerId1.getApplicationAttemptId().getApplicationId()
+ .toString(), testContainerId1.toString(), stdout }));
+ String message2 =
+ "Owner '" + ugi.getShortUserName() + "' for path "
+ + stdoutFile2 + " did not match expected owner '"
+ + ugi.getShortUserName() + "'";
+
+ Assert.assertTrue(line.contains(message1));
+ Assert.assertFalse(line.contains(message2));
+ Assert.assertFalse(line.contains(data + testContainerId1.toString()
+ + stderr));
+ Assert.assertTrue(line.contains(data + testContainerId1.toString()
+ + stdout));
+ }
private void writeSrcFile(Path srcFilePath, String fileName, long length)
throws IOException {
+ OutputStreamWriter osw = getOutputStreamWriter(srcFilePath, fileName);
+ int ch = filler;
+ for (int i = 0; i < length; i++) {
+ osw.write(ch);
+ }
+ osw.close();
+ }
+
+ private void writeSrcFile(Path srcFilePath, String fileName, String data)
+ throws IOException {
+ OutputStreamWriter osw = getOutputStreamWriter(srcFilePath, fileName);
+ osw.write(data);
+ osw.close();
+ }
+
+ private OutputStreamWriter getOutputStreamWriter(Path srcFilePath,
+ String fileName) throws IOException, FileNotFoundException,
+ UnsupportedEncodingException {
File dir = new File(srcFilePath.toString());
if (!dir.exists()) {
if (!dir.mkdirs()) {
@@ -143,10 +261,6 @@ private void writeSrcFile(Path srcFilePath, String fileName, long length)
File outputFile = new File(new File(srcFilePath.toString()), fileName);
FileOutputStream os = new FileOutputStream(outputFile);
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF8");
- int ch = filler;
- for (int i = 0; i < length; i++) {
- osw.write(ch);
- }
- osw.close();
+ return osw;
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/resources/krb5.conf b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/resources/krb5.conf
new file mode 100644
index 0000000000000..121ac6d9b981a
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/resources/krb5.conf
@@ -0,0 +1,28 @@
+#
+# 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.
+#
+[libdefaults]
+ default_realm = APACHE.ORG
+ udp_preference_limit = 1
+ extra_addresses = 127.0.0.1
+[realms]
+ APACHE.ORG = {
+ admin_server = localhost:88
+ kdc = localhost:88
+ }
+[domain_realm]
+ localhost = APACHE.ORG
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
index f9a0558563df4..6ef794442c3e1 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
@@ -123,7 +123,9 @@ private void uploadLogsForContainer(ContainerId containerId) {
+ ". Current good log dirs are "
+ StringUtils.join(",", dirsHandler.getLogDirs()));
LogKey logKey = new LogKey(containerId);
- LogValue logValue = new LogValue(dirsHandler.getLogDirs(), containerId);
+ LogValue logValue =
+ new LogValue(dirsHandler.getLogDirs(), containerId,
+ userUgi.getShortUserName());
try {
this.writer.append(logKey, logValue);
} catch (IOException e) {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java
index 5fdd9577d0fb0..452a8237cb85e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsPage.java
@@ -39,8 +39,8 @@
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.SecureIOUtils;
import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
@@ -52,8 +52,8 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.util.ConverterUtils;
-import org.apache.hadoop.yarn.webapp.YarnWebParams;
import org.apache.hadoop.yarn.webapp.SubView;
+import org.apache.hadoop.yarn.webapp.YarnWebParams;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.PRE;
import org.apache.hadoop.yarn.webapp.view.HtmlBlock;
@@ -228,6 +228,27 @@ private void printLogs(Block html, ContainerId containerId,
return;
} else {
FileInputStream logByteStream = null;
+
+ try {
+ logByteStream =
+ SecureIOUtils.openForRead(logFile, application.getUser(), null);
+ } catch (IOException e) {
+ LOG.error(
+ "Exception reading log file " + logFile.getAbsolutePath(), e);
+ if (e.getMessage().contains(
+ "did not match expected owner '" + application.getUser()
+ + "'")) {
+ html.h1("Exception reading log file. Application submitted by '"
+ + application.getUser()
+ + "' doesn't own requested log file : "
+ + logFile.getName());
+ } else {
+ html.h1("Exception reading log file. It might be because log "
+ + "file was aggregated : " + logFile.getName());
+ }
+ return;
+ }
+
try {
long toRead = end - start;
if (toRead < logFile.length()) {
@@ -236,11 +257,8 @@ private void printLogs(Block html, ContainerId containerId,
logFile.getName(), "?start=0"), "here").
_(" for full log")._();
}
- // TODO: Use secure IO Utils to avoid symlink attacks.
// TODO Fix findBugs close warning along with IOUtils change
- logByteStream = new FileInputStream(logFile);
IOUtils.skipFully(logByteStream, start);
-
InputStreamReader reader = new InputStreamReader(logByteStream);
int bufferSize = 65536;
char[] cbuf = new char[bufferSize];
@@ -260,8 +278,10 @@ private void printLogs(Block html, ContainerId containerId,
reader.close();
} catch (IOException e) {
- html.h1("Exception reading log-file. Log file was likely aggregated. "
- + StringUtils.stringifyException(e));
+ LOG.error(
+ "Exception reading log file " + logFile.getAbsolutePath(), e);
+ html.h1("Exception reading log file. It might be because log "
+ + "file was aggregated : " + logFile.getName());
} finally {
if (logByteStream != null) {
try {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java
index 43a5401ab4256..3fa594a889552 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestLogAggregationService.java
@@ -18,6 +18,7 @@
package org.apache.hadoop.yarn.server.nodemanager.containermanager.logaggregation;
+import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
@@ -126,6 +127,7 @@ public void tearDown() throws IOException, InterruptedException {
@SuppressWarnings("unchecked")
public void testLocalFileDeletionAfterUpload() throws Exception {
this.delSrvc = new DeletionService(createContainerExecutor());
+ delSrvc = spy(delSrvc);
this.delSrvc.init(conf);
this.conf.set(YarnConfiguration.NM_LOG_DIRS, localLogDir.getAbsolutePath());
this.conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR,
@@ -169,7 +171,8 @@ public void testLocalFileDeletionAfterUpload() throws Exception {
// ensure filesystems were closed
verify(logAggregationService).closeFileSystems(
any(UserGroupInformation.class));
-
+ verify(delSrvc).delete(eq(user), eq((Path) null),
+ eq(new Path(app1LogDir.getAbsolutePath())));
delSrvc.stop();
String containerIdStr = ConverterUtils.toString(container11);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java
index 459493959ade7..76be0a2342303 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestContainerLogsPage.java
@@ -18,27 +18,48 @@
package org.apache.hadoop.yarn.server.nodemanager.webapp;
+import static org.junit.Assume.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.verify;
+import java.io.BufferedOutputStream;
import java.io.File;
+import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.io.nativeio.NativeIO;
+import org.apache.hadoop.security.UserGroupInformation;
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.conf.YarnConfiguration;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
+import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+import org.apache.hadoop.yarn.server.nodemanager.webapp.ContainerLogsPage.ContainersLogsBlock;
+import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.util.BuilderUtils;
+import org.apache.hadoop.yarn.webapp.YarnWebParams;
+import org.apache.hadoop.yarn.webapp.test.WebAppTests;
import org.junit.Assert;
import org.junit.Test;
+import com.google.inject.Injector;
+import com.google.inject.Module;
+
public class TestContainerLogsPage {
@Test(timeout=30000)
@@ -69,4 +90,99 @@ public void testContainerLogDirs() throws IOException {
container1, dirsHandler);
Assert.assertTrue(!(files.get(0).toString().contains("file:")));
}
+
+ @Test(timeout = 10000)
+ public void testContainerLogPageAccess() throws IOException {
+ // SecureIOUtils require Native IO to be enabled. This test will run
+ // only if it is enabled.
+ assumeTrue(NativeIO.isAvailable());
+ String user = "randomUser" + System.currentTimeMillis();
+ File absLogDir = null, appDir = null, containerDir = null, syslog = null;
+ try {
+ // target log directory
+ absLogDir =
+ new File("target", TestContainerLogsPage.class.getSimpleName()
+ + "LogDir").getAbsoluteFile();
+ absLogDir.mkdir();
+
+ Configuration conf = new Configuration();
+ conf.set(YarnConfiguration.NM_LOG_DIRS, absLogDir.toURI().toString());
+ conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
+ "kerberos");
+ UserGroupInformation.setConfiguration(conf);
+
+ NodeHealthCheckerService healthChecker = new NodeHealthCheckerService();
+ healthChecker.init(conf);
+ LocalDirsHandlerService dirsHandler = healthChecker.getDiskHandler();
+ // Add an application and the corresponding containers
+ RecordFactory recordFactory =
+ RecordFactoryProvider.getRecordFactory(conf);
+ long clusterTimeStamp = 1234;
+ ApplicationId appId =
+ BuilderUtils.newApplicationId(recordFactory, clusterTimeStamp, 1);
+ Application app = mock(Application.class);
+ when(app.getAppId()).thenReturn(appId);
+
+ // Making sure that application returns a random user. This is required
+ // for SecureIOUtils' file owner check.
+ when(app.getUser()).thenReturn(user);
+
+ ApplicationAttemptId appAttemptId =
+ BuilderUtils.newApplicationAttemptId(appId, 1);
+ ContainerId container1 =
+ BuilderUtils.newContainerId(recordFactory, appId, appAttemptId, 0);
+
+ // Testing secure read access for log files
+
+ // Creating application and container directory and syslog file.
+ appDir = new File(absLogDir, appId.toString());
+ appDir.mkdir();
+ containerDir = new File(appDir, container1.toString());
+ containerDir.mkdir();
+ syslog = new File(containerDir, "syslog");
+ syslog.createNewFile();
+ BufferedOutputStream out =
+ new BufferedOutputStream(new FileOutputStream(syslog));
+ out.write("Log file Content".getBytes());
+ out.close();
+
+ ApplicationACLsManager aclsManager = mock(ApplicationACLsManager.class);
+
+ Context context = mock(Context.class);
+ ConcurrentMap<ApplicationId, Application> appMap =
+ new ConcurrentHashMap<ApplicationId, Application>();
+ appMap.put(appId, app);
+ when(context.getApplications()).thenReturn(appMap);
+ when(context.getContainers()).thenReturn(
+ new ConcurrentHashMap<ContainerId, Container>());
+
+ ContainersLogsBlock cLogsBlock =
+ new ContainersLogsBlock(conf, context, aclsManager, dirsHandler);
+
+ Map<String, String> params = new HashMap<String, String>();
+ params.put(YarnWebParams.CONTAINER_ID, container1.toString());
+ params.put(YarnWebParams.CONTAINER_LOG_TYPE, "syslog");
+
+ Injector injector =
+ WebAppTests.testPage(ContainerLogsPage.class,
+ ContainersLogsBlock.class, cLogsBlock, params, (Module[])null);
+ PrintWriter spyPw = WebAppTests.getPrintWriter(injector);
+ verify(spyPw).write(
+ "Exception reading log file. Application submitted by '" + user
+ + "' doesn't own requested log file : syslog");
+ } finally {
+ if (syslog != null) {
+ syslog.delete();
+ }
+ if (containerDir != null) {
+ containerDir.delete();
+ }
+ if (appDir != null) {
+ appDir.delete();
+ }
+ if (absLogDir != null) {
+ absLogDir.delete();
+ }
+ }
+ }
}
|
f9ce11eef8b05e7e31b45a428d63ae35eed8ed42
|
spring-framework
|
Provide controller level Cache-Control support--Prior to this commit
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-web/src/main/java/org/springframework/http/ResponseEntity.java b/spring-web/src/main/java/org/springframework/http/ResponseEntity.java
index 840f696bd735..5d00716d5f94 100644
--- a/spring-web/src/main/java/org/springframework/http/ResponseEntity.java
+++ b/spring-web/src/main/java/org/springframework/http/ResponseEntity.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.
@@ -59,6 +59,7 @@
* </pre>
*
* @author Arjen Poutsma
+ * @author Brian Clozel
* @since 3.0.2
* @see #getStatusCode()
*/
@@ -318,6 +319,20 @@ public interface HeadersBuilder<B extends HeadersBuilder<B>> {
*/
B location(URI location);
+ /**
+ * Set the caching directives for the resource, as specified by the
+ * {@code Cache-Control} header.
+ *
+ * <p>A {@code CacheControl} instance can be built like
+ * {@code CacheControl.maxAge(3600).cachePublic().noTransform()}.
+ *
+ * @param cacheControl the instance that builds cache related HTTP response headers
+ * @return this builder
+ * @see <a href="https://tools.ietf.org/html/rfc7234#section-5.2">RFC-7234 Section 5.2</a>
+ * @since 4.2
+ */
+ B cacheControl(CacheControl cacheControl);
+
/**
* Build the response entity with no body.
* @return the response entity
@@ -423,6 +438,15 @@ public BodyBuilder location(URI location) {
return this;
}
+ @Override
+ public BodyBuilder cacheControl(CacheControl cacheControl) {
+ String ccValue = cacheControl.getHeaderValue();
+ if(ccValue != null) {
+ this.headers.setCacheControl(cacheControl.getHeaderValue());
+ }
+ return this;
+ }
+
@Override
public ResponseEntity<Void> build() {
return new ResponseEntity<Void>(null, this.headers, this.status);
diff --git a/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java b/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java
index bb54104652ab..5ce43e8dad0d 100644
--- a/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java
+++ b/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java
@@ -19,11 +19,14 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.hamcrest.Matchers;
import org.junit.Test;
import static org.junit.Assert.*;
+
/**
* @author Arjen Poutsma
* @author Marcel Overdijk
@@ -163,7 +166,7 @@ public void headers() throws URISyntaxException {
}
@Test
- public void headersCopy(){
+ public void headersCopy() {
HttpHeaders customHeaders = new HttpHeaders();
customHeaders.set("X-CustomHeader", "vale");
@@ -178,7 +181,7 @@ public void headersCopy(){
}
@Test // SPR-12792
- public void headersCopyWithEmptyAndNull(){
+ public void headersCopyWithEmptyAndNull() {
ResponseEntity<Void> responseEntityWithEmptyHeaders =
ResponseEntity.ok().headers(new HttpHeaders()).build();
ResponseEntity<Void> responseEntityWithNullHeaders =
@@ -189,4 +192,58 @@ public void headersCopyWithEmptyAndNull(){
assertEquals(responseEntityWithEmptyHeaders.toString(), responseEntityWithNullHeaders.toString());
}
+ @Test
+ public void emptyCacheControl() {
+
+ Integer entity = new Integer(42);
+
+ ResponseEntity<Integer> responseEntity =
+ ResponseEntity.status(HttpStatus.OK)
+ .cacheControl(CacheControl.empty())
+ .body(entity);
+
+ assertNotNull(responseEntity);
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertFalse(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL));
+ assertEquals(entity, responseEntity.getBody());
+ }
+
+ @Test
+ public void cacheControl() {
+
+ Integer entity = new Integer(42);
+
+ ResponseEntity<Integer> responseEntity =
+ ResponseEntity.status(HttpStatus.OK)
+ .cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePrivate().
+ mustRevalidate().proxyRevalidate().sMaxAge(30, TimeUnit.MINUTES))
+ .body(entity);
+
+ assertNotNull(responseEntity);
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertTrue(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL));
+ assertEquals(entity, responseEntity.getBody());
+ String cacheControlHeader = responseEntity.getHeaders().getCacheControl();
+ assertThat(cacheControlHeader, Matchers.equalTo("max-age=3600, must-revalidate, private, proxy-revalidate, s-maxage=1800"));
+ }
+
+ @Test
+ public void cacheControlNoCache() {
+
+ Integer entity = new Integer(42);
+
+ ResponseEntity<Integer> responseEntity =
+ ResponseEntity.status(HttpStatus.OK)
+ .cacheControl(CacheControl.noStore())
+ .body(entity);
+
+ assertNotNull(responseEntity);
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertTrue(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL));
+ assertEquals(entity, responseEntity.getBody());
+
+ String cacheControlHeader = responseEntity.getHeaders().getCacheControl();
+ assertThat(cacheControlHeader, Matchers.equalTo("no-store"));
+ }
+
}
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java
index 27989f45a36b..90b7b059fc10 100644
--- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java
+++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.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.
@@ -31,6 +31,7 @@
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.Assert;
+import org.springframework.util.StringUtils;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.support.WebDataBinderFactory;
@@ -139,12 +140,36 @@ public void handleReturnValue(Object returnValue, MethodParameter returnType,
}
Object body = responseEntity.getBody();
+ if (responseEntity instanceof ResponseEntity) {
+ if (isResourceNotModified(webRequest, (ResponseEntity<?>) responseEntity)) {
+ // Ensure headers are flushed, no body should be written
+ outputMessage.flush();
+ // skip call to converters, as they may update the body
+ return;
+ }
+ }
// Try even with null body. ResponseBodyAdvice could get involved.
writeWithMessageConverters(body, returnType, inputMessage, outputMessage);
// Ensure headers are flushed even if no body was written
- outputMessage.getBody();
+ outputMessage.flush();
+ }
+
+ private boolean isResourceNotModified(NativeWebRequest webRequest, ResponseEntity<?> responseEntity) {
+ String eTag = responseEntity.getHeaders().getETag();
+ long lastModified = responseEntity.getHeaders().getLastModified();
+ boolean notModified = false;
+ if (lastModified != -1 && StringUtils.hasLength(eTag)) {
+ notModified = webRequest.checkNotModified(eTag, lastModified);
+ }
+ else if (lastModified != -1) {
+ notModified = webRequest.checkNotModified(lastModified);
+ }
+ else if (StringUtils.hasLength(eTag)) {
+ notModified = webRequest.checkNotModified(eTag);
+ }
+ return notModified;
}
@Override
diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java
index 273283fdbca0..dc3e70b3c2a0 100644
--- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java
+++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.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.
@@ -18,8 +18,12 @@
import java.lang.reflect.Method;
import java.net.URI;
+import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
@@ -106,7 +110,7 @@ public void setUp() throws Exception {
returnTypeInt = new MethodParameter(getClass().getMethod("handle3"), -1);
mavContainer = new ModelAndViewContainer();
- servletRequest = new MockHttpServletRequest();
+ servletRequest = new MockHttpServletRequest("GET", "/foo");
servletResponse = new MockHttpServletResponse();
webRequest = new ServletWebRequest(servletRequest, servletResponse);
}
@@ -320,6 +324,98 @@ public void responseHeaderAndBody() throws Exception {
assertEquals("headerValue", outputMessage.getValue().getHeaders().get("header").get(0));
}
+ @Test
+ public void handleReturnTypeLastModified() throws Exception {
+ long currentTime = new Date().getTime();
+ long oneMinuteAgo = currentTime - (1000 * 60);
+ servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, currentTime);
+ HttpHeaders responseHeaders = new HttpHeaders();
+ responseHeaders.setDate(HttpHeaders.LAST_MODIFIED, oneMinuteAgo);
+ ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.OK);
+
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
+
+ processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
+
+ assertTrue(mavContainer.isRequestHandled());
+ assertEquals(HttpStatus.NOT_MODIFIED.value(), servletResponse.getStatus());
+ assertEquals(oneMinuteAgo/1000 * 1000, Long.parseLong(servletResponse.getHeader(HttpHeaders.LAST_MODIFIED)));
+ assertEquals(0, servletResponse.getContentAsByteArray().length);
+ }
+
+ @Test
+ public void handleReturnTypeEtag() throws Exception {
+ String etagValue = "\"deadb33f8badf00d\"";
+ servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
+ HttpHeaders responseHeaders = new HttpHeaders();
+ responseHeaders.set(HttpHeaders.ETAG, etagValue);
+ ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.OK);
+
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
+
+ processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
+
+ assertTrue(mavContainer.isRequestHandled());
+ assertEquals(HttpStatus.NOT_MODIFIED.value(), servletResponse.getStatus());
+ assertEquals(etagValue, servletResponse.getHeader(HttpHeaders.ETAG));
+ assertEquals(0, servletResponse.getContentAsByteArray().length);
+ }
+
+ @Test
+ public void handleReturnTypeETagAndLastModified() throws Exception {
+ long currentTime = new Date().getTime();
+ long oneMinuteAgo = currentTime - (1000 * 60);
+ String etagValue = "\"deadb33f8badf00d\"";
+ servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, currentTime);
+ servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
+ HttpHeaders responseHeaders = new HttpHeaders();
+ responseHeaders.setDate(HttpHeaders.LAST_MODIFIED, oneMinuteAgo);
+ responseHeaders.set(HttpHeaders.ETAG, etagValue);
+ ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.OK);
+
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
+
+ processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
+
+ assertTrue(mavContainer.isRequestHandled());
+ assertEquals(HttpStatus.NOT_MODIFIED.value(), servletResponse.getStatus());
+ assertEquals(oneMinuteAgo/1000 * 1000, Long.parseLong(servletResponse.getHeader(HttpHeaders.LAST_MODIFIED)));
+ assertEquals(etagValue, servletResponse.getHeader(HttpHeaders.ETAG));
+ assertEquals(0, servletResponse.getContentAsByteArray().length);
+ }
+
+ @Test
+ public void handleReturnTypeChangedETagAndLastModified() throws Exception {
+ long currentTime = new Date().getTime();
+ long oneMinuteAgo = currentTime - (1000 * 60);
+ String etagValue = "\"deadb33f8badf00d\"";
+ String changedEtagValue = "\"changed-etag-value\"";
+ servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, currentTime);
+ servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
+ HttpHeaders responseHeaders = new HttpHeaders();
+ responseHeaders.setDate(HttpHeaders.LAST_MODIFIED, oneMinuteAgo);
+ responseHeaders.set(HttpHeaders.ETAG, changedEtagValue);
+ ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.OK);
+
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
+
+ processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
+
+ assertTrue(mavContainer.isRequestHandled());
+ assertEquals(HttpStatus.OK.value(), servletResponse.getStatus());
+ assertEquals(oneMinuteAgo/1000 * 1000, Long.parseLong(servletResponse.getHeader(HttpHeaders.LAST_MODIFIED)));
+ assertEquals(changedEtagValue, servletResponse.getHeader(HttpHeaders.ETAG));
+ assertEquals(0, servletResponse.getContentAsByteArray().length);
+ }
+
public ResponseEntity<String> handle1(HttpEntity<String> httpEntity, ResponseEntity<String> responseEntity, int i, RequestEntity<String> requestEntity) {
return responseEntity;
}
|
7ff073ed301e732ae2805481d63854fa0be93180
|
arquillian$arquillian-graphene
|
Add support for multiple @InitialPage with parallel browsers
Fixes ARQGRA-478
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageObjectsLocation.java b/ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageObjectsLocation.java
index b5b857c8f..95985288f 100644
--- a/ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageObjectsLocation.java
+++ b/ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageObjectsLocation.java
@@ -42,6 +42,7 @@
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
+import qualifier.Browser2;
import qualifier.Browser3;
@RunWith(Arquillian.class)
@@ -51,6 +52,10 @@ public class TestPageObjectsLocation {
@Drone
private WebDriver browser;
+ @Drone
+ @Browser2
+ private WebDriver browser2;
+
@Drone
@Browser3
private WebDriver browser3;
@@ -111,6 +116,21 @@ public void testInitialPageCustomBrowser(@Browser3 @InitialPage MyPageObject2 ob
checkMyPageObject2(obj);
}
+ @Test
+ public void testMultipleInitialPagesWithCustomBrowsers(
+ @Browser2 @InitialPage MyPageObject2 page1,
+ @Browser3 @InitialPage MyPageObject2 page2) {
+ browser.get(contextRoot.toExternalForm());
+ checkMyPageObject2(page1);
+ checkMyPageObject2(page2);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testMultipleInitialPagesGoingToSameBrowser(
+ @Browser2 @InitialPage MyPageObject2 page1,
+ @Browser2 @InitialPage MyPageObject2 page2) {
+ }
+
@Test
public void testGotoPageCustomBrowser() {
MyPageObject2 page2 = Graphene.goTo(MyPageObject2.class, Browser3.class);
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/location/LocationEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/location/LocationEnricher.java
index dbc6b30f9..3ae86930b 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/location/LocationEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/location/LocationEnricher.java
@@ -23,7 +23,11 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
+import java.util.ArrayList;
import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import org.jboss.arquillian.core.api.Injector;
import org.jboss.arquillian.core.api.Instance;
@@ -60,17 +64,24 @@ public void enrich(Object testCase) {
@Override
public Object[] resolve(Method method) {
- int indexOfInitialPage = getIndexOfParameterWithAnnotation(InitialPage.class, method);
- if (indexOfInitialPage == -1) {
+ List<Integer> indicesOfInitialPage = getIndexOfParameterWithAnnotation(InitialPage.class, method);
+ if (indicesOfInitialPage.isEmpty()) {
return new Object[method.getParameterTypes().length];
}
- Class<?> qualifier = ReflectionHelper.getQualifier(method.getParameterAnnotations()[indexOfInitialPage]);
- Class<?>[] parameterTypes = method.getParameterTypes();
- Object[] result = new Object[method.getParameterTypes().length];
- result[indexOfInitialPage] = goTo(parameterTypes[indexOfInitialPage], qualifier);
+ Object[] results = new Object[method.getParameterTypes().length];
+ Set<Class<?>> usedQualifiers = new HashSet<Class<?>>();
+ for (Integer indexOfInitialPage : indicesOfInitialPage) {
+ Class<?> qualifier = ReflectionHelper.getQualifier(method.getParameterAnnotations()[indexOfInitialPage]);
+ if (usedQualifiers.contains(qualifier)) {
+ throw new IllegalArgumentException("There are multiple @InitialPage parameters using the same qualifier");
+ }
+ usedQualifiers.add(qualifier);
+ Class<?>[] parameterTypes = method.getParameterTypes();
+ results[indexOfInitialPage] = goTo(parameterTypes[indexOfInitialPage], qualifier);
+ }
- return result;
+ return results;
}
public <T> T goTo(Class<T> pageObject, Class<?> browserQualifier) {
@@ -132,28 +143,18 @@ private void handleLocationOf(Class<?> pageObjectClass, WebDriver browser) {
* @param method
* @return
*/
- private int getIndexOfParameterWithAnnotation(Class<? extends Annotation> annotation, Method method) {
+ private List<Integer> getIndexOfParameterWithAnnotation(Class<? extends Annotation> annotation, Method method) {
Annotation[][] annotationsOfAllParameters = method.getParameterAnnotations();
- int result = 0;
- boolean founded = false;
- for (; result < annotationsOfAllParameters.length; result++) {
- for (int j = 0; j < annotationsOfAllParameters[result].length; j++) {
- if (annotationsOfAllParameters[result][j].annotationType().equals(annotation)) {
- founded = true;
- break;
+ List<Integer> results = new ArrayList<Integer>();
+ for (int i = 0; i < annotationsOfAllParameters.length; i++) {
+ for (int j = 0; j < annotationsOfAllParameters[i].length; j++) {
+ if (annotationsOfAllParameters[i][j].annotationType().equals(annotation)) {
+ results.add(i);
}
}
- if (founded) {
- break;
- }
}
- if (!founded) {
- // the method has no parameters with Location annotation
- return -1;
- }
-
- return result;
+ return results;
}
private LocationDecider resolveDecider(Collection<LocationDecider> deciders, Class<?> scheme) {
|
fbf70d4fbfd01a5f7f5798c32d61aad97b7ca540
|
drools
|
fix test using using no longer existing- ConsequenceException.getRule() method--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
index c2b421650e1..7ce9c814c87 100644
--- a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
+++ b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
@@ -2874,7 +2874,7 @@ public void testConsequenceException() throws Exception {
fail( "Should throw an Exception from the Consequence" );
} catch ( final org.drools.runtime.rule.ConsequenceException e ) {
assertEquals( "Throw Consequence Exception",
- e.getRule().getName() );
+ e.getActivation().getRule().getName() );
assertEquals( "this should throw an exception",
e.getCause().getMessage() );
}
|
124d1524d913a177088a3acb46cc2a6181b276f9
|
internetarchive$heritrix3
|
[HER-1546] Springify(5): Update checkpointing to work smoothly with spring-configured crawls
processor-related bean checkpoint support:
* Processor.java
implement Checkpointable and BeanNameAware; methods to support JSON state-saving
* DispositionChain.java
implement Checkpointable and during-checkpoint disposition-lockout for state stability
|
p
|
https://github.com/internetarchive/heritrix3
|
diff --git a/modules/src/main/java/org/archive/modules/DispositionChain.java b/modules/src/main/java/org/archive/modules/DispositionChain.java
index cbbb9ff17..67a71431d 100644
--- a/modules/src/main/java/org/archive/modules/DispositionChain.java
+++ b/modules/src/main/java/org/archive/modules/DispositionChain.java
@@ -1,5 +1,61 @@
package org.archive.modules;
-public class DispositionChain extends ProcessorChain {
+import java.io.IOException;
+/*
+ * This file is part of the Heritrix web crawler (crawler.archive.org).
+ *
+ * Licensed to the Internet Archive (IA) by one or more individual
+ * contributors.
+ *
+ * The IA 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.
+ */
+
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import org.archive.checkpointing.Checkpointable;
+import org.archive.crawler.framework.Checkpoint;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public class DispositionChain extends ProcessorChain implements Checkpointable {
+ protected ReentrantReadWriteLock dispositionInProgressLock =
+ new ReentrantReadWriteLock(true);
+
+
+ public void startCheckpoint(Checkpoint checkpointInProgress) {
+ dispositionInProgressLock.writeLock().lock();
+ }
+
+ public void doCheckpoint(Checkpoint checkpointInProgress) throws IOException {
+ // do nothing; this class only participates in checkpointing
+ // via the startCheckpoint/finishCheckpoint locking
+ }
+
+ public void finishCheckpoint(Checkpoint checkpointInProgress) {
+ dispositionInProgressLock.writeLock().unlock();
+ }
+
+ @Autowired(required=false)
+ public void setRecoveryCheckpoint(Checkpoint checkpoint) {
+ // do nothing
+ }
+
+ @Override
+ public void process(CrawlURI curi, ChainStatusReceiver thread) throws InterruptedException {
+ dispositionInProgressLock.readLock().lock();
+ super.process(curi, thread);
+ dispositionInProgressLock.readLock().unlock();
+ }
+
+
}
diff --git a/modules/src/main/java/org/archive/modules/Processor.java b/modules/src/main/java/org/archive/modules/Processor.java
index 0325c45e7..acd5bf41f 100644
--- a/modules/src/main/java/org/archive/modules/Processor.java
+++ b/modules/src/main/java/org/archive/modules/Processor.java
@@ -19,11 +19,14 @@
package org.archive.modules;
+import java.io.IOException;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.httpclient.HttpStatus;
+import org.archive.checkpointing.Checkpointable;
+import org.archive.crawler.framework.Checkpoint;
import org.archive.modules.credential.CredentialAvatar;
import org.archive.modules.credential.HttpAuthenticationCredential;
import org.archive.modules.deciderules.AcceptDecideRule;
@@ -32,6 +35,10 @@
import org.archive.net.UURI;
import org.archive.spring.HasKeyedProperties;
import org.archive.spring.KeyedProperties;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.springframework.beans.factory.BeanNameAware;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.Lifecycle;
@@ -42,18 +49,22 @@
* @author pjack
*/
public abstract class Processor
-implements Serializable, HasKeyedProperties, Lifecycle {
+implements Serializable,
+ HasKeyedProperties,
+ Lifecycle,
+ BeanNameAware,
+ Checkpointable {
protected KeyedProperties kp = new KeyedProperties();
public KeyedProperties getKeyedProperties() {
return kp;
}
- String name = this.getClass().getSimpleName();
- public String getName() {
- return this.name;
+ String beanName;
+ public String getBeanName() {
+ return this.beanName;
}
- public void setName(String name) {
- this.name = name;
+ public void setBeanName(String name) {
+ this.beanName = name;
}
/**
@@ -91,7 +102,7 @@ public void setShouldProcessRule(DecideRule rule) {
/**
* The number of URIs processed by this processor.
*/
- private AtomicLong uriCount = new AtomicLong(0);
+ protected AtomicLong uriCount = new AtomicLong(0);
/**
@@ -233,7 +244,6 @@ public static boolean hasHttpAuthenticationCredentialAvatar(CrawlURI puri) {
return false;
}
-
// FIXME: Raise to interface
// FIXME: Internationalize somehow
// FIXME: Pass in PrintWriter instead creating large in-memory strings
@@ -247,10 +257,66 @@ public boolean isRunning() {
}
public void start() {
+ if(isRunning) {
+ return;
+ }
isRunning = true;
+ if(recoveryCheckpoint!=null) {
+ try {
+ JSONObject json = recoveryCheckpoint.loadJson(getBeanName());
+ fromCheckpointJson(json);
+ } catch (JSONException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
+
public void stop() {
isRunning = false;
}
+
+ public void startCheckpoint(Checkpoint checkpointInProgress) {}
+
+ public void doCheckpoint(Checkpoint checkpointInProgress)
+ throws IOException {
+ try {
+ JSONObject json = toCheckpointJson();
+ checkpointInProgress.saveJson(beanName, json);
+ } catch(JSONException j) {
+ // impossible
+ }
+ }
+
+ /**
+ * Return a JSONObject of current stat that can be consulted
+ * on recovery to restore necessary values.
+ *
+ * @return JSONObject
+ * @throws JSONException
+ */
+ protected JSONObject toCheckpointJson() throws JSONException {
+ JSONObject json = new JSONObject();
+ json.put("uriCount", getURICount());
+ return json;
+ }
+
+ /**
+ * Restore internal state from JSONObject stored at earlier
+ * checkpoint-time.
+ *
+ * @param json JSONObject
+ * @throws JSONException
+ */
+ protected void fromCheckpointJson(JSONObject json) throws JSONException {
+ uriCount.set(json.getLong("uriCount"));
+ }
+
+ public void finishCheckpoint(Checkpoint checkpointInProgress) {}
+
+ protected Checkpoint recoveryCheckpoint;
+ @Autowired(required=false)
+ public void setRecoveryCheckpoint(Checkpoint checkpoint) {
+ this.recoveryCheckpoint = checkpoint;
+ }
}
diff --git a/modules/src/main/java/org/archive/modules/ProcessorChain.java b/modules/src/main/java/org/archive/modules/ProcessorChain.java
index b56f2048c..13839e558 100644
--- a/modules/src/main/java/org/archive/modules/ProcessorChain.java
+++ b/modules/src/main/java/org/archive/modules/ProcessorChain.java
@@ -100,7 +100,7 @@ public void singleLineReportTo(PrintWriter pw) {
pw.print(size());
pw.print(" processors: ");
for(Processor p : this) {
- pw.print(p.getName());
+ pw.print(p.getBeanName());
pw.print(" ");
}
}
@@ -110,7 +110,7 @@ public void process(CrawlURI curi, ChainStatusReceiver thread) throws Interrupte
String skipToProc = null;
ploop: for(Processor curProc : this ) {
- if(skipToProc!=null && curProc.getName() != skipToProc) {
+ if(skipToProc!=null && curProc.getBeanName() != skipToProc) {
continue;
} else {
skipToProc = null;
|
72894b26c24b1ea31c6dda4634cfde67e7dc3050
|
spring-framework
|
Fix conversion of Message<?> payload for replies--If a custom MessageConverter is set
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java b/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java
index f910fd430828..cd0516de6d57 100644
--- a/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java
+++ b/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.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.
@@ -396,6 +396,15 @@ private class MessagingMessageConverterAdapter extends MessagingMessageConverter
protected Object extractPayload(Message message) throws JMSException {
return extractMessage(message);
}
+
+ @Override
+ protected Message createMessageForPayload(Object payload, Session session) throws JMSException {
+ MessageConverter converter = getMessageConverter();
+ if (converter != null) {
+ return converter.toMessage(payload, session);
+ }
+ throw new IllegalStateException("No message converter, cannot handle '" + payload + "'");
+ }
}
diff --git a/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java b/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java
index aefa45877e47..a4db74313e9c 100644
--- a/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java
+++ b/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.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.
@@ -93,7 +93,7 @@ public javax.jms.Message toMessage(Object object, Session session) throws JMSExc
Message.class.getName() + "] is handled by this converter");
}
Message<?> input = (Message<?>) object;
- javax.jms.Message reply = this.payloadConverter.toMessage(input.getPayload(), session);
+ javax.jms.Message reply = createMessageForPayload(input.getPayload(), session);
this.headerMapper.fromHeaders(input.getHeaders(), reply);
return reply;
}
@@ -119,4 +119,12 @@ protected Object extractPayload(javax.jms.Message message) throws JMSException {
return this.payloadConverter.fromMessage(message);
}
+ /**
+ * Create a JMS message for the specified payload.
+ * @see MessageConverter#toMessage(Object, Session)
+ */
+ protected javax.jms.Message createMessageForPayload(Object payload, Session session) throws JMSException {
+ return this.payloadConverter.toMessage(payload, session);
+ }
+
}
diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java
index 5fc400e8bb0d..f5f38d787d33 100644
--- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java
+++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.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.
@@ -17,6 +17,8 @@
package org.springframework.jms.listener.adapter;
import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;
@@ -28,6 +30,7 @@
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.jms.StubTextMessage;
import org.springframework.jms.support.JmsHeaders;
+import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.MessageConversionException;
import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
@@ -111,6 +114,38 @@ public void exceptionInInvocation() {
}
}
+ @Test
+ public void incomingMessageUsesMessageConverter() throws JMSException {
+ javax.jms.Message jmsMessage = mock(javax.jms.Message.class);
+ Session session = mock(Session.class);
+ MessageConverter messageConverter = mock(MessageConverter.class);
+ given(messageConverter.fromMessage(jmsMessage)).willReturn("FooBar");
+ MessagingMessageListenerAdapter listener = getSimpleInstance("simple", Message.class);
+ listener.setMessageConverter(messageConverter);
+ listener.onMessage(jmsMessage, session);
+ verify(messageConverter, times(1)).fromMessage(jmsMessage);
+ assertEquals(1, sample.simples.size());
+ assertEquals("FooBar", sample.simples.get(0).getPayload());
+ }
+
+ @Test
+ public void replyUsesMessageConverterForPayload() throws JMSException {
+ Session session = mock(Session.class);
+ MessageConverter messageConverter = mock(MessageConverter.class);
+ given(messageConverter.toMessage("Response", session)).willReturn(new StubTextMessage("Response"));
+
+ Message<String> result = MessageBuilder.withPayload("Response")
+ .build();
+
+ MessagingMessageListenerAdapter listener = getSimpleInstance("echo", Message.class);
+ listener.setMessageConverter(messageConverter);
+ javax.jms.Message replyMessage = listener.buildMessage(session, result);
+
+ verify(messageConverter, times(1)).toMessage("Response", session);
+ assertNotNull("reply should never be null", replyMessage);
+ assertEquals("Response", ((TextMessage) replyMessage).getText());
+ }
+
protected MessagingMessageListenerAdapter getSimpleInstance(String methodName, Class... parameterTypes) {
Method m = ReflectionUtils.findMethod(SampleBean.class, methodName, parameterTypes);
return createInstance(m);
@@ -131,6 +166,12 @@ private void initializeFactory(DefaultMessageHandlerMethodFactory factory) {
@SuppressWarnings("unused")
private static class SampleBean {
+ public final List<Message<String>> simples = new ArrayList<>();
+
+ public void simple(Message<String> input) {
+ simples.add(input);
+ }
+
public Message<String> echo(Message<String> input) {
return MessageBuilder.withPayload(input.getPayload())
.setHeader(JmsHeaders.TYPE, "reply")
|
f95ec3f5bf12bee07c90943cff3b135e6a7e7a8b
|
hadoop
|
HADOOP-6133. Add a caching layer to- Configuration::getClassByName to alleviate a performance regression- introduced in a compatibility layer. Contributed by Todd Lipcon--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@812285 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index b3e5b2e07573c..a32e6c7905614 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -512,7 +512,8 @@ Trunk (unreleased changes)
HADOOP-6176. Add a couple package private methods to AccessTokenHandler
for testing. (Kan Zhang via szetszwo)
- HADOOP-6182. Fix ReleaseAudit warnings (Giridharan Kesavan and Lee Tucker via gkesavan)
+ HADOOP-6182. Fix ReleaseAudit warnings (Giridharan Kesavan and Lee Tucker
+ via gkesavan)
HADOOP-6173. Change src/native/packageNativeHadoop.sh to package all
native library files. (Hong Tang via szetszwo)
@@ -526,6 +527,10 @@ Trunk (unreleased changes)
HADOOP-6231. Allow caching of filesystem instances to be disabled on a
per-instance basis. (tomwhite)
+ HADOOP-6133. Add a caching layer to Configuration::getClassByName to
+ alleviate a performance regression introduced in a compatibility layer.
+ (Todd Lipcon via cdouglas)
+
OPTIMIZATIONS
HADOOP-5595. NameNode does not need to run a replicator to choose a
diff --git a/src/java/org/apache/hadoop/conf/Configuration.java b/src/java/org/apache/hadoop/conf/Configuration.java
index cfb1ba8d70a54..8bf4c1c436eb2 100644
--- a/src/java/org/apache/hadoop/conf/Configuration.java
+++ b/src/java/org/apache/hadoop/conf/Configuration.java
@@ -170,6 +170,9 @@ public class Configuration implements Iterable<Map.Entry<String,String>>,
*/
private static final ArrayList<String> defaultResources =
new ArrayList<String>();
+
+ private static final Map<ClassLoader, Map<String, Class<?>>>
+ CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, Class<?>>>();
/**
* Flag to indicate if the storage of resource which updates a key needs
@@ -1029,7 +1032,27 @@ public void setStrings(String name, String... values) {
* @throws ClassNotFoundException if the class is not found.
*/
public Class<?> getClassByName(String name) throws ClassNotFoundException {
- return Class.forName(name, true, classLoader);
+ Map<String, Class<?>> map;
+
+ synchronized (CACHE_CLASSES) {
+ map = CACHE_CLASSES.get(classLoader);
+ if (map == null) {
+ map = Collections.synchronizedMap(
+ new WeakHashMap<String, Class<?>>());
+ CACHE_CLASSES.put(classLoader, map);
+ }
+ }
+
+ Class clazz = map.get(name);
+ if (clazz == null) {
+ clazz = Class.forName(name, true, classLoader);
+ if (clazz != null) {
+ // two putters can race here, but they'll put the same class
+ map.put(name, clazz);
+ }
+ }
+
+ return clazz;
}
/**
|
59b8a139d72463fbf324e851a9e6daf918fe1b22
|
spring-framework
|
JndiObjectFactoryBean explicitly only chooses- public interfaces as default proxy interfaces (SPR-5869)--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java
index 9914e0dbdae3..504a96ad8c64 100644
--- a/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java
+++ b/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.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.
@@ -17,7 +17,7 @@
package org.springframework.jndi;
import java.lang.reflect.Method;
-
+import java.lang.reflect.Modifier;
import javax.naming.Context;
import javax.naming.NamingException;
@@ -295,7 +295,12 @@ private static Object createJndiObjectProxy(JndiObjectFactoryBean jof) throws Na
throw new IllegalStateException(
"Cannot deactivate 'lookupOnStartup' without specifying a 'proxyInterface' or 'expectedType'");
}
- proxyFactory.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader));
+ Class[] ifcs = ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader);
+ for (Class ifc : ifcs) {
+ if (Modifier.isPublic(ifc.getModifiers())) {
+ proxyFactory.addInterface(ifc);
+ }
+ }
}
if (jof.exposeAccessContext) {
proxyFactory.addAdvice(new JndiContextExposingInterceptor(jof.getJndiTemplate()));
|
2ca1f557dc3220a047c5ee6a1d8c1a0584f6ca4e
|
orientdb
|
Fix by Luca Molino to close issue 619--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java b/commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java
index 59339861f7e..1701bf54d79 100644
--- a/commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java
+++ b/commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java
@@ -70,7 +70,7 @@ public TTYConsoleReader() {
}
if (System.getProperty("file.encoding") != null) {
inStream = new InputStreamReader(System.in, System.getProperty("file.encoding"));
- outStream = new PrintStream(System.out, true, System.getProperty("file.encoding"));
+ outStream = new PrintStream(System.out, false, System.getProperty("file.encoding"));
} else {
inStream = new InputStreamReader(System.in);
outStream = System.out;
@@ -93,7 +93,6 @@ public String readLine() {
int historyNum = history.size();
boolean hintedHistory = false;
while (true) {
-
boolean escape = false;
boolean ctrl = false;
int next = inStream.read();
@@ -260,7 +259,7 @@ public String readLine() {
rewriteConsole(buffer, false);
currentPos = buffer.length();
} else {
- if (next > UNIT_SEPARATOR_CHAR && next < BACKSPACE_CHAR) {
+ if ((next > UNIT_SEPARATOR_CHAR && next < BACKSPACE_CHAR) || next > BACKSPACE_CHAR) {
StringBuffer cleaner = new StringBuffer();
for (int i = 0; i < buffer.length(); i++) {
cleaner.append(" ");
|
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
|
c2d25218b429e6041c3652025788701e795db22e
|
Delta Spike
|
DELTASPIKE-312 remove GlobalAlternatives handling for OWB and fix tests
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java
index e76a257f8..f0a7959b4 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java
@@ -59,7 +59,7 @@ public class ExcludeExtension implements Extension, Deactivatable
{
private static final Logger LOG = Logger.getLogger(ExcludeExtension.class.getName());
- private static Boolean isOwbDetected = false;
+ private static Boolean isWeldDetected = false;
private boolean isActivated = true;
private boolean isGlobalAlternativeActivated = true;
@@ -77,7 +77,7 @@ protected void init(@Observes BeforeBeanDiscovery beforeBeanDiscovery)
isCustomProjectStageBeanFilterActivated =
ClassDeactivationUtils.isActivated(CustomProjectStageBeanFilter.class);
- isOwbDetected = isOpenWebBeans();
+ isWeldDetected = isWeld();
}
/**
@@ -100,11 +100,7 @@ protected void vetoBeans(@Observes ProcessAnnotatedType processAnnotatedType, Be
//we need to do it before the exclude logic to keep the @Exclude support for global alternatives
if (isGlobalAlternativeActivated)
{
- if (isOwbDetected)
- {
- activateGlobalAlternativesOwb(processAnnotatedType, beanManager);
- }
- else
+ if (isWeldDetected)
{
activateGlobalAlternativesWeld(processAnnotatedType, beanManager);
}
@@ -239,84 +235,6 @@ private void activateGlobalAlternativesWeld(ProcessAnnotatedType processAnnotate
}
}
- //see OWB-643
- //just #veto the original implementation and remove @Alternative from the ProcessAnnotatedType of
- // the configured alternative doesn't work with OWB (due to OWB-643)
- private void activateGlobalAlternativesOwb(ProcessAnnotatedType processAnnotatedType,
- BeanManager beanManager)
- {
- //the current bean is the bean with a potential global alternative
- Class<Object> currentBean = processAnnotatedType.getAnnotatedType().getJavaClass();
-
- if (currentBean.isInterface())
- {
- return;
- }
-
- Set<Class> beanBaseTypes = resolveBeanTypes(currentBean);
-
- boolean isAlternativeBeanImplementation = currentBean.isAnnotationPresent(Alternative.class);
-
- List<Annotation> qualifiersOfCurrentBean =
- resolveQualifiers(processAnnotatedType.getAnnotatedType().getAnnotations(), beanManager);
-
- String configuredBeanName;
- List<Annotation> qualifiersOfConfiguredBean;
- Class<Object> alternativeBeanClass;
- Set<Annotation> alternativeBeanAnnotations;
-
- for (Class currentType : beanBaseTypes)
- {
- alternativeBeanAnnotations = new HashSet<Annotation>();
-
- configuredBeanName = ConfigResolver.getPropertyValue(currentType.getName());
- if (configuredBeanName != null && configuredBeanName.length() > 0)
- {
- alternativeBeanClass = ClassUtils.tryToLoadClassForName(configuredBeanName);
-
- if (alternativeBeanClass == null)
- {
- throw new IllegalStateException("Can't find class " + configuredBeanName + " which is configured" +
- " for " + currentType.getName());
- }
- alternativeBeanAnnotations.addAll(Arrays.asList(alternativeBeanClass.getAnnotations()));
- qualifiersOfConfiguredBean = resolveQualifiers(alternativeBeanAnnotations, beanManager);
- }
- else
- {
- continue;
- }
-
- //current bean is annotated with @Alternative and of the same type as the configured bean
- if (isAlternativeBeanImplementation && alternativeBeanClass.equals(currentBean))
- {
- if (doQualifiersMatch(qualifiersOfCurrentBean, qualifiersOfConfiguredBean))
- {
- //veto if the current annotated-type is a global alternative - it replaced the original type already
- processAnnotatedType.veto();
- break;
- }
- }
- else
- {
- if (!alternativeBeanClass.isAnnotationPresent(Alternative.class))
- {
- continue;
- }
-
- if (doQualifiersMatch(qualifiersOfCurrentBean, qualifiersOfConfiguredBean))
- {
- AnnotatedTypeBuilder<Object> annotatedTypeBuilder
- = new AnnotatedTypeBuilder<Object>().readFromType(alternativeBeanClass);
-
- //just to avoid issues with switching between app-servers,...
- annotatedTypeBuilder.removeFromClass(Alternative.class);
- processAnnotatedType.setAnnotatedType(annotatedTypeBuilder.create());
- }
- }
- }
- }
-
private boolean doQualifiersMatch(List<Annotation> qualifiersOfCurrentBean,
List<Annotation> qualifiersOfConfiguredBean)
{
@@ -524,13 +442,13 @@ private void veto(ProcessAnnotatedType processAnnotatedType, String vetoType)
processAnnotatedType.getAnnotatedType().getJavaClass());
}
- private boolean isOpenWebBeans()
+ private boolean isWeld()
{
IllegalStateException runtimeException = new IllegalStateException();
for (StackTraceElement element : runtimeException.getStackTrace())
{
- if (element.toString().contains("org.apache.webbeans."))
+ if (element.toString().contains("org.jboss.weld"))
{
return true;
}
diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java
index 287fae222..60ca097f9 100644
--- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java
+++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java
@@ -31,7 +31,9 @@
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
@@ -40,7 +42,6 @@
import org.junit.runner.RunWith;
import javax.inject.Inject;
-import java.util.List;
/**
* Tests for @Alternative across BDAs
@@ -67,6 +68,14 @@ public class GlobalAlternativeTest
@Deployment
public static WebArchive deploy()
{
+ Asset beansXml = new StringAsset(
+ "<beans><alternatives>" +
+ "<class>" + BaseInterface1AlternativeImplementation.class.getName() + "</class>" +
+ "<class>" + SubBaseBean2.class.getName() + "</class>" +
+ "<class>" + AlternativeBaseBeanB.class.getName() + "</class>" +
+ "</alternatives></beans>"
+ );
+
JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, "excludeIntegrationTest.jar")
.addPackage(GlobalAlternativeTest.class.getPackage())
.addPackage(QualifierA.class.getPackage())
@@ -75,7 +84,7 @@ public static WebArchive deploy()
return ShrinkWrap.create(WebArchive.class, "globalAlternative.war")
.addAsLibraries(ArchiveUtils.getDeltaSpikeCoreArchive(new String[]{"META-INF.config"}))
.addAsLibraries(testJar)
- .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
+ .addAsWebInfResource(beansXml, "beans.xml");
}
/**
@@ -84,10 +93,9 @@ public static WebArchive deploy()
@Test
public void alternativeImplementationWithClassAsBaseType()
{
- List<BaseBean1> testBeans = BeanProvider.getContextualReferences(BaseBean1.class, true);
+ BaseBean1 testBean = BeanProvider.getContextualReference(BaseBean1.class);
- Assert.assertEquals(1, testBeans.size());
- Assert.assertEquals(SubBaseBean2.class.getName(), testBeans.get(0).getClass().getName());
+ Assert.assertEquals(SubBaseBean2.class.getName(), testBean.getClass().getName());
}
/**
diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean1.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean1.java
index b6c904808..4156b2521 100644
--- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean1.java
+++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean1.java
@@ -21,8 +21,6 @@
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Alternative;
-/**
- */
@Alternative
@Dependent
public class SubBaseBean1 extends BaseBean1
diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean2.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean2.java
index 7d5ca9999..05e1c1aba 100644
--- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean2.java
+++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean2.java
@@ -21,8 +21,6 @@
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Alternative;
-/**
- */
@Alternative
@Dependent
public class SubBaseBean2 extends SubBaseBean1
|
85ec6bc6d7cd0904757b596627fd3666de7738dd
|
camel
|
added fix for- https://issues.apache.org/activemq/browse/CAMEL-347 to enable JUEL to invoke- methods in expressions--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@631503 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/camel
|
diff --git a/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java b/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java
new file mode 100644
index 0000000000000..2412b27fa96a3
--- /dev/null
+++ b/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java
@@ -0,0 +1,84 @@
+/**
+ *
+ * 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.language.juel;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.el.BeanELResolver;
+import javax.el.ELContext;
+import javax.el.PropertyNotFoundException;
+
+/**
+ * An extension of the JUEL {@link BeanELResolver} which also supports the resolving of methods
+ *
+ * @version $Revision: 1.1 $
+ */
+public class BeanAndMethodELResolver extends BeanELResolver {
+ public BeanAndMethodELResolver() {
+ super(false);
+ }
+
+ @Override
+ public Object getValue(ELContext elContext, Object base, Object property) {
+ try {
+ return super.getValue(elContext, base, property);
+ }
+ catch (PropertyNotFoundException e) {
+ // lets see if its a method call...
+ Method method = findMethod(elContext, base, property);
+ if (method != null) {
+ elContext.setPropertyResolved(true);
+ return method;
+ }
+ else {
+ throw e;
+ }
+ }
+ }
+
+ protected Method findMethod(ELContext elContext, Object base, Object property) {
+ if (base != null && property instanceof String) {
+ Method[] methods = base.getClass().getMethods();
+ List<Method> matching = new ArrayList<Method>();
+ for (Method method : methods) {
+ if (method.getName().equals(property) && Modifier.isPublic(method.getModifiers())) {
+ matching.add(method);
+ }
+ }
+ int size = matching.size();
+ if (size > 0) {
+ if (size > 1) {
+ // TODO there's currently no way for JUEL to tell us how many parameters there are
+ // so lets just pick the first one that has a single param by default
+ for (Method method : matching) {
+ Class<?>[] paramTypes = method.getParameterTypes();
+ if (paramTypes.length == 1) {
+ return method;
+ }
+ }
+ }
+ // lets default to the first one
+ return matching.get(0);
+ }
+ }
+ return null;
+ }
+}
diff --git a/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java b/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java
index dbeb68dc43ba8..a2d5e80e14c4f 100644
--- a/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java
+++ b/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java
@@ -16,12 +16,11 @@
*/
package org.apache.camel.language.juel;
-import javax.el.ELContext;
-import javax.el.ExpressionFactory;
-import javax.el.ValueExpression;
+import java.util.Properties;
-import de.odysseus.el.util.SimpleContext;
+import javax.el.*;
+import de.odysseus.el.util.SimpleContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.impl.ExpressionSupport;
@@ -29,14 +28,14 @@
/**
* The <a href="http://activemq.apache.org/camel/el.html">EL Language from JSP and JSF</a>
* using the <a href="http://activemq.apache.org/camel/juel.html">JUEL library</a>
- *
+ *
* @version $Revision$
*/
public class JuelExpression extends ExpressionSupport<Exchange> {
-
private final String expression;
private final Class<?> type;
private ExpressionFactory expressionFactory;
+ private Properties expressionFactoryProperties;
public JuelExpression(String expression, Class<?> type) {
this.expression = expression;
@@ -57,7 +56,8 @@ public Object evaluate(Exchange exchange) {
public ExpressionFactory getExpressionFactory() {
if (expressionFactory == null) {
- expressionFactory = ExpressionFactory.newInstance();
+ Properties properties = getExpressionFactoryProperties();
+ expressionFactory = ExpressionFactory.newInstance(properties);
}
return expressionFactory;
}
@@ -66,6 +66,18 @@ public void setExpressionFactory(ExpressionFactory expressionFactory) {
this.expressionFactory = expressionFactory;
}
+ public Properties getExpressionFactoryProperties() {
+ if (expressionFactoryProperties == null) {
+ expressionFactoryProperties = new Properties();
+ populateDefaultExpressionProperties(expressionFactoryProperties);
+ }
+ return expressionFactoryProperties;
+ }
+
+ public void setExpressionFactoryProperties(Properties expressionFactoryProperties) {
+ this.expressionFactoryProperties = expressionFactoryProperties;
+ }
+
protected ELContext populateContext(ELContext context, Exchange exchange) {
setVariable(context, "exchange", exchange, Exchange.class);
setVariable(context, "in", exchange.getIn(), Message.class);
@@ -74,6 +86,14 @@ protected ELContext populateContext(ELContext context, Exchange exchange) {
return context;
}
+ /**
+ * A Strategy Method to populate the default properties used to create the expression factory
+ */
+ protected void populateDefaultExpressionProperties(Properties properties) {
+ // lets enable method invocations
+ properties.setProperty("javax.el.methodInvocations", "true");
+ }
+
protected void setVariable(ELContext context, String name, Object value, Class<?> type) {
ValueExpression valueExpression = getExpressionFactory().createValueExpression(value, type);
SimpleContext simpleContext = (SimpleContext) context;
@@ -84,7 +104,17 @@ protected void setVariable(ELContext context, String name, Object value, Class<?
* Factory method to create the EL context
*/
protected ELContext createContext() {
- return new SimpleContext();
+ ELResolver resolver = new CompositeELResolver() {
+ {
+ //add(methodResolver);
+ add(new ArrayELResolver(false));
+ add(new ListELResolver(false));
+ add(new MapELResolver(false));
+ add(new ResourceBundleELResolver());
+ add(new BeanAndMethodELResolver());
+ }
+ };
+ return new SimpleContext(resolver);
}
protected String assertionFailureMessage(Exchange exchange) {
diff --git a/components/camel-juel/src/test/java/org/apache/camel/language/juel/JuelLanguageTest.java b/components/camel-juel/src/test/java/org/apache/camel/language/juel/JuelLanguageTest.java
index e7e5734aed8e2..dba142ceb009c 100644
--- a/components/camel-juel/src/test/java/org/apache/camel/language/juel/JuelLanguageTest.java
+++ b/components/camel-juel/src/test/java/org/apache/camel/language/juel/JuelLanguageTest.java
@@ -28,6 +28,10 @@ public void testElExpressions() throws Exception {
assertExpression("${in.body}", "<hello id='m123'>world!</hello>");
}
+ public void testElPredicates() throws Exception {
+ assertPredicate("${in.headers.foo.startsWith('a')}");
+ }
+
protected String getLanguageName() {
return "el";
}
|
100f571c9a2835d5a30a55374b9be74c147e031f
|
ReactiveX-RxJava
|
forEach with Action1 but not Observer--I re-read the MSDN docs and found the previous implementation wasn't complying with the contract.--http://msdn.microsoft.com/en-us/library/hh211815(v=vs.103).aspx--I believe this now does.-
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy b/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy
index 7f62af5724..967c096691 100644
--- a/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy
+++ b/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy
@@ -22,6 +22,7 @@ import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
+import static org.junit.Assert.*;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -222,33 +223,17 @@ def class ObservableTests {
verify(a, times(1)).received(3);
}
- @Test
- public void testForEachWithComplete() {
- Observable.create(new AsyncObservable()).forEach({ result -> a.received(result)}, {}, {a.received('done')});
- verify(a, times(1)).received(1);
- verify(a, times(1)).received(2);
- verify(a, times(1)).received(3);
- verify(a, times(1)).received("done");
- }
-
@Test
public void testForEachWithError() {
- Observable.create(new AsyncObservable()).forEach({ result -> throw new RuntimeException('err')}, {err -> a.received(err.message)});
- verify(a, times(0)).received(1);
- verify(a, times(0)).received(2);
- verify(a, times(0)).received(3);
- verify(a, times(1)).received("err");
- verify(a, times(0)).received("done");
- }
-
- @Test
- public void testForEachWithCompleteAndError() {
- Observable.create(new AsyncObservable()).forEach({ result -> throw new RuntimeException('err')}, {err -> a.received(err.message)}, {a.received('done')},);
+ try {
+ Observable.create(new AsyncObservable()).forEach({ result -> throw new RuntimeException('err')});
+ fail("we expect an exception to be thrown");
+ }catch(Exception e) {
+
+ }
verify(a, times(0)).received(1);
verify(a, times(0)).received(2);
verify(a, times(0)).received(3);
- verify(a, times(1)).received("err");
- verify(a, times(0)).received("done");
}
def class AsyncObservable implements Func1<Observer<Integer>, Subscription> {
diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java
index 86e85be0f5..ba9cc6827b 100644
--- a/rxjava-core/src/main/java/rx/Observable.java
+++ b/rxjava-core/src/main/java/rx/Observable.java
@@ -26,6 +26,7 @@
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.Test;
@@ -334,33 +335,39 @@ public void onNext(T args) {
}
/**
- * Blocking version of {@link #subscribe(Observer)}.
+ * Invokes an action for each element in the observable sequence, and blocks until the sequence is terminated.
* <p>
* NOTE: This will block even if the Observable is asynchronous.
+ * <p>
+ * This is similar to {@link #subscribe(Observer)} but blocks. Because it blocks it does not need the {@link Observer#onCompleted()} or {@link Observer#onError(Exception)} methods.
*
- * @param observer
+ * @param onNext
+ * {@link Action1}
+ * @throws RuntimeException
+ * if error occurs
*/
- public void forEach(final Observer<T> observer) {
+ public void forEach(final Action1<T> onNext) {
final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicReference<Exception> exceptionFromOnError = new AtomicReference<Exception>();
+
subscribe(new Observer<T>() {
public void onCompleted() {
- try {
- observer.onCompleted();
- } finally {
- latch.countDown();
- }
+ latch.countDown();
}
public void onError(Exception e) {
- try {
- observer.onError(e);
- } finally {
- latch.countDown();
- }
+ /*
+ * If we receive an onError event we set the reference on the outer thread
+ * so we can git it and throw after the latch.await().
+ *
+ * We do this instead of throwing directly since this may be on a different thread and the latch is still waiting.
+ */
+ exceptionFromOnError.set(e);
+ latch.countDown();
}
public void onNext(T args) {
- observer.onNext(args);
+ onNext.call(args);
}
});
// block until the subscription completes and then return
@@ -369,46 +376,21 @@ public void onNext(T args) {
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for subscription to complete.", e);
}
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public void forEach(final Map<String, Object> callbacks) {
- // lookup and memoize onNext
- Object _onNext = callbacks.get("onNext");
- if (_onNext == null) {
- throw new RuntimeException("onNext must be implemented");
- }
- final FuncN onNext = Functions.from(_onNext);
-
- forEach(new Observer() {
-
- public void onCompleted() {
- Object onComplete = callbacks.get("onCompleted");
- if (onComplete != null) {
- Functions.from(onComplete).call();
- }
- }
-
- public void onError(Exception e) {
- handleError(e);
- Object onError = callbacks.get("onError");
- if (onError != null) {
- Functions.from(onError).call(e);
- }
- }
- public void onNext(Object args) {
- onNext.call(args);
+ if (exceptionFromOnError.get() != null) {
+ if (exceptionFromOnError.get() instanceof RuntimeException) {
+ throw (RuntimeException) exceptionFromOnError.get();
+ } else {
+ throw new RuntimeException(exceptionFromOnError.get());
}
-
- });
+ }
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void forEach(final Object o) {
- if (o instanceof Observer) {
- // in case a dynamic language is not correctly handling the overloaded methods and we receive an Observer just forward to the correct method.
- forEach((Observer) o);
+ if (o instanceof Action1) {
+ // in case a dynamic language is not correctly handling the overloaded methods and we receive an Action1 just forward to the correct method.
+ forEach((Action1) o);
}
// lookup and memoize onNext
@@ -417,156 +399,15 @@ public void forEach(final Object o) {
}
final FuncN onNext = Functions.from(o);
- forEach(new Observer() {
-
- public void onCompleted() {
- // do nothing
- }
-
- public void onError(Exception e) {
- handleError(e);
- // no callback defined
- }
-
- public void onNext(Object args) {
- onNext.call(args);
- }
-
- });
- }
-
- public void forEach(final Action1<T> onNext) {
-
- forEach(new Observer<T>() {
-
- public void onCompleted() {
- // do nothing
- }
-
- public void onError(Exception e) {
- handleError(e);
- // no callback defined
- }
-
- public void onNext(T args) {
- if (onNext == null) {
- throw new RuntimeException("onNext must be implemented");
- }
- onNext.call(args);
- }
-
- });
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public void forEach(final Object onNext, final Object onError) {
- // lookup and memoize onNext
- if (onNext == null) {
- throw new RuntimeException("onNext must be implemented");
- }
- final FuncN onNextFunction = Functions.from(onNext);
-
- forEach(new Observer() {
+ forEach(new Action1() {
- public void onCompleted() {
- // do nothing
- }
-
- public void onError(Exception e) {
- handleError(e);
- if (onError != null) {
- Functions.from(onError).call(e);
- }
- }
-
- public void onNext(Object args) {
- onNextFunction.call(args);
- }
-
- });
- }
-
- public void forEach(final Action1<T> onNext, final Action1<Exception> onError) {
-
- forEach(new Observer<T>() {
-
- public void onCompleted() {
- // do nothing
- }
-
- public void onError(Exception e) {
- handleError(e);
- if (onError != null) {
- onError.call(e);
- }
- }
-
- public void onNext(T args) {
- if (onNext == null) {
- throw new RuntimeException("onNext must be implemented");
- }
+ public void call(Object args) {
onNext.call(args);
}
});
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public void forEach(final Object onNext, final Object onError, final Object onComplete) {
- // lookup and memoize onNext
- if (onNext == null) {
- throw new RuntimeException("onNext must be implemented");
- }
- final FuncN onNextFunction = Functions.from(onNext);
-
- forEach(new Observer() {
-
- public void onCompleted() {
- if (onComplete != null) {
- Functions.from(onComplete).call();
- }
- }
-
- public void onError(Exception e) {
- handleError(e);
- if (onError != null) {
- Functions.from(onError).call(e);
- }
- }
-
- public void onNext(Object args) {
- onNextFunction.call(args);
- }
-
- });
- }
-
- public void forEach(final Action1<T> onNext, final Action1<Exception> onError, final Action0 onComplete) {
-
- forEach(new Observer<T>() {
-
- public void onCompleted() {
- onComplete.call();
- }
-
- public void onError(Exception e) {
- handleError(e);
- if (onError != null) {
- onError.call(e);
- }
- }
-
- public void onNext(T args) {
- if (onNext == null) {
- throw new RuntimeException("onNext must be implemented");
- }
- onNext.call(args);
- }
-
- });
- }
-
-
/**
* Allow the {@link RxJavaErrorHandler} to receive the exception from onError.
*
|
f7de5d7fc5ac956afa63b91a62173dddcea902ea
|
Mylyn Reviews
|
Removed CDO dependency
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/org.eclipse.mylyn.reviews.core/META-INF/CDO.MF b/org.eclipse.mylyn.reviews.core/META-INF/CDO.MF
deleted file mode 100644
index bbfa1b05..00000000
--- a/org.eclipse.mylyn.reviews.core/META-INF/CDO.MF
+++ /dev/null
@@ -1 +0,0 @@
-This is a marker file for bundles with CDO native models.
diff --git a/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF b/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
index 66bc7522..2782c9a4 100644
--- a/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
+++ b/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
@@ -6,7 +6,6 @@ Bundle-Version: 0.0.1
Bundle-Activator: org.eclipse.mylyn.reviews.core.Activator
Require-Bundle: org.eclipse.core.runtime,
org.eclipse.emf.edit;bundle-version="2.5.0",
- org.eclipse.emf.cdo;bundle-version="2.0.0",
org.eclipse.team.core;bundle-version="3.5.0",
org.eclipse.core.resources;bundle-version="3.5.1",
org.eclipse.mylyn.tasks.core;bundle-version="3.3.0",
diff --git a/org.eclipse.mylyn.reviews.core/model/review.genmodel b/org.eclipse.mylyn.reviews.core/model/review.genmodel
index 440f4c37..c3b7f79e 100644
--- a/org.eclipse.mylyn.reviews.core/model/review.genmodel
+++ b/org.eclipse.mylyn.reviews.core/model/review.genmodel
@@ -1,14 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<genmodel:GenModel xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore"
- xmlns:genmodel="http://www.eclipse.org/emf/2002/GenModel" copyrightText="Copyright (c) 2010 Vienna University of Technology
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html

Contributors:
 Vienna University of Technology - initial API and implementation"
- modelDirectory="/org.eclipse.mylyn.reviews.core/src" modelPluginID="org.eclipse.mylyn.reviews.core"
- modelName="Review" rootExtendsInterface="org.eclipse.emf.cdo.CDOObject" rootExtendsClass="org.eclipse.emf.internal.cdo.CDOObjectImpl"
- reflectiveDelegation="true" testsDirectory="/org.eclipse.mylyn.reviews.core.tests/src"
- importerID="org.eclipse.emf.importer.cdo" featureDelegation="Reflective" complianceLevel="6.0"
- copyrightFields="false">
+ xmlns:genmodel="http://www.eclipse.org/emf/2002/GenModel" modelDirectory="/org.eclipse.mylyn.reviews.core/src"
+ modelPluginID="org.eclipse.mylyn.reviews.core" modelName="Review" importerID="org.eclipse.emf.importer.ecore"
+ complianceLevel="5.0" copyrightFields="false">
<foreignModel>review.ecore</foreignModel>
- <modelPluginVariables>CDO=org.eclipse.emf.cdo</modelPluginVariables>
<genPackages prefix="Review" basePackage="org.eclipse.mylyn.reviews.core.model"
disposableProviderFactory="true" ecorePackage="review.ecore#/">
<genEnums typeSafeEnumCompatible="false" ecoreEnum="review.ecore#//Rating">
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java
index e6acd268..5d3bf277 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java
@@ -10,9 +10,8 @@
*/
package org.eclipse.mylyn.reviews.core.model.review;
-import org.eclipse.emf.cdo.CDOObject;
-
import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
@@ -29,10 +28,9 @@
*
* @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReview()
* @model
- * @extends CDOObject
* @generated
*/
-public interface Review extends CDOObject {
+public interface Review extends EObject {
/**
* Returns the value of the '<em><b>Result</b></em>' reference.
* <!-- begin-user-doc -->
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java
index ec9d9aa2..59c089de 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java
@@ -10,7 +10,7 @@
*/
package org.eclipse.mylyn.reviews.core.model.review;
-import org.eclipse.emf.cdo.CDOObject;
+import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
@@ -28,10 +28,9 @@
*
* @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult()
* @model
- * @extends CDOObject
* @generated
*/
-public interface ReviewResult extends CDOObject {
+public interface ReviewResult extends EObject {
/**
* Returns the value of the '<em><b>Text</b></em>' attribute.
* <!-- begin-user-doc -->
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java
index 56dfcd3d..252a01a1 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java
@@ -10,7 +10,7 @@
*/
package org.eclipse.mylyn.reviews.core.model.review;
-import org.eclipse.emf.cdo.CDOObject;
+import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
@@ -26,10 +26,9 @@
*
* @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getScopeItem()
* @model
- * @extends CDOObject
* @generated
*/
-public interface ScopeItem extends CDOObject {
+public interface ScopeItem extends EObject {
/**
* Returns the value of the '<em><b>Author</b></em>' attribute.
* <!-- begin-user-doc -->
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java
index 8d541789..15f58c54 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java
@@ -16,12 +16,14 @@
import java.util.Date;
import org.eclipse.compare.patch.IFilePatch2;
+import org.eclipse.emf.common.notify.Notification;
import org.eclipse.compare.patch.PatchParser;
import org.eclipse.compare.patch.ReaderCreator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.mylyn.reviews.core.model.review.Patch;
import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
@@ -31,22 +33,70 @@
* <p>
* The following features are implemented:
* <ul>
- * <li>
- * {@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getContents
- * <em>Contents</em>}</li>
- * <li>
- * {@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getCreationDate
- * <em>Creation Date</em>}</li>
- * <li>
- * {@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getFileName
- * <em>File Name</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getContents <em>Contents</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getCreationDate <em>Creation Date</em>}</li>
+ * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getFileName <em>File Name</em>}</li>
* </ul>
* </p>
*
- * @author Kilian Matt
* @generated
*/
public class PatchImpl extends ScopeItemImpl implements Patch {
+ /**
+ * The default value of the '{@link #getContents() <em>Contents</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getContents()
+ * @generated
+ * @ordered
+ */
+ protected static final String CONTENTS_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getContents() <em>Contents</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getContents()
+ * @generated
+ * @ordered
+ */
+ protected String contents = CONTENTS_EDEFAULT;
+ /**
+ * The default value of the '{@link #getCreationDate() <em>Creation Date</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getCreationDate()
+ * @generated
+ * @ordered
+ */
+ protected static final Date CREATION_DATE_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getCreationDate() <em>Creation Date</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getCreationDate()
+ * @generated
+ * @ordered
+ */
+ protected Date creationDate = CREATION_DATE_EDEFAULT;
+ /**
+ * The default value of the '{@link #getFileName() <em>File Name</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getFileName()
+ * @generated
+ * @ordered
+ */
+ protected static final String FILE_NAME_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getFileName() <em>File Name</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getFileName()
+ * @generated
+ * @ordered
+ */
+ protected String fileName = FILE_NAME_EDEFAULT;
+
/*
* owner* <!-- begin-user-doc --> <!-- end-user-doc -->
*
@@ -58,7 +108,6 @@ protected PatchImpl() {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
- *
* @generated
*/
@Override
@@ -68,56 +117,59 @@ protected EClass eStaticClass() {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
- *
* @generated
*/
public String getContents() {
- return (String) eGet(ReviewPackage.Literals.PATCH__CONTENTS, true);
+ return contents;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
- *
* @generated
*/
public void setContents(String newContents) {
- eSet(ReviewPackage.Literals.PATCH__CONTENTS, newContents);
+ String oldContents = contents;
+ contents = newContents;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__CONTENTS, oldContents, contents));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
- *
* @generated
*/
public Date getCreationDate() {
- return (Date) eGet(ReviewPackage.Literals.PATCH__CREATION_DATE, true);
+ return creationDate;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
- *
* @generated
*/
public void setCreationDate(Date newCreationDate) {
- eSet(ReviewPackage.Literals.PATCH__CREATION_DATE, newCreationDate);
+ Date oldCreationDate = creationDate;
+ creationDate = newCreationDate;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__CREATION_DATE, oldCreationDate, creationDate));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
- *
* @generated
*/
public String getFileName() {
- return (String) eGet(ReviewPackage.Literals.PATCH__FILE_NAME, true);
+ return fileName;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
- *
* @generated
*/
public void setFileName(String newFileName) {
- eSet(ReviewPackage.Literals.PATCH__FILE_NAME, newFileName);
+ String oldFileName = fileName;
+ fileName = newFileName;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__FILE_NAME, oldFileName, fileName));
}
/**
@@ -146,4 +198,102 @@ public Reader createReader() throws CoreException {
}
}
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public Object eGet(int featureID, boolean resolve, boolean coreType) {
+ switch (featureID) {
+ case ReviewPackage.PATCH__CONTENTS:
+ return getContents();
+ case ReviewPackage.PATCH__CREATION_DATE:
+ return getCreationDate();
+ case ReviewPackage.PATCH__FILE_NAME:
+ return getFileName();
+ }
+ return super.eGet(featureID, resolve, coreType);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eSet(int featureID, Object newValue) {
+ switch (featureID) {
+ case ReviewPackage.PATCH__CONTENTS:
+ setContents((String)newValue);
+ return;
+ case ReviewPackage.PATCH__CREATION_DATE:
+ setCreationDate((Date)newValue);
+ return;
+ case ReviewPackage.PATCH__FILE_NAME:
+ setFileName((String)newValue);
+ return;
+ }
+ super.eSet(featureID, newValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eUnset(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.PATCH__CONTENTS:
+ setContents(CONTENTS_EDEFAULT);
+ return;
+ case ReviewPackage.PATCH__CREATION_DATE:
+ setCreationDate(CREATION_DATE_EDEFAULT);
+ return;
+ case ReviewPackage.PATCH__FILE_NAME:
+ setFileName(FILE_NAME_EDEFAULT);
+ return;
+ }
+ super.eUnset(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public boolean eIsSet(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.PATCH__CONTENTS:
+ return CONTENTS_EDEFAULT == null ? contents != null : !CONTENTS_EDEFAULT.equals(contents);
+ case ReviewPackage.PATCH__CREATION_DATE:
+ return CREATION_DATE_EDEFAULT == null ? creationDate != null : !CREATION_DATE_EDEFAULT.equals(creationDate);
+ case ReviewPackage.PATCH__FILE_NAME:
+ return FILE_NAME_EDEFAULT == null ? fileName != null : !FILE_NAME_EDEFAULT.equals(fileName);
+ }
+ return super.eIsSet(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String toString() {
+ if (eIsProxy()) return super.toString();
+
+ StringBuffer result = new StringBuffer(super.toString());
+ result.append(" (contents: ");
+ result.append(contents);
+ result.append(", creationDate: ");
+ result.append(creationDate);
+ result.append(", fileName: ");
+ result.append(fileName);
+ result.append(')');
+ return result.toString();
+ }
+
} // PatchImpl
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java
index 1167ec76..0ef56ca2 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java
@@ -69,10 +69,10 @@ public ReviewFactoryImpl() {
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
- case ReviewPackage.REVIEW: return (EObject)createReview();
- case ReviewPackage.REVIEW_RESULT: return (EObject)createReviewResult();
- case ReviewPackage.PATCH: return (EObject)createPatch();
- case ReviewPackage.SCOPE_ITEM: return (EObject)createScopeItem();
+ case ReviewPackage.REVIEW: return createReview();
+ case ReviewPackage.REVIEW_RESULT: return createReviewResult();
+ case ReviewPackage.PATCH: return createPatch();
+ case ReviewPackage.SCOPE_ITEM: return createScopeItem();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java
index d634e095..4cebc515 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java
@@ -10,11 +10,16 @@
*/
package org.eclipse.mylyn.reviews.core.model.review.impl;
+import java.util.Collection;
+import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.internal.cdo.CDOObjectImpl;
+import org.eclipse.emf.ecore.InternalEObject;
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
+import org.eclipse.emf.ecore.impl.EObjectImpl;
+import org.eclipse.emf.ecore.util.EObjectResolvingEList;
import org.eclipse.mylyn.reviews.core.model.review.Review;
import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
@@ -35,7 +40,26 @@
*
* @generated
*/
-public class ReviewImpl extends CDOObjectImpl implements Review {
+public class ReviewImpl extends EObjectImpl implements Review {
+ /**
+ * The cached value of the '{@link #getResult() <em>Result</em>}' reference.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getResult()
+ * @generated
+ * @ordered
+ */
+ protected ReviewResult result;
+ /**
+ * The cached value of the '{@link #getScope() <em>Scope</em>}' reference list.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getScope()
+ * @generated
+ * @ordered
+ */
+ protected EList<ScopeItem> scope;
+
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
@@ -60,9 +84,16 @@ protected EClass eStaticClass() {
* <!-- end-user-doc -->
* @generated
*/
- @Override
- protected int eStaticFeatureCount() {
- return 0;
+ public ReviewResult getResult() {
+ if (result != null && result.eIsProxy()) {
+ InternalEObject oldResult = (InternalEObject)result;
+ result = (ReviewResult)eResolveProxy(oldResult);
+ if (result != oldResult) {
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReviewPackage.REVIEW__RESULT, oldResult, result));
+ }
+ }
+ return result;
}
/**
@@ -70,8 +101,8 @@ protected int eStaticFeatureCount() {
* <!-- end-user-doc -->
* @generated
*/
- public ReviewResult getResult() {
- return (ReviewResult)eGet(ReviewPackage.Literals.REVIEW__RESULT, true);
+ public ReviewResult basicGetResult() {
+ return result;
}
/**
@@ -80,7 +111,10 @@ public ReviewResult getResult() {
* @generated
*/
public void setResult(ReviewResult newResult) {
- eSet(ReviewPackage.Literals.REVIEW__RESULT, newResult);
+ ReviewResult oldResult = result;
+ result = newResult;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW__RESULT, oldResult, result));
}
/**
@@ -90,7 +124,81 @@ public void setResult(ReviewResult newResult) {
*/
@SuppressWarnings("unchecked")
public EList<ScopeItem> getScope() {
- return (EList<ScopeItem>)eGet(ReviewPackage.Literals.REVIEW__SCOPE, true);
+ if (scope == null) {
+ scope = new EObjectResolvingEList<ScopeItem>(ScopeItem.class, this, ReviewPackage.REVIEW__SCOPE);
+ }
+ return scope;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public Object eGet(int featureID, boolean resolve, boolean coreType) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW__RESULT:
+ if (resolve) return getResult();
+ return basicGetResult();
+ case ReviewPackage.REVIEW__SCOPE:
+ return getScope();
+ }
+ return super.eGet(featureID, resolve, coreType);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @SuppressWarnings("unchecked")
+ @Override
+ public void eSet(int featureID, Object newValue) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW__RESULT:
+ setResult((ReviewResult)newValue);
+ return;
+ case ReviewPackage.REVIEW__SCOPE:
+ getScope().clear();
+ getScope().addAll((Collection<? extends ScopeItem>)newValue);
+ return;
+ }
+ super.eSet(featureID, newValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eUnset(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW__RESULT:
+ setResult((ReviewResult)null);
+ return;
+ case ReviewPackage.REVIEW__SCOPE:
+ getScope().clear();
+ return;
+ }
+ super.eUnset(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public boolean eIsSet(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW__RESULT:
+ return result != null;
+ case ReviewPackage.REVIEW__SCOPE:
+ return scope != null && !scope.isEmpty();
+ }
+ return super.eIsSet(featureID);
}
} //ReviewImpl
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java
index b15c49a5..1619866d 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java
@@ -10,10 +10,10 @@
*/
package org.eclipse.mylyn.reviews.core.model.review.impl;
+import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
-
-import org.eclipse.emf.internal.cdo.CDOObjectImpl;
-
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
+import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.mylyn.reviews.core.model.review.Rating;
import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
@@ -33,24 +33,69 @@
*
* @generated
*/
-public class ReviewResultImpl extends CDOObjectImpl implements ReviewResult {
+public class ReviewResultImpl extends EObjectImpl implements ReviewResult {
/**
+ * The default value of the '{@link #getText() <em>Text</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
+ * @see #getText()
* @generated
+ * @ordered
*/
- protected ReviewResultImpl() {
- super();
- }
+ protected static final String TEXT_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getText() <em>Text</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getText()
+ * @generated
+ * @ordered
+ */
+ protected String text = TEXT_EDEFAULT;
+ /**
+ * The default value of the '{@link #getRating() <em>Rating</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getRating()
+ * @generated
+ * @ordered
+ */
+ protected static final Rating RATING_EDEFAULT = Rating.NONE;
+ /**
+ * The cached value of the '{@link #getRating() <em>Rating</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getRating()
+ * @generated
+ * @ordered
+ */
+ protected Rating rating = RATING_EDEFAULT;
+ /**
+ * The default value of the '{@link #getReviewer() <em>Reviewer</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getReviewer()
+ * @generated
+ * @ordered
+ */
+ protected static final String REVIEWER_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getReviewer() <em>Reviewer</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getReviewer()
+ * @generated
+ * @ordered
+ */
+ protected String reviewer = REVIEWER_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
- @Override
- protected EClass eStaticClass() {
- return ReviewPackage.Literals.REVIEW_RESULT;
+ protected ReviewResultImpl() {
+ super();
}
/**
@@ -59,8 +104,8 @@ protected EClass eStaticClass() {
* @generated
*/
@Override
- protected int eStaticFeatureCount() {
- return 0;
+ protected EClass eStaticClass() {
+ return ReviewPackage.Literals.REVIEW_RESULT;
}
/**
@@ -69,7 +114,7 @@ protected int eStaticFeatureCount() {
* @generated
*/
public String getText() {
- return (String)eGet(ReviewPackage.Literals.REVIEW_RESULT__TEXT, true);
+ return text;
}
/**
@@ -78,7 +123,10 @@ public String getText() {
* @generated
*/
public void setText(String newText) {
- eSet(ReviewPackage.Literals.REVIEW_RESULT__TEXT, newText);
+ String oldText = text;
+ text = newText;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__TEXT, oldText, text));
}
/**
@@ -87,7 +135,7 @@ public void setText(String newText) {
* @generated
*/
public Rating getRating() {
- return (Rating)eGet(ReviewPackage.Literals.REVIEW_RESULT__RATING, true);
+ return rating;
}
/**
@@ -96,7 +144,10 @@ public Rating getRating() {
* @generated
*/
public void setRating(Rating newRating) {
- eSet(ReviewPackage.Literals.REVIEW_RESULT__RATING, newRating);
+ Rating oldRating = rating;
+ rating = newRating == null ? RATING_EDEFAULT : newRating;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__RATING, oldRating, rating));
}
/**
@@ -105,7 +156,7 @@ public void setRating(Rating newRating) {
* @generated
*/
public String getReviewer() {
- return (String)eGet(ReviewPackage.Literals.REVIEW_RESULT__REVIEWER, true);
+ return reviewer;
}
/**
@@ -114,7 +165,108 @@ public String getReviewer() {
* @generated
*/
public void setReviewer(String newReviewer) {
- eSet(ReviewPackage.Literals.REVIEW_RESULT__REVIEWER, newReviewer);
+ String oldReviewer = reviewer;
+ reviewer = newReviewer;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__REVIEWER, oldReviewer, reviewer));
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public Object eGet(int featureID, boolean resolve, boolean coreType) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW_RESULT__TEXT:
+ return getText();
+ case ReviewPackage.REVIEW_RESULT__RATING:
+ return getRating();
+ case ReviewPackage.REVIEW_RESULT__REVIEWER:
+ return getReviewer();
+ }
+ return super.eGet(featureID, resolve, coreType);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eSet(int featureID, Object newValue) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW_RESULT__TEXT:
+ setText((String)newValue);
+ return;
+ case ReviewPackage.REVIEW_RESULT__RATING:
+ setRating((Rating)newValue);
+ return;
+ case ReviewPackage.REVIEW_RESULT__REVIEWER:
+ setReviewer((String)newValue);
+ return;
+ }
+ super.eSet(featureID, newValue);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public void eUnset(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW_RESULT__TEXT:
+ setText(TEXT_EDEFAULT);
+ return;
+ case ReviewPackage.REVIEW_RESULT__RATING:
+ setRating(RATING_EDEFAULT);
+ return;
+ case ReviewPackage.REVIEW_RESULT__REVIEWER:
+ setReviewer(REVIEWER_EDEFAULT);
+ return;
+ }
+ super.eUnset(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public boolean eIsSet(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.REVIEW_RESULT__TEXT:
+ return TEXT_EDEFAULT == null ? text != null : !TEXT_EDEFAULT.equals(text);
+ case ReviewPackage.REVIEW_RESULT__RATING:
+ return rating != RATING_EDEFAULT;
+ case ReviewPackage.REVIEW_RESULT__REVIEWER:
+ return REVIEWER_EDEFAULT == null ? reviewer != null : !REVIEWER_EDEFAULT.equals(reviewer);
+ }
+ return super.eIsSet(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String toString() {
+ if (eIsProxy()) return super.toString();
+
+ StringBuffer result = new StringBuffer(super.toString());
+ result.append(" (text: ");
+ result.append(text);
+ result.append(", rating: ");
+ result.append(rating);
+ result.append(", reviewer: ");
+ result.append(reviewer);
+ result.append(')');
+ return result.toString();
}
} //ReviewResultImpl
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java
index 806b27cf..cad5f6f7 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java
@@ -10,10 +10,10 @@
*/
package org.eclipse.mylyn.reviews.core.model.review.impl;
+import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
-
-import org.eclipse.emf.internal.cdo.CDOObjectImpl;
-
+import org.eclipse.emf.ecore.impl.ENotificationImpl;
+import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
@@ -30,7 +30,26 @@
*
* @generated
*/
-public class ScopeItemImpl extends CDOObjectImpl implements ScopeItem {
+public class ScopeItemImpl extends EObjectImpl implements ScopeItem {
+ /**
+ * The default value of the '{@link #getAuthor() <em>Author</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getAuthor()
+ * @generated
+ * @ordered
+ */
+ protected static final String AUTHOR_EDEFAULT = null;
+ /**
+ * The cached value of the '{@link #getAuthor() <em>Author</em>}' attribute.
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @see #getAuthor()
+ * @generated
+ * @ordered
+ */
+ protected String author = AUTHOR_EDEFAULT;
+
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
@@ -50,14 +69,39 @@ protected EClass eStaticClass() {
return ReviewPackage.Literals.SCOPE_ITEM;
}
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public String getAuthor() {
+ return author;
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ public void setAuthor(String newAuthor) {
+ String oldAuthor = author;
+ author = newAuthor;
+ if (eNotificationRequired())
+ eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.SCOPE_ITEM__AUTHOR, oldAuthor, author));
+ }
+
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
- protected int eStaticFeatureCount() {
- return 0;
+ public Object eGet(int featureID, boolean resolve, boolean coreType) {
+ switch (featureID) {
+ case ReviewPackage.SCOPE_ITEM__AUTHOR:
+ return getAuthor();
+ }
+ return super.eGet(featureID, resolve, coreType);
}
/**
@@ -65,8 +109,14 @@ protected int eStaticFeatureCount() {
* <!-- end-user-doc -->
* @generated
*/
- public String getAuthor() {
- return (String)eGet(ReviewPackage.Literals.SCOPE_ITEM__AUTHOR, true);
+ @Override
+ public void eSet(int featureID, Object newValue) {
+ switch (featureID) {
+ case ReviewPackage.SCOPE_ITEM__AUTHOR:
+ setAuthor((String)newValue);
+ return;
+ }
+ super.eSet(featureID, newValue);
}
/**
@@ -74,8 +124,44 @@ public String getAuthor() {
* <!-- end-user-doc -->
* @generated
*/
- public void setAuthor(String newAuthor) {
- eSet(ReviewPackage.Literals.SCOPE_ITEM__AUTHOR, newAuthor);
+ @Override
+ public void eUnset(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.SCOPE_ITEM__AUTHOR:
+ setAuthor(AUTHOR_EDEFAULT);
+ return;
+ }
+ super.eUnset(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public boolean eIsSet(int featureID) {
+ switch (featureID) {
+ case ReviewPackage.SCOPE_ITEM__AUTHOR:
+ return AUTHOR_EDEFAULT == null ? author != null : !AUTHOR_EDEFAULT.equals(author);
+ }
+ return super.eIsSet(featureID);
+ }
+
+ /**
+ * <!-- begin-user-doc -->
+ * <!-- end-user-doc -->
+ * @generated
+ */
+ @Override
+ public String toString() {
+ if (eIsProxy()) return super.toString();
+
+ StringBuffer result = new StringBuffer(super.toString());
+ result.append(" (author: ");
+ result.append(author);
+ result.append(')');
+ return result.toString();
}
} //ScopeItemImpl
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java
index 2374149a..73e096eb 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java
@@ -14,6 +14,7 @@
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;
+import org.eclipse.mylyn.reviews.core.model.review.*;
import org.eclipse.mylyn.reviews.core.model.review.Patch;
import org.eclipse.mylyn.reviews.core.model.review.Review;
import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
@@ -24,22 +25,21 @@
* <!-- begin-user-doc --> The <b>Adapter Factory</b> for the model. It provides
* an adapter <code>createXXX</code> method for each class of the model. <!--
* end-user-doc -->
- *
* @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage
* @generated
*/
public class ReviewAdapterFactory extends AdapterFactoryImpl {
/**
- * The cached model package. <!-- begin-user-doc --> <!-- end-user-doc -->
- *
+ * The cached model package.
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
protected static ReviewPackage modelPackage;
/**
- * Creates an instance of the adapter factory. <!-- begin-user-doc --> <!--
+ * Creates an instance of the adapter factory.
+ * <!-- begin-user-doc --> <!--
* end-user-doc -->
- *
* @generated
*/
public ReviewAdapterFactory() {
@@ -53,7 +53,6 @@ public ReviewAdapterFactory() {
* <!-- begin-user-doc --> This implementation returns <code>true</code> if
* the object is either the model's package or is an instance object of the
* model. <!-- end-user-doc -->
- *
* @return whether this factory is applicable for the type of the object.
* @generated
*/
@@ -63,7 +62,7 @@ public boolean isFactoryForType(Object object) {
return true;
}
if (object instanceof EObject) {
- return ((EObject) object).eClass().getEPackage() == modelPackage;
+ return ((EObject)object).eClass().getEPackage() == modelPackage;
}
return false;
}
@@ -75,44 +74,39 @@ public boolean isFactoryForType(Object object) {
* @generated
*/
protected ReviewSwitch<Adapter> modelSwitch = new ReviewSwitch<Adapter>() {
- @Override
- public Adapter caseReview(Review object) {
- return createReviewAdapter();
- }
-
- @Override
- public Adapter caseReviewResult(ReviewResult object) {
- return createReviewResultAdapter();
- }
-
- @Override
- public Adapter casePatch(Patch object) {
- return createPatchAdapter();
- }
-
- @Override
- public Adapter caseScopeItem(ScopeItem object) {
- return createScopeItemAdapter();
- }
-
- @Override
- public Adapter defaultCase(EObject object) {
- return createEObjectAdapter();
- }
- };
+ @Override
+ public Adapter caseReview(Review object) {
+ return createReviewAdapter();
+ }
+ @Override
+ public Adapter caseReviewResult(ReviewResult object) {
+ return createReviewResultAdapter();
+ }
+ @Override
+ public Adapter casePatch(Patch object) {
+ return createPatchAdapter();
+ }
+ @Override
+ public Adapter caseScopeItem(ScopeItem object) {
+ return createScopeItemAdapter();
+ }
+ @Override
+ public Adapter defaultCase(EObject object) {
+ return createEObjectAdapter();
+ }
+ };
/**
- * Creates an adapter for the <code>target</code>. <!-- begin-user-doc -->
+ * Creates an adapter for the <code>target</code>.
+ * <!-- begin-user-doc -->
* <!-- end-user-doc -->
- *
- * @param target
- * the object to adapt.
+ * @param target the object to adapt.
* @return the adapter for the <code>target</code>.
* @generated
*/
@Override
public Adapter createAdapter(Notifier target) {
- return modelSwitch.doSwitch((EObject) target);
+ return modelSwitch.doSwitch((EObject)target);
}
/**
@@ -148,12 +142,10 @@ public Adapter createReviewResultAdapter() {
}
/**
- * Creates a new adapter for an object of class '
- * {@link org.eclipse.mylyn.reviews.core.model.review.Patch <em>Patch</em>}
- * '. <!-- begin-user-doc --> This default implementation returns null so
+ * Creates a new adapter for an object of class '{@link org.eclipse.mylyn.reviews.core.model.review.Patch <em>Patch</em>}'.
+ * <!-- begin-user-doc --> This default implementation returns null so
* that we can easily ignore cases; it's useful to ignore a case when
* inheritance will catch all the cases anyway. <!-- end-user-doc -->
- *
* @return the new adapter.
* @see org.eclipse.mylyn.reviews.core.model.review.Patch
* @generated
@@ -163,13 +155,11 @@ public Adapter createPatchAdapter() {
}
/**
- * Creates a new adapter for an object of class '
- * {@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem
- * <em>Scope Item</em>}'. <!-- begin-user-doc --> This default
+ * Creates a new adapter for an object of class '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem <em>Scope Item</em>}'.
+ * <!-- begin-user-doc --> This default
* implementation returns null so that we can easily ignore cases; it's
* useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
- *
* @return the new adapter.
* @see org.eclipse.mylyn.reviews.core.model.review.ScopeItem
* @generated
@@ -179,9 +169,9 @@ public Adapter createScopeItemAdapter() {
}
/**
- * Creates a new adapter for the default case. <!-- begin-user-doc --> This
+ * Creates a new adapter for the default case.
+ * <!-- begin-user-doc --> This
* default implementation returns null. <!-- end-user-doc -->
- *
* @return the new adapter.
* @generated
*/
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java
index d676e9e8..3ab3388d 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java
@@ -14,6 +14,7 @@
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
+import org.eclipse.mylyn.reviews.core.model.review.*;
import org.eclipse.mylyn.reviews.core.model.review.Patch;
import org.eclipse.mylyn.reviews.core.model.review.Review;
import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
@@ -27,22 +28,21 @@
* starting with the actual class of the object and proceeding up the
* inheritance hierarchy until a non-null result is returned, which is the
* result of the switch. <!-- end-user-doc -->
- *
* @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage
* @generated
*/
public class ReviewSwitch<T> {
/**
- * The cached model package <!-- begin-user-doc --> <!-- end-user-doc -->
- *
+ * The cached model package
+ * <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
protected static ReviewPackage modelPackage;
/**
- * Creates an instance of the switch. <!-- begin-user-doc --> <!--
+ * Creates an instance of the switch.
+ * <!-- begin-user-doc --> <!--
* end-user-doc -->
- *
* @generated
*/
public ReviewSwitch() {
@@ -52,12 +52,10 @@ public ReviewSwitch() {
}
/**
- * Calls <code>caseXXX</code> for each class of the model until one returns
- * a non null result; it yields that result. <!-- begin-user-doc --> <!--
+ * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
+ * <!-- begin-user-doc --> <!--
* end-user-doc -->
- *
- * @return the first non-null result returned by a <code>caseXXX</code>
- * call.
+ * @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
public T doSwitch(EObject theEObject) {
@@ -65,80 +63,70 @@ public T doSwitch(EObject theEObject) {
}
/**
- * Calls <code>caseXXX</code> for each class of the model until one returns
- * a non null result; it yields that result. <!-- begin-user-doc --> <!--
+ * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
+ * <!-- begin-user-doc --> <!--
* end-user-doc -->
- *
- * @return the first non-null result returned by a <code>caseXXX</code>
- * call.
+ * @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(EClass theEClass, EObject theEObject) {
if (theEClass.eContainer() == modelPackage) {
return doSwitch(theEClass.getClassifierID(), theEObject);
- } else {
+ }
+ else {
List<EClass> eSuperTypes = theEClass.getESuperTypes();
- return eSuperTypes.isEmpty() ? defaultCase(theEObject) : doSwitch(
- eSuperTypes.get(0), theEObject);
+ return
+ eSuperTypes.isEmpty() ?
+ defaultCase(theEObject) :
+ doSwitch(eSuperTypes.get(0), theEObject);
}
}
/**
- * Calls <code>caseXXX</code> for each class of the model until one returns
- * a non null result; it yields that result. <!-- begin-user-doc --> <!--
+ * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
+ * <!-- begin-user-doc --> <!--
* end-user-doc -->
- *
- * @return the first non-null result returned by a <code>caseXXX</code>
- * call.
+ * @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
- case ReviewPackage.REVIEW: {
- Review review = (Review) theEObject;
- T result = caseReview(review);
- if (result == null)
- result = defaultCase(theEObject);
- return result;
- }
- case ReviewPackage.REVIEW_RESULT: {
- ReviewResult reviewResult = (ReviewResult) theEObject;
- T result = caseReviewResult(reviewResult);
- if (result == null)
- result = defaultCase(theEObject);
- return result;
- }
- case ReviewPackage.PATCH: {
- Patch patch = (Patch) theEObject;
- T result = casePatch(patch);
- if (result == null)
- result = caseScopeItem(patch);
- if (result == null)
- result = defaultCase(theEObject);
- return result;
- }
- case ReviewPackage.SCOPE_ITEM: {
- ScopeItem scopeItem = (ScopeItem) theEObject;
- T result = caseScopeItem(scopeItem);
- if (result == null)
- result = defaultCase(theEObject);
- return result;
- }
- default:
- return defaultCase(theEObject);
+ case ReviewPackage.REVIEW: {
+ Review review = (Review)theEObject;
+ T result = caseReview(review);
+ if (result == null) result = defaultCase(theEObject);
+ return result;
+ }
+ case ReviewPackage.REVIEW_RESULT: {
+ ReviewResult reviewResult = (ReviewResult)theEObject;
+ T result = caseReviewResult(reviewResult);
+ if (result == null) result = defaultCase(theEObject);
+ return result;
+ }
+ case ReviewPackage.PATCH: {
+ Patch patch = (Patch)theEObject;
+ T result = casePatch(patch);
+ if (result == null) result = caseScopeItem(patch);
+ if (result == null) result = defaultCase(theEObject);
+ return result;
+ }
+ case ReviewPackage.SCOPE_ITEM: {
+ ScopeItem scopeItem = (ScopeItem)theEObject;
+ T result = caseScopeItem(scopeItem);
+ if (result == null) result = defaultCase(theEObject);
+ return result;
+ }
+ default: return defaultCase(theEObject);
}
}
/**
- * Returns the result of interpreting the object as an instance of '
- * <em>Review</em>'. <!-- begin-user-doc --> This implementation returns
+ * Returns the result of interpreting the object as an instance of '<em>Review</em>'.
+ * <!-- begin-user-doc --> This implementation returns
* null; returning a non-null result will terminate the switch. <!--
* end-user-doc -->
- *
- * @param object
- * the target of the switch.
- * @return the result of interpreting the object as an instance of '
- * <em>Review</em>'.
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>Review</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
@@ -147,15 +135,12 @@ public T caseReview(Review object) {
}
/**
- * Returns the result of interpreting the object as an instance of '
- * <em>Result</em>'. <!-- begin-user-doc --> This implementation returns
+ * Returns the result of interpreting the object as an instance of '<em>Result</em>'.
+ * <!-- begin-user-doc --> This implementation returns
* null; returning a non-null result will terminate the switch. <!--
* end-user-doc -->
- *
- * @param object
- * the target of the switch.
- * @return the result of interpreting the object as an instance of '
- * <em>Result</em>'.
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>Result</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
@@ -164,15 +149,12 @@ public T caseReviewResult(ReviewResult object) {
}
/**
- * Returns the result of interpreting the object as an instance of '
- * <em>Patch</em>'. <!-- begin-user-doc --> This implementation returns
+ * Returns the result of interpreting the object as an instance of '<em>Patch</em>'.
+ * <!-- begin-user-doc --> This implementation returns
* null; returning a non-null result will terminate the switch. <!--
* end-user-doc -->
- *
- * @param object
- * the target of the switch.
- * @return the result of interpreting the object as an instance of '
- * <em>Patch</em>'.
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>Patch</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
@@ -181,15 +163,12 @@ public T casePatch(Patch object) {
}
/**
- * Returns the result of interpreting the object as an instance of '
- * <em>Scope Item</em>'. <!-- begin-user-doc --> This implementation returns
+ * Returns the result of interpreting the object as an instance of '<em>Scope Item</em>'.
+ * <!-- begin-user-doc --> This implementation returns
* null; returning a non-null result will terminate the switch. <!--
* end-user-doc -->
- *
- * @param object
- * the target of the switch.
- * @return the result of interpreting the object as an instance of '
- * <em>Scope Item</em>'.
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>Scope Item</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
@@ -198,15 +177,12 @@ public T caseScopeItem(ScopeItem object) {
}
/**
- * Returns the result of interpreting the object as an instance of '
- * <em>EObject</em>'. <!-- begin-user-doc --> This implementation returns
+ * Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
+ * <!-- begin-user-doc --> This implementation returns
* null; returning a non-null result will terminate the switch, but this is
* the last case anyway. <!-- end-user-doc -->
- *
- * @param object
- * the target of the switch.
- * @return the result of interpreting the object as an instance of '
- * <em>EObject</em>'.
+ * @param object the target of the switch.
+ * @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
|
7631ac6f526edf472d1383f7b82171c7ac29f0fb
|
Delta Spike
|
DELTASPIKE-378 add getPropertyAwarePropertyValue
feel free to propose a better name if you find one :)
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java
index 05cbc59df..6b3ada263 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java
@@ -162,18 +162,110 @@ public static String getPropertyValue(String key)
* <p><b>Attention</b> This method must only be used after all ConfigSources
* got registered and it also must not be used to determine the ProjectStage itself.</p>
* @param key
+ * @return the configured value or if non found the defaultValue
+ *
+ */
+ public static String getProjectStageAwarePropertyValue(String key)
+ {
+ ProjectStage ps = getProjectStage();
+
+ String value = getPropertyValue(key + '.' + ps);
+ if (value == null)
+ {
+ value = getPropertyValue(key);
+ }
+
+ return value;
+ }
+ /**
+ * {@link #getProjectStageAwarePropertyValue(String)} which returns the defaultValue
+ * if the property is <code>null</code> or empty.
+ * @param key
* @param defaultValue
* @return the configured value or if non found the defaultValue
*
*/
public static String getProjectStageAwarePropertyValue(String key, String defaultValue)
{
- ProjectStage ps = getProjectStage();
+ String value = getProjectStageAwarePropertyValue(key);
+
+ if (value == null || value.length() == 0)
+ {
+ value = defaultValue;
+ }
+
+ return value;
+ }
+
+ /**
+ * <p>Search for the configured value in all {@link ConfigSource}s and take the
+ * current {@link org.apache.deltaspike.core.api.projectstage.ProjectStage}
+ * and the value configured for the given property into account.</p>
+ *
+ * <p>The first step is to resolve the value of the given property. This will
+ * take the current ProjectStage into account. E.g. given the property is 'dbvendor'
+ * and the ProjectStage is 'UnitTest', the first lookup is
+ * <ul><li>'dbvendor.UnitTest'</li></ul>.
+ * If this value is not found then we will do a 2nd lookup for
+ * <ul><li>'dbvendor'</li></ul></p>
+ *
+ * <p>If a value was found for the given property (e.g. dbvendor = 'mysql'
+ * then we will use this value to lookup in the following order until we
+ * found a non-null value. If there was no value found for the property
+ * we will only do the key+ProjectStage and key lookup.
+ * In the following sample 'dataSource' is used as key parameter:
+ *
+ * <ul>
+ * <li>'datasource.mysql.UnitTest'</li>
+ * <li>'datasource.mysql'</li>
+ * <li>'datasource.UnitTest'</li>
+ * <li>'datasource'</li>
+ * </ul>
+ * </p>
+ *
+ *
+ * <p><b>Attention</b> This method must only be used after all ConfigSources
+ * got registered and it also must not be used to determine the ProjectStage itself.</p>
+ * @param key
+ * @param property the property to look up first
+ * @return the configured value or if non found the defaultValue
+ *
+ */
+ public static String getPropertyAwarePropertyValue(String key, String property)
+ {
+ String propertyValue = getProjectStageAwarePropertyValue(property);
+
+ String value = null;
+
+ if (propertyValue != null && propertyValue.length() > 0)
+ {
+ value = getProjectStageAwarePropertyValue(key + '.' + propertyValue);
+ }
- String value = getPropertyValue(key + '.' + ps, defaultValue);
if (value == null)
{
- value = getPropertyValue(key, defaultValue);
+ value = getProjectStageAwarePropertyValue(key);
+ }
+
+ return value;
+ }
+
+ /*
+ * <p><b>Attention</b> This method must only be used after all ConfigSources
+ * got registered and it also must not be used to determine the ProjectStage itself.</p>
+ * @param key
+ * @param property the property to look up first
+ * @param defaultValue
+ * @return the configured value or if non found the defaultValue
+ *
+ */
+ public static String getPropertyAwarePropertyValue(String key, String property, String defaultValue)
+ {
+ String value = getPropertyAwarePropertyValue(key, property);
+
+ if (value == null || value.length() == 0)
+ {
+ value = defaultValue;
}
return value;
diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java
index 91ebb22dc..d30e7de52 100644
--- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java
+++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java
@@ -28,6 +28,7 @@
public class ConfigResolverTest
{
+ private static final String DEFAULT_VALUE = "defaultValue";
@Test
public void testOverruledValue()
{
@@ -60,12 +61,43 @@ public void testGetProjectStageAwarePropertyValue()
Assert.assertNull(ConfigResolver.getProjectStageAwarePropertyValue("notexisting", null));
Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey", null));
+ Assert.assertEquals("unittestvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey"));
Assert.assertEquals("unittestvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey", null));
Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey2", null));
+ Assert.assertEquals("testvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey2"));
Assert.assertEquals("testvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey2", null));
Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey3", null));
- Assert.assertEquals("", ConfigResolver.getProjectStageAwarePropertyValue("testkey3", null));
+ Assert.assertEquals("", ConfigResolver.getProjectStageAwarePropertyValue("testkey3"));
+ Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getProjectStageAwarePropertyValue("testkey3", DEFAULT_VALUE));
+ }
+
+ @Test
+ public void testGetPropertyAwarePropertyValue() {
+ ProjectStageProducer.setProjectStage(ProjectStage.UnitTest);
+
+ Assert.assertNull(ConfigResolver.getPropertyAwarePropertyValue("notexisting", null));
+
+ Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey", null));
+ Assert.assertEquals("unittestvalue", ConfigResolver.getPropertyAwarePropertyValue("testkey", "dbvendor"));
+ Assert.assertEquals("unittestvalue", ConfigResolver.getPropertyAwarePropertyValue("testkey", "dbvendor", null));
+
+ Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey2", null));
+ Assert.assertEquals("testvalue", ConfigResolver.getPropertyAwarePropertyValue("testkey2", "dbvendor"));
+ Assert.assertEquals("testvalue", ConfigResolver.getPropertyAwarePropertyValue("testkey2", "dbvendor", null));
+
+ Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey3", null));
+ Assert.assertEquals("", ConfigResolver.getPropertyAwarePropertyValue("testkey3", "dbvendor"));
+ Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getPropertyAwarePropertyValue("testkey3", "dbvendor", DEFAULT_VALUE));
+
+ Assert.assertEquals("TestDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendor"));
+ Assert.assertEquals("PostgreDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendor2"));
+ Assert.assertEquals("DefaultDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendorX"));
+
+ Assert.assertEquals("TestDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendor", null));
+ Assert.assertEquals("PostgreDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendor2", null));
+ Assert.assertEquals("DefaultDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendorX", null));
+ Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getPropertyAwarePropertyValue("dataSourceX", "dbvendorX", DEFAULT_VALUE));
}
}
diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java
index e9e066fba..d0f2c938b 100644
--- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java
+++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java
@@ -48,6 +48,20 @@ public TestConfigSource()
// a value which got ProjectStage overloaded to an empty value
props.put("testkey3", "testvalue");
props.put("testkey3.UnitTest", "");
+
+ // now for the PropertyAware tests
+ props.put("dbvendor.UnitTest", "mysql");
+ props.put("dbvendor", "postgresql");
+
+ props.put("dataSource.mysql.Production", "java:/comp/env/MyDs");
+ props.put("dataSource.mysql.UnitTest", "TestDataSource");
+ props.put("dataSource.postgresql", "PostgreDataSource");
+ props.put("dataSource", "DefaultDataSource");
+
+ // another one
+ props.put("dbvendor2.Production", "mysql");
+ props.put("dbvendor2", "postgresql");
+
}
@Override
|
4a9f2fb05a3163e11ed35d85a33a6b8e216dde77
|
ReactiveX-RxJava
|
TakeWhile protect calls to predicate--
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java b/rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java
index f45efabc92..1bad2d36e5 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java
@@ -123,7 +123,15 @@ public void onError(Exception e) {
@Override
public void onNext(T args) {
- if (predicate.call(args, counter.getAndIncrement())) {
+ Boolean isSelected;
+ try {
+ isSelected = predicate.call(args, counter.getAndIncrement());
+ }
+ catch (Exception e) {
+ observer.onError(e);
+ return;
+ }
+ if (isSelected) {
observer.onNext(args);
} else {
observer.onCompleted();
@@ -238,6 +246,35 @@ public Boolean call(String s)
})).last();
}
+ @Test
+ public void testTakeWhileProtectsPredicateCall() {
+ TestObservable source = new TestObservable(mock(Subscription.class), "one");
+ final RuntimeException testException = new RuntimeException("test exception");
+
+ @SuppressWarnings("unchecked")
+ Observer<String> aObserver = mock(Observer.class);
+ Observable<String> take = Observable.create(takeWhile(source, new Func1<String, Boolean>()
+ {
+ @Override
+ public Boolean call(String s)
+ {
+ throw testException;
+ }
+ }));
+ take.subscribe(aObserver);
+
+ // wait for the Observable to complete
+ try {
+ source.t.join();
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+
+ verify(aObserver, never()).onNext(any(String.class));
+ verify(aObserver, times(1)).onError(testException);
+ }
+
@Test
public void testUnsubscribeAfterTake() {
Subscription s = mock(Subscription.class);
|
ea3cbbfc7cebb2adc6edd8c9aaefd786c7cd05df
|
ReactiveX-RxJava
|
ObserveOn and SubscribeOn concurrency unit tests--- these are very rudimentary and may have a determinism problem due to the Thread.sleep-
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
index 59edfade39..119b2ce96e 100644
--- a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
+++ b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java
@@ -23,6 +23,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
@@ -395,4 +396,137 @@ public Subscription call(Scheduler scheduler, String state) {
}
}
+ @Test
+ public void testConcurrentOnNextFailsValidation() throws InterruptedException {
+
+ final int count = 10;
+ final CountDownLatch latch = new CountDownLatch(count);
+ Observable<String> o = Observable.create(new Func1<Observer<String>, Subscription>() {
+
+ @Override
+ public Subscription call(final Observer<String> observer) {
+ for (int i = 0; i < count; i++) {
+ final int v = i;
+ new Thread(new Runnable() {
+
+ @Override
+ public void run() {
+ observer.onNext("v: " + v);
+
+ latch.countDown();
+ }
+ }).start();
+ }
+ return Subscriptions.empty();
+ }
+ });
+
+ ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<String>();
+ // this should call onNext concurrently
+ o.subscribe(observer);
+
+ if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) {
+ fail("timed out");
+ }
+
+ if (observer.error.get() == null) {
+ fail("We expected error messages due to concurrency");
+ }
+ }
+
+ @Test
+ public void testObserveOn() throws InterruptedException {
+
+ Observable<String> o = Observable.from("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten");
+
+ ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<String>();
+
+ o.observeOn(Schedulers.threadPoolForComputation()).subscribe(observer);
+
+ if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) {
+ fail("timed out");
+ }
+
+ if (observer.error.get() != null) {
+ observer.error.get().printStackTrace();
+ fail("Error: " + observer.error.get().getMessage());
+ }
+ }
+
+ @Test
+ public void testSubscribeOnNestedConcurrency() throws InterruptedException {
+
+ Observable<String> o = Observable.from("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")
+ .mapMany(new Func1<String, Observable<String>>() {
+
+ @Override
+ public Observable<String> call(final String v) {
+ return Observable.create(new Func1<Observer<String>, Subscription>() {
+
+ @Override
+ public Subscription call(final Observer<String> observer) {
+ observer.onNext("value_after_map-" + v);
+ observer.onCompleted();
+ return Subscriptions.empty();
+ }
+ }).subscribeOn(Schedulers.newThread()); // subscribe on a new thread
+ }
+ });
+
+ ConcurrentObserverValidator<String> observer = new ConcurrentObserverValidator<String>();
+
+ o.subscribe(observer);
+
+ if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) {
+ fail("timed out");
+ }
+
+ if (observer.error.get() != null) {
+ observer.error.get().printStackTrace();
+ fail("Error: " + observer.error.get().getMessage());
+ }
+ }
+
+ /**
+ * Used to determine if onNext is being invoked concurrently.
+ *
+ * @param <T>
+ */
+ private static class ConcurrentObserverValidator<T> implements Observer<T> {
+
+ final AtomicInteger concurrentCounter = new AtomicInteger();
+ final AtomicReference<Exception> error = new AtomicReference<Exception>();
+ final CountDownLatch completed = new CountDownLatch(1);
+
+ @Override
+ public void onCompleted() {
+ completed.countDown();
+ }
+
+ @Override
+ public void onError(Exception e) {
+ completed.countDown();
+ error.set(e);
+ }
+
+ @Override
+ public void onNext(T args) {
+ int count = concurrentCounter.incrementAndGet();
+ System.out.println("ConcurrentObserverValidator.onNext: " + args);
+ if (count > 1) {
+ onError(new RuntimeException("we should not have concurrent execution of onNext"));
+ }
+ try {
+ try {
+ // take some time so other onNext calls could pile up (I haven't yet thought of a way to do this without sleeping)
+ Thread.sleep(50);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ } finally {
+ concurrentCounter.decrementAndGet();
+ }
+ }
+
+ }
}
|
43b5767f6213784c7e4cdfce2bebadd87108b33f
|
hbase
|
HBASE-10606 Bad timeout in- RpcRetryingCaller-callWithRetries w/o parameters--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1572124 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
index 8b2df053f67c..bf89fe276bd2 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
@@ -33,7 +33,6 @@
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -49,7 +48,6 @@
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
-import org.apache.hadoop.hbase.util.Pair;
import org.cloudera.htrace.Trace;
import com.google.common.annotations.VisibleForTesting;
@@ -118,8 +116,6 @@ public static interface AsyncRequestFuture {
public void waitUntilDone() throws InterruptedIOException {}
};
-
- // TODO: many of the fields should be made private
protected final long id;
protected final ClusterConnection hConnection;
@@ -156,6 +152,7 @@ public void waitUntilDone() throws InterruptedIOException {}
protected final long pause;
protected int numTries;
protected int serverTrackerTimeout;
+ protected int operationTimeout;
// End configuration settings.
protected static class BatchErrors {
@@ -206,6 +203,8 @@ public AsyncProcess(ClusterConnection hc, Configuration conf, ExecutorService po
HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
this.numTries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
+ this.operationTimeout = conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
+ HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
this.maxTotalConcurrentTasks = conf.getInt(HConstants.HBASE_CLIENT_MAX_TOTAL_TASKS,
HConstants.DEFAULT_HBASE_CLIENT_MAX_TOTAL_TASKS);
@@ -303,14 +302,12 @@ public <CResult> AsyncRequestFuture submit(ExecutorService pool, TableName table
Iterator<? extends Row> it = rows.iterator();
while (it.hasNext()) {
Row r = it.next();
- HRegionLocation loc = null;
+ HRegionLocation loc;
try {
loc = findDestLocation(tableName, r);
} catch (IOException ex) {
- if (locationErrors == null) {
- locationErrors = new ArrayList<Exception>();
- locationErrorRows = new ArrayList<Integer>();
- }
+ locationErrors = new ArrayList<Exception>();
+ locationErrorRows = new ArrayList<Integer>();
LOG.error("Failed to get region location ", ex);
// This action failed before creating ars. Add it to retained but do not add to submit list.
// We will then add it to ars in an already-failed state.
@@ -600,7 +597,7 @@ public void run() {
try {
MultiServerCallable<Row> callable = createCallable(server, tableName, multiAction);
try {
- res = createCaller(callable).callWithoutRetries(callable);
+ res = createCaller(callable).callWithoutRetries(callable, operationTimeout);
} catch (IOException e) {
// The service itself failed . It may be an error coming from the communication
// layer, but, as well, a functional error raised by the server.
@@ -1010,7 +1007,7 @@ public boolean hasError() {
* failed operations themselves.
* @param failedRows an optional list into which the rows that failed since the last time
* {@link #waitForAllPreviousOpsAndReset(List)} was called, or AP was created, are saved.
- * @returns all the errors since the last time {@link #waitForAllPreviousOpsAndReset(List)}
+ * @return all the errors since the last time {@link #waitForAllPreviousOpsAndReset(List)}
* was called, or AP was created.
*/
public RetriesExhaustedWithDetailsException waitForAllPreviousOpsAndReset(
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
index 807975eb6c9c..0290dcac922a 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
@@ -39,6 +39,7 @@
import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos;
import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.ExceptionUtil;
/**
* Implements the scanner interface for the HBase client.
@@ -63,7 +64,7 @@ public class ClientScanner extends AbstractClientScanner {
protected final long maxScannerResultSize;
private final HConnection connection;
private final TableName tableName;
- private final int scannerTimeout;
+ protected final int scannerTimeout;
protected boolean scanMetricsPublished = false;
protected RpcRetryingCaller<Result []> caller;
@@ -224,7 +225,7 @@ protected boolean nextScanner(int nbRows, final boolean done)
// Close the previous scanner if it's open
if (this.callable != null) {
this.callable.setClose();
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
this.callable = null;
}
@@ -261,7 +262,7 @@ protected boolean nextScanner(int nbRows, final boolean done)
callable = getScannerCallable(localStartKey, nbRows);
// Open a scanner on the region server starting at the
// beginning of the region
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
this.currentRegion = callable.getHRegionInfo();
if (this.scanMetrics != null) {
this.scanMetrics.countOfRegions.incrementAndGet();
@@ -326,17 +327,17 @@ public Result next() throws IOException {
// Skip only the first row (which was the last row of the last
// already-processed batch).
callable.setCaching(1);
- values = this.caller.callWithRetries(callable);
+ values = this.caller.callWithRetries(callable, scannerTimeout);
callable.setCaching(this.caching);
skipFirst = false;
}
// Server returns a null values if scanning is to stop. Else,
// returns an empty array if scanning is to go on and we've just
// exhausted current region.
- values = this.caller.callWithRetries(callable);
+ values = this.caller.callWithRetries(callable, scannerTimeout);
if (skipFirst && values != null && values.length == 1) {
skipFirst = false; // Already skipped, unset it before scanning again
- values = this.caller.callWithRetries(callable);
+ values = this.caller.callWithRetries(callable, scannerTimeout);
}
retryAfterOutOfOrderException = true;
} catch (DoNotRetryIOException e) {
@@ -428,7 +429,7 @@ public void close() {
if (callable != null) {
callable.setClose();
try {
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
} catch (UnknownScannerException e) {
// We used to catch this error, interpret, and rethrow. However, we
// have since decided that it's not nice for a scanner's close to
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java
index 77fd2aa3186a..a980ec968f41 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java
@@ -200,7 +200,7 @@ && nextScanner(countdown, values == null, currentRegionDone)) {
// Server returns a null values if scanning is to stop. Else,
// returns an empty array if scanning is to go on and we've just
// exhausted current region.
- values = this.caller.callWithRetries(smallScanCallable);
+ values = this.caller.callWithRetries(smallScanCallable, scannerTimeout);
this.currentRegion = smallScanCallable.getHRegionInfo();
long currentTime = System.currentTimeMillis();
if (this.scanMetrics != null) {
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java
index 2dc212a76686..27e973ba7af9 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java
@@ -175,6 +175,7 @@ public class HBaseAdmin implements Abortable, Closeable {
private boolean aborted;
private boolean cleanupConnectionOnClose = false; // close the connection in close()
private boolean closed = false;
+ private int operationTimeout;
private RpcRetryingCallerFactory rpcCallerFactory;
@@ -192,6 +193,11 @@ public HBaseAdmin(Configuration c)
this.cleanupConnectionOnClose = true;
}
+ public int getOperationTimeout() {
+ return operationTimeout;
+ }
+
+
/**
* Constructor for externally managed HConnections.
* The connection to master will be created when required by admin functions.
@@ -217,6 +223,9 @@ public HBaseAdmin(HConnection connection)
HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
this.retryLongerMultiplier = this.conf.getInt(
"hbase.client.retries.longer.multiplier", 10);
+ this.operationTimeout = this.conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
+ HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
+
this.rpcCallerFactory = RpcRetryingCallerFactory.instantiate(this.conf);
}
@@ -3315,7 +3324,7 @@ public long sleep(long pause, int tries) {
private <V> V executeCallable(MasterCallable<V> callable) throws IOException {
RpcRetryingCaller<V> caller = rpcCallerFactory.newCaller();
try {
- return caller.callWithRetries(callable);
+ return caller.callWithRetries(callable, operationTimeout);
} finally {
callable.close();
}
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java
index 1a6ee4c59e2e..62fb9ccc73b4 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java
@@ -36,6 +36,7 @@
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.ExceptionUtil;
/**
* Scanner class that contains the <code>hbase:meta</code> table scanning logic.
@@ -189,6 +190,7 @@ static void metaScan(Configuration configuration, ClusterConnection connection,
try {
scanner.close();
} catch (Throwable t) {
+ ExceptionUtil.rethrowIfInterrupt(t);
LOG.debug("Got exception in closing the result scanner", t);
}
}
@@ -196,6 +198,7 @@ static void metaScan(Configuration configuration, ClusterConnection connection,
try {
visitor.close();
} catch (Throwable t) {
+ ExceptionUtil.rethrowIfInterrupt(t);
LOG.debug("Got exception in closing the meta scanner visitor", t);
}
}
@@ -203,6 +206,7 @@ static void metaScan(Configuration configuration, ClusterConnection connection,
try {
metaTable.close();
} catch (Throwable t) {
+ ExceptionUtil.rethrowIfInterrupt(t);
LOG.debug("Got exception in closing the meta table", t);
}
}
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java
index 618b3b38003b..470ffa132fc6 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java
@@ -60,7 +60,7 @@ protected boolean nextScanner(int nbRows, final boolean done)
// Close the previous scanner if it's open
if (this.callable != null) {
this.callable.setClose();
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
this.callable = null;
}
@@ -108,7 +108,7 @@ protected boolean nextScanner(int nbRows, final boolean done)
callable = getScannerCallable(localStartKey, nbRows, locateStartRow);
// Open a scanner on the region server starting at the
// beginning of the region
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
this.currentRegion = callable.getHRegionInfo();
if (this.scanMetrics != null) {
this.scanMetrics.countOfRegions.incrementAndGet();
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java
index 68faba560ec9..2a9732522079 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java
@@ -42,20 +42,14 @@
* Runs an rpc'ing {@link RetryingCallable}. Sets into rpc client
* threadlocal outstanding timeouts as so we don't persist too much.
* Dynamic rather than static so can set the generic appropriately.
+ *
+ * This object has a state. It should not be used by in parallel by different threads.
+ * Reusing it is possible however, even between multiple threads. However, the user will
+ * have to manage the synchronization on its side: there is no synchronization inside the class.
*/
@InterfaceAudience.Private
[email protected]
- (value = "IS2_INCONSISTENT_SYNC", justification = "na")
public class RpcRetryingCaller<T> {
static final Log LOG = LogFactory.getLog(RpcRetryingCaller.class);
- /**
- * Timeout for the call including retries
- */
- private int callTimeout;
- /**
- * The remaining time, for the call to come. Takes into account the tries already done.
- */
- private int remainingTime;
/**
* When we started making calls.
*/
@@ -70,18 +64,17 @@ public class RpcRetryingCaller<T> {
public RpcRetryingCaller(Configuration conf) {
this.pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
- HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
+ HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
this.retries =
conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
- this.callTimeout = conf.getInt(
- HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
- HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
}
- private void beforeCall() {
- if (callTimeout > 0) {
- remainingTime = (int) (callTimeout -
+ private int getRemainingTime(int callTimeout) {
+ if (callTimeout <= 0) {
+ return 0;
+ } else {
+ int remainingTime = (int) (callTimeout -
(EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime));
if (remainingTime < MIN_RPC_TIMEOUT) {
// If there is no time left, we're trying anyway. It's too late.
@@ -89,17 +82,10 @@ private void beforeCall() {
// resetting to the minimum.
remainingTime = MIN_RPC_TIMEOUT;
}
- } else {
- remainingTime = 0;
+ return remainingTime;
}
}
-
- public synchronized T callWithRetries(RetryingCallable<T> callable) throws IOException,
- RuntimeException {
- return callWithRetries(callable, HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
- }
-
/**
* Retries if invocation fails.
* @param callTimeout Timeout for this call
@@ -108,11 +94,8 @@ public synchronized T callWithRetries(RetryingCallable<T> callable) throws IOExc
* @throws IOException if a remote or network exception occurs
* @throws RuntimeException other unspecified error
*/
- @edu.umd.cs.findbugs.annotations.SuppressWarnings
- (value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "na")
- public synchronized T callWithRetries(RetryingCallable<T> callable, int callTimeout)
+ public T callWithRetries(RetryingCallable<T> callable, int callTimeout)
throws IOException, RuntimeException {
- this.callTimeout = callTimeout;
List<RetriesExhaustedException.ThrowableWithExtraContext> exceptions =
new ArrayList<RetriesExhaustedException.ThrowableWithExtraContext>();
this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
@@ -120,8 +103,7 @@ public synchronized T callWithRetries(RetryingCallable<T> callable, int callTime
long expectedSleep;
try {
callable.prepare(tries != 0); // if called with false, check table status on ZK
- beforeCall();
- return callable.call(remainingTime);
+ return callable.call(getRemainingTime(callTimeout));
} catch (Throwable t) {
ExceptionUtil.rethrowIfInterrupt(t);
if (LOG.isTraceEnabled()) {
@@ -145,8 +127,8 @@ public synchronized T callWithRetries(RetryingCallable<T> callable, int callTime
// If, after the planned sleep, there won't be enough time left, we stop now.
long duration = singleCallDuration(expectedSleep);
- if (duration > this.callTimeout) {
- String msg = "callTimeout=" + this.callTimeout + ", callDuration=" + duration +
+ if (duration > callTimeout) {
+ String msg = "callTimeout=" + callTimeout + ", callDuration=" + duration +
": " + callable.getExceptionMessageAdditionalDetail();
throw (SocketTimeoutException)(new SocketTimeoutException(msg).initCause(t));
}
@@ -163,8 +145,7 @@ public synchronized T callWithRetries(RetryingCallable<T> callable, int callTime
* @return Calculate how long a single call took
*/
private long singleCallDuration(final long expectedSleep) {
- return (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime)
- + MIN_RPC_TIMEOUT + expectedSleep;
+ return (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime) + expectedSleep;
}
/**
@@ -176,7 +157,7 @@ private long singleCallDuration(final long expectedSleep) {
* @throws IOException if a remote or network exception occurs
* @throws RuntimeException other unspecified error
*/
- public T callWithoutRetries(RetryingCallable<T> callable)
+ public T callWithoutRetries(RetryingCallable<T> callable, int callTimeout)
throws IOException, RuntimeException {
// The code of this method should be shared with withRetries.
this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RegionCoprocessorRpcChannel.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RegionCoprocessorRpcChannel.java
index f28feac23eb2..e627662c34b2 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RegionCoprocessorRpcChannel.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RegionCoprocessorRpcChannel.java
@@ -24,6 +24,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.RegionServerCallable;
@@ -52,6 +53,7 @@ public class RegionCoprocessorRpcChannel extends CoprocessorRpcChannel{
private final TableName table;
private final byte[] row;
private byte[] lastRegion;
+ private int operationTimeout;
private RpcRetryingCallerFactory rpcFactory;
@@ -60,6 +62,9 @@ public RegionCoprocessorRpcChannel(HConnection conn, TableName table, byte[] row
this.table = table;
this.row = row;
this.rpcFactory = RpcRetryingCallerFactory.instantiate(conn.getConfiguration());
+ this.operationTimeout = conn.getConfiguration().getInt(
+ HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
+ HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
}
@Override
@@ -88,7 +93,7 @@ public CoprocessorServiceResponse call(int callTimeout) throws Exception {
}
};
CoprocessorServiceResponse result = rpcFactory.<CoprocessorServiceResponse> newCaller()
- .callWithRetries(callable);
+ .callWithRetries(callable, operationTimeout);
Message response = null;
if (result.getValue().hasValue()) {
response = responsePrototype.newBuilderForType()
diff --git a/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestAsyncProcess.java b/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestAsyncProcess.java
index 66c51721f9a4..1ff1f01dd173 100644
--- a/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestAsyncProcess.java
+++ b/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestAsyncProcess.java
@@ -149,7 +149,8 @@ protected RpcRetryingCaller<MultiResponse> createCaller(MultiServerCallable<Row>
callable.getMulti(), nbMultiResponse, nbActions);
return new RpcRetryingCaller<MultiResponse>(conf) {
@Override
- public MultiResponse callWithoutRetries( RetryingCallable<MultiResponse> callable)
+ public MultiResponse callWithoutRetries(RetryingCallable<MultiResponse> callable,
+ int callTimeout)
throws IOException, RuntimeException {
try {
// sleep one second in order for threadpool to start another thread instead of reusing
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.java
index 43e167f0aaf1..d49146a6ed45 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.java
@@ -630,7 +630,7 @@ public Boolean call(int callTimeout) throws Exception {
List<LoadQueueItem> toRetry = new ArrayList<LoadQueueItem>();
Configuration conf = getConf();
boolean success = RpcRetryingCallerFactory.instantiate(conf).<Boolean> newCaller()
- .callWithRetries(svrCallable);
+ .callWithRetries(svrCallable, Integer.MAX_VALUE);
if (!success) {
LOG.warn("Attempt to bulk load region containing "
+ Bytes.toStringBinary(first) + " into table "
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAdmin.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAdmin.java
index ea56574f52de..38194f970edd 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAdmin.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAdmin.java
@@ -1552,7 +1552,6 @@ private void setUpforLogRolling() {
TEST_UTIL.getConfiguration().setInt(
"hbase.regionserver.logroll.errors.tolerated", 2);
- TEST_UTIL.getConfiguration().setInt("ipc.socket.timeout", 10 * 1000);
TEST_UTIL.getConfiguration().setInt("hbase.rpc.timeout", 10 * 1000);
// For less frequently updated regions flush after every 2 flushes
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java
index 89ce874495fa..c1d93a2e788f 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java
@@ -170,7 +170,7 @@ public Void call(int callTimeout) throws Exception {
};
RpcRetryingCallerFactory factory = new RpcRetryingCallerFactory(conf);
RpcRetryingCaller<Void> caller = factory.<Void> newCaller();
- caller.callWithRetries(callable);
+ caller.callWithRetries(callable, Integer.MAX_VALUE);
// Periodically do compaction to reduce the number of open file handles.
if (numBulkLoads.get() % 10 == 0) {
@@ -190,7 +190,7 @@ public Void call(int callTimeout) throws Exception {
return null;
}
};
- caller.callWithRetries(callable);
+ caller.callWithRetries(callable, Integer.MAX_VALUE);
}
}
}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestLogRollAbort.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestLogRollAbort.java
index 590481f15372..4a1b0f5f625e 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestLogRollAbort.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestLogRollAbort.java
@@ -60,7 +60,6 @@ public static void setUpBeforeClass() throws Exception {
// Tweak default timeout values down for faster recovery
TEST_UTIL.getConfiguration().setInt(
"hbase.regionserver.logroll.errors.tolerated", 2);
- TEST_UTIL.getConfiguration().setInt("ipc.socket.timeout", 10 * 1000);
TEST_UTIL.getConfiguration().setInt("hbase.rpc.timeout", 10 * 1000);
// Increase the amount of time between client retries
|
0c6b38b0b5749057d6e9dcb5f7917f27e6542fc3
|
spring-framework
|
DataSourceUtils lets timeout exceptions through- even for setReadOnly calls (revised; SPR-7226)--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java b/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java
index 07c6efaf3494..89ecf0bc66e3 100644
--- a/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java
+++ b/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.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.
@@ -21,7 +21,6 @@
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;
-
import javax.sql.DataSource;
import junit.framework.TestCase;
@@ -463,6 +462,8 @@ public void testParticipatingTransactionWithIncompatibleReadOnly() throws Except
conControl.setReturnValue(false, 1);
con.rollback();
conControl.setVoidCallable(1);
+ con.setReadOnly(true);
+ conControl.setThrowable(new SQLException("read-only not supported"), 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
con.close();
|
3384d37a5254d5b232d2912ad67988ff505fb263
|
tapiji
|
Fix error while restoring UI state if memento files are not present.
If the Eclipse IDE is started the first time with internationalization support, the TapiJI managed memento files are not present within the workspace. This changeset prevents an exception during startup if the state file is not found.
(cherry picked from commit 9a915cc7ecb994b9aef66a7648592ed36e27b89b)
Conflicts:
org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
|
a
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
index 0700ff51..8248c03e 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java
@@ -1,13 +1,11 @@
/*******************************************************************************
- * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
+ * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
*
- * Contributors:
- * Martin Reiterer - initial API and implementation
- * Alexej Strelzow - moved object management to RBManager, Babel integration
+ * Contributors: Martin Reiterer - initial API and implementation Alexej
+ * Strelzow - moved object management to RBManager, Babel integration
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui;
@@ -129,10 +127,14 @@ public void onDelete(String resourceBundleId,
public static ResourceBundleManager getManager(IProject project) {
// check if persistant state has been loaded
if (!state_loaded) {
- stateLoader = getStateLoader();
- stateLoader.loadState();
- state_loaded = true;
- excludedResources = stateLoader.getExcludedResources();
+ IStateLoader stateLoader = getStateLoader();
+ if (stateLoader != null) {
+ stateLoader.loadState();
+ state_loaded = true;
+ excludedResources = stateLoader.getExcludedResources();
+ } else {
+ Logger.logError("State-Loader uninitialized! Unable to restore project state.");
+ }
}
// set host-project
@@ -362,7 +364,7 @@ public static Set<IProject> getAllSupportedProjects() {
}
} catch (CoreException e) {
// TODO Auto-generated catch block
- e.printStackTrace();
+ Logger.logError(e);
}
}
return projs;
@@ -583,7 +585,12 @@ public static boolean isResourceExcluded(IResource res) {
IResource resource = res;
if (!state_loaded) {
- stateLoader.loadState();
+ IStateLoader stateLoader = getStateLoader();
+ if (stateLoader != null) {
+ stateLoader.loadState();
+ } else {
+ Logger.logError("State-Loader uninitialized! Unable to restore state.");
+ }
}
boolean isExcluded = false;
@@ -621,7 +628,7 @@ public IFile getRandomFile(String bundleName) {
IMessagesBundle bundle = messagesBundles.iterator().next();
return FileUtils.getFile(bundle);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
}
return null;
}
@@ -793,26 +800,34 @@ public Set<Locale> getProjectProvidedLocales() {
return locales;
}
- private static IStateLoader getStateLoader() {
+ public static IStateLoader getStateLoader() {
+ if (stateLoader == null) {
- IExtensionPoint extp = Platform.getExtensionRegistry()
- .getExtensionPoint(
- "org.eclipse.babel.tapiji.tools.core" + ".stateLoader");
- IConfigurationElement[] elements = extp.getConfigurationElements();
+ IExtensionPoint extp = Platform.getExtensionRegistry()
+ .getExtensionPoint(
+ "org.eclipse.babel.tapiji.tools.core"
+ + ".stateLoader");
+ IConfigurationElement[] elements = extp.getConfigurationElements();
- if (elements.length != 0) {
- try {
- return (IStateLoader) elements[0]
- .createExecutableExtension("class");
- } catch (CoreException e) {
- e.printStackTrace();
+ if (elements.length != 0) {
+ try {
+ stateLoader = (IStateLoader) elements[0]
+ .createExecutableExtension("class");
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
}
}
- return null;
+
+ return stateLoader;
+
}
public static void saveManagerState() {
- stateLoader.saveState();
+ IStateLoader stateLoader = getStateLoader();
+ if (stateLoader != null) {
+ stateLoader.saveState();
+ }
}
}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
index 56974777..d40dbd60 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
@@ -1,12 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2012 Martin Reiterer.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
+ * Copyright (c) 2012 Martin Reiterer. All rights reserved. This program and the
+ * accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
- * Contributors:
- * Martin Reiterer - initial API and implementation
+ * Contributors: Martin Reiterer - initial API and implementation
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui.decorators;
@@ -34,10 +32,6 @@ public class ExcludedResource implements ILabelDecorator,
IResourceExclusionListener {
private static final String ENTRY_SUFFIX = "[no i18n]";
- private static final Image OVERLAY_IMAGE_ON = ImageUtils
- .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON);
- private static final Image OVERLAY_IMAGE_OFF = ImageUtils
- .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF);
private final List<ILabelProviderListener> label_provider_listener = new ArrayList<ILabelProviderListener>();
public boolean decorate(Object element) {
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
index a5353e0d..b0482588 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java
@@ -10,6 +10,7 @@
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui.memento;
+import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashSet;
@@ -48,15 +49,17 @@ public class ResourceBundleManagerStateLoader implements IStateLoader {
*/
@Override
public void loadState() {
-
- excludedResources = new HashSet<IResourceDescriptor>();
- FileReader reader = null;
- try {
- reader = new FileReader(FileUtils.getRBManagerStateFile());
- loadManagerState(XMLMemento.createReadRoot(reader));
- } catch (Exception e) {
- Logger.logError(e);
- }
+
+ excludedResources = new HashSet<IResourceDescriptor>();
+ FileReader reader = null;
+ try {
+ reader = new FileReader(FileUtils.getRBManagerStateFile());
+ loadManagerState(XMLMemento.createReadRoot(reader));
+ } catch (FileNotFoundException e) {
+ Logger.logInfo("Unable to restore internationalization state. Reason: internationalization.xml not found!");
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
}
private void loadManagerState(XMLMemento memento) {
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
index 7f21d7bc..dcbabae0 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
@@ -1,12 +1,10 @@
/*******************************************************************************
- * Copyright (c) 2012 Martin Reiterer.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
+ * Copyright (c) 2012 Martin Reiterer. All rights reserved. This program and the
+ * accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
- * Contributors:
- * Martin Reiterer - initial API and implementation
+ * Contributors: Martin Reiterer - initial API and implementation
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core;
@@ -16,7 +14,15 @@
public class Logger {
public static void logInfo(String message) {
- log(IStatus.INFO, IStatus.OK, message, null);
+ log(IStatus.INFO, IStatus.INFO, message, null);
+ }
+
+ public static void logWarning(String message) {
+ log(IStatus.WARNING, IStatus.WARNING, message, null);
+ }
+
+ public static void logError(String message) {
+ log(IStatus.ERROR, IStatus.ERROR, message, null);
}
public static void logError(Throwable exception) {
@@ -24,7 +30,7 @@ public static void logError(Throwable exception) {
}
public static void logError(String message, Throwable exception) {
- log(IStatus.ERROR, IStatus.OK, message, exception);
+ log(IStatus.ERROR, IStatus.ERROR, message, exception);
}
public static void log(int severity, int code, String message,
|
03351581d05f135185ba6e487986f14667b25cbe
|
hbase
|
HBASE-4606 Remove spam in HCM and fix a- list.size == 0--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1185326 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 0645ae1adc7e..22fafea1dab9 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -623,6 +623,7 @@ Release 0.92.0 - Unreleased
HBASE-4558 Refactor TestOpenedRegionHandler and TestOpenRegionHandler.(Ram)
HBASE-4558 Addendum for TestMasterFailover (Ram) - Breaks the build
HBASE-4568 Make zk dump jsp response faster
+ HBASE-4606 Remove spam in HCM and fix a list.size == 0
TASKS
diff --git a/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java b/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
index 406e5e345493..f7fac44e8752 100644
--- a/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
+++ b/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
@@ -1400,12 +1400,9 @@ public <R> void processBatchCallback(
throw new IllegalArgumentException(
"argument results must be the same size as argument list");
}
- if (list.size() == 0) {
+ if (list.isEmpty()) {
return;
}
- if (LOG.isDebugEnabled()) {
- LOG.debug("expecting "+results.length+" results");
- }
// Keep track of the most recent servers for any given item for better
// exceptional reporting. We keep HRegionLocation to save on parsing.
|
7db99eb0da29b8106532a863da32a6bb39ae0a3b
|
camel
|
Camel fails if onCompletion has been mis- configured from Java DSL.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1040143 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/model/OnCompletionDefinition.java b/camel-core/src/main/java/org/apache/camel/model/OnCompletionDefinition.java
index cfe9ad0507d62..e1fe00927f504 100644
--- a/camel-core/src/main/java/org/apache/camel/model/OnCompletionDefinition.java
+++ b/camel-core/src/main/java/org/apache/camel/model/OnCompletionDefinition.java
@@ -141,6 +141,9 @@ public ProcessorDefinition end() {
* @return the builder
*/
public OnCompletionDefinition onCompleteOnly() {
+ if (onFailureOnly) {
+ throw new IllegalArgumentException("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: " + this);
+ }
// must define return type as OutputDefinition and not this type to avoid end user being able
// to invoke onFailureOnly/onCompleteOnly more than once
setOnCompleteOnly(Boolean.TRUE);
@@ -154,6 +157,9 @@ public OnCompletionDefinition onCompleteOnly() {
* @return the builder
*/
public OnCompletionDefinition onFailureOnly() {
+ if (onCompleteOnly) {
+ throw new IllegalArgumentException("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: " + this);
+ }
// must define return type as OutputDefinition and not this type to avoid end user being able
// to invoke onFailureOnly/onCompleteOnly more than once
setOnCompleteOnly(Boolean.FALSE);
diff --git a/camel-core/src/test/java/org/apache/camel/processor/OnCompletionInvalidConfiguredTest.java b/camel-core/src/test/java/org/apache/camel/processor/OnCompletionInvalidConfiguredTest.java
new file mode 100644
index 0000000000000..e432f0e9ea1d2
--- /dev/null
+++ b/camel-core/src/test/java/org/apache/camel/processor/OnCompletionInvalidConfiguredTest.java
@@ -0,0 +1,47 @@
+/**
+ * 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.processor;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.RouteBuilder;
+
+/**
+ * @version $Revision$
+ */
+public class OnCompletionInvalidConfiguredTest extends ContextTestSupport {
+
+ @Override
+ public boolean isUseRouteBuilder() {
+ return false;
+ }
+
+ public void testInvalidConfigured() throws Exception {
+ try {
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ onCompletion().onFailureOnly().onCompleteOnly().to("mock:foo");
+
+ from("direct:start").to("mock:result");
+ }
+ });
+ fail("Should throw exception");
+ } catch (IllegalArgumentException e) {
+ assertEquals("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: onCompletion[[]]", e.getMessage());
+ }
+ }
+}
|
b5d1d49a9aa0420d22096c898545aa349a13f07c
|
orientdb
|
Fixed issue 110 about HTTP/REST invocation of- "command" parameter passing a SELECT statement--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
index aaf8f66177b..61eaf54250b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
@@ -44,6 +44,7 @@
import com.orientechnologies.orient.core.sql.operator.OQueryOperatorContainsText;
import com.orientechnologies.orient.core.sql.operator.OQueryOperatorEquals;
import com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery;
+import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.storage.ORecordBrowsingListener;
import com.orientechnologies.orient.core.storage.impl.local.OStorageLocal;
@@ -76,7 +77,15 @@ public OCommandExecutorSQLSelect parse(final OCommandRequestText iRequest) {
init(iRequest.getDatabase(), iRequest.getText());
- request = (OSQLAsynchQuery<ORecordSchemaAware<?>>) iRequest;
+ if (iRequest instanceof OSQLAsynchQuery)
+ request = (OSQLAsynchQuery<ORecordSchemaAware<?>>) iRequest;
+ else {
+ // BUILD A QUERY OBJECT FROM THE COMMAND REQUEST
+ request = new OSQLSynchQuery<ORecordSchemaAware<?>>(iRequest.getText());
+ request.setDatabase(iRequest.getDatabase());
+ if (iRequest.getResultListener() != null)
+ request.setResultListener(iRequest.getResultListener());
+ }
int pos = extractProjections();
// TODO: IF NO PROJECTION WHAT???
@@ -156,7 +165,7 @@ record = database.load(rid);
throw new OQueryParsingException("No source found in query: specify class, clusters or single records");
processResultSet();
- return null;
+ return request instanceof OSQLSynchQuery ? ((OSQLSynchQuery<ORecordSchemaAware<?>>) request).getResult() : tempResult;
}
public boolean foreach(final ORecordInternal<?> iRecord) {
|
e62058be691ad452be79c96d0738207d34d55ea3
|
Delta Spike
|
DELTASPIKE-462 don't close the EM if we didn't open it
This happens when we use BeanManagedUserTransactionStrategy
and have a Stateless EJB call our transactional CDI beans.
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/ResourceLocalTransactionStrategy.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/ResourceLocalTransactionStrategy.java
index c363d7286..b7bd1fada 100644
--- a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/ResourceLocalTransactionStrategy.java
+++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/ResourceLocalTransactionStrategy.java
@@ -79,6 +79,7 @@ public Object execute(InvocationContext invocationContext) throws Exception
TransactionBeanStorage transactionBeanStorage = TransactionBeanStorage.getInstance();
boolean isOutermostInterceptor = transactionBeanStorage.isEmpty();
+ boolean outermostTransactionAlreadyExisted = false;
if (isOutermostInterceptor)
{
@@ -107,6 +108,10 @@ public Object execute(InvocationContext invocationContext) throws Exception
{
transaction.begin();
}
+ else if (isOutermostInterceptor)
+ {
+ outermostTransactionAlreadyExisted = true;
+ }
//don't move it before EntityTransaction#begin() and invoke it in any case
beforeProceed(entityManagerEntry);
@@ -125,25 +130,15 @@ public Object execute(InvocationContext invocationContext) throws Exception
Set<EntityManagerEntry> entityManagerEntryList =
transactionBeanStorage.getUsedEntityManagerEntries();
- for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList)
+ if (!outermostTransactionAlreadyExisted)
{
- EntityTransaction transaction = getTransaction(currentEntityManagerEntry);
- if (transaction != null && transaction.isActive())
- {
- try
- {
- transaction.rollback();
- }
- catch (Exception eRollback)
- {
- if (LOGGER.isLoggable(Level.SEVERE))
- {
- LOGGER.log(Level.SEVERE,
- "Got additional Exception while subsequently " +
- "rolling back other SQL transactions", eRollback);
- }
- }
- }
+ // We only commit transactions we opened ourselfs.
+ // If the transaction got opened outside of our interceptor chain
+ // we must not handle it.
+ // This e.g. happens if a Stateless EJB invokes a Transactional CDI bean
+ // which uses the BeanManagedUserTransactionStrategy.
+
+ rollbackAllTransactions(entityManagerEntryList);
}
// drop all EntityManagers from the request-context cache
@@ -163,73 +158,85 @@ public Object execute(InvocationContext invocationContext) throws Exception
boolean commitFailed = false;
// commit all open transactions in the outermost interceptor!
- // this is a 'JTA for poor men' only, and will not guaranty
+ // For Resource-local this is a 'JTA for poor men' only, and will not guaranty
// commit stability over various databases!
+ // In case of JTA we will just commit the UserTransaction.
if (isOutermostInterceptor)
{
- // only commit all transactions if we didn't rollback
- // them already
- if (firstException == null)
+ if (!outermostTransactionAlreadyExisted)
{
- Set<EntityManagerEntry> entityManagerEntryList =
- transactionBeanStorage.getUsedEntityManagerEntries();
+ // We only commit transactions we opened ourselfs.
+ // If the transaction got opened outside of our interceptor chain
+ // we must not handle it.
+ // This e.g. happens if a Stateless EJB invokes a Transactional CDI bean
+ // which uses the BeanManagedUserTransactionStrategy.
- boolean rollbackOnly = false;
- // but first try to flush all the transactions and write the updates to the database
- for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList)
+ if (firstException == null)
{
- EntityTransaction transaction = getTransaction(currentEntityManagerEntry);
- if (transaction != null && transaction.isActive())
+ // only commit all transactions if we didn't rollback
+ // them already
+ Set<EntityManagerEntry> entityManagerEntryList =
+ transactionBeanStorage.getUsedEntityManagerEntries();
+
+ boolean rollbackOnly = false;
+ // but first try to flush all the transactions and write the updates to the database
+ for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList)
{
- try
+ EntityTransaction transaction = getTransaction(currentEntityManagerEntry);
+ if (transaction != null && transaction.isActive())
{
- if (!commitFailed)
+ try
{
- currentEntityManagerEntry.getEntityManager().flush();
-
- if (!rollbackOnly && transaction.getRollbackOnly())
+ if (!commitFailed)
{
- //don't set commitFailed to true directly
- //(the order of the entity-managers isn't deterministic -> tests would break)
- rollbackOnly = true;
+ currentEntityManagerEntry.getEntityManager().flush();
+
+ if (!rollbackOnly && transaction.getRollbackOnly())
+ {
+ // don't set commitFailed to true directly
+ // (the order of the entity-managers isn't deterministic
+ // -> tests would break)
+ rollbackOnly = true;
+ }
}
}
- }
- catch (Exception e)
- {
- firstException = e;
- commitFailed = true;
- break;
+ catch (Exception e)
+ {
+ firstException = e;
+ commitFailed = true;
+ break;
+ }
}
}
- }
- if (rollbackOnly)
- {
- commitFailed = true;
- }
+ if (rollbackOnly)
+ {
+ commitFailed = true;
+ }
- // and now either commit or rollback all transactions
- for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList)
- {
- EntityTransaction transaction = getTransaction(currentEntityManagerEntry);
- if (transaction != null && transaction.isActive())
+ // and now either commit or rollback all transactions
+ for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList)
{
- try
+ EntityTransaction transaction = getTransaction(currentEntityManagerEntry);
+ if (transaction != null && transaction.isActive())
{
- if (commitFailed || transaction.getRollbackOnly() /*last chance to check it (again)*/)
+ try
{
- transaction.rollback();
+ // last chance to check it (again)
+ if (commitFailed || transaction.getRollbackOnly())
+ {
+ transaction.rollback();
+ }
+ else
+ {
+ transaction.commit();
+ }
}
- else
+ catch (Exception e)
{
- transaction.commit();
+ firstException = e;
+ commitFailed = true;
}
}
- catch (Exception e)
- {
- firstException = e;
- commitFailed = true;
- }
}
}
}
@@ -248,6 +255,30 @@ public Object execute(InvocationContext invocationContext) throws Exception
}
}
+ private void rollbackAllTransactions(Set<EntityManagerEntry> entityManagerEntryList)
+ {
+ for (EntityManagerEntry currentEntityManagerEntry : entityManagerEntryList)
+ {
+ EntityTransaction transaction = getTransaction(currentEntityManagerEntry);
+ if (transaction != null && transaction.isActive())
+ {
+ try
+ {
+ transaction.rollback();
+ }
+ catch (Exception eRollback)
+ {
+ if (LOGGER.isLoggable(Level.SEVERE))
+ {
+ LOGGER.log(Level.SEVERE,
+ "Got additional Exception while subsequently " +
+ "rolling back other SQL transactions", eRollback);
+ }
+ }
+ }
+ }
+ }
+
protected EntityManagerEntry createEntityManagerEntry(
EntityManager entityManager, Class<? extends Annotation> qualifier)
{
diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/context/EntityManagerEntry.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/context/EntityManagerEntry.java
index 811bf619d..c37dc7224 100644
--- a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/context/EntityManagerEntry.java
+++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/context/EntityManagerEntry.java
@@ -24,7 +24,6 @@
/**
* Stores a {@link EntityManager} and the qualifier
- * @deprecated we shall rather introduce an own QualifierMap or a ComparableQualifier which checks Nonbinding
*/
@Typed()
public class EntityManagerEntry
|
a6fa02a07fe374204e9e02914ccf1cc9812aa5ba
|
restlet-framework-java
|
- Initial code for new default HTTP connector and- SIP connector.--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java b/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java
index 8631b810ca..a0b89ae9c7 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java
@@ -1037,10 +1037,12 @@ public void writeMessages() {
}
}
- writeMessage(message);
+ if (message != null) {
+ writeMessage(message);
- if (getState() == ConnectionState.CLOSING) {
- close(true);
+ if (getState() == ConnectionState.CLOSING) {
+ close(true);
+ }
}
}
} catch (Exception e) {
|
954582943efddc51245c74ebeaeb1b218aa05668
|
restlet-framework-java
|
- Refactored WADL extension based on John- Logsdon feed-back. Add convenience methods and constructors on- MethodInfo and RepresentationInfo. Removed unecessary methods on - WadlResource like getRepresentationInfo(Variant) and - getParametersInfo(RequestInfo|ResponseInfo|Representation- Info).--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt
index 2d0bc382b8..e9142e9d0e 100644
--- a/build/tmpl/text/changes.txt
+++ b/build/tmpl/text/changes.txt
@@ -15,7 +15,12 @@ Changes log
- Added the ability to provide Wadl documentation to any
Restlet instances.
- NRE and Extension Enhancements
- -
+ - Refactored WADL extension based on John Logsdon feed-back.
+ Add convenience methods and constructors on MethodInfo and
+ RepresentationInfo. Removed unecessary methods on
+ WadlResource like getRepresentationInfo(Variant) and
+ getParametersInfo(RequestInfo|ResponseInfo|Representation-
+ Info).
- Misc
-
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
index 4b720dd46f..5ac681ffc5 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
@@ -34,6 +34,7 @@
import org.restlet.data.Method;
import org.restlet.data.Reference;
+import org.restlet.resource.Variant;
import org.restlet.util.XmlWriter;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
@@ -97,6 +98,78 @@ public MethodInfo(String documentation) {
super(documentation);
}
+ /**
+ * Adds a new request parameter.
+ *
+ * @param name
+ * The name of the parameter.
+ * @param required
+ * True if thes parameter is required.
+ * @param type
+ * The type of the parameter.
+ * @param style
+ * The style of the parameter.
+ * @param documentation
+ * A single documentation element.
+ * @return The created parameter description.
+ */
+ public ParameterInfo addRequestParameter(String name, boolean required,
+ String type, ParameterStyle style, String documentation) {
+ ParameterInfo result = new ParameterInfo(name, required, type, style,
+ documentation);
+ getRequest().getParameters().add(result);
+ return result;
+ }
+
+ /**
+ * Adds a new request representation based on a given variant.
+ *
+ * @param variant
+ * The variant to describe.
+ * @return The created representation description.
+ */
+ public RepresentationInfo addRequestRepresentation(Variant variant) {
+ RepresentationInfo result = new RepresentationInfo(variant);
+ getRequest().getRepresentations().add(result);
+ return result;
+ }
+
+ /**
+ * Adds a new response parameter.
+ *
+ * @param name
+ * The name of the parameter.
+ * @param required
+ * True if thes parameter is required.
+ * @param type
+ * The type of the parameter.
+ * @param style
+ * The style of the parameter.
+ * @param documentation
+ * A single documentation element.
+ * @return The created parameter description.
+ */
+ public ParameterInfo addResponseParameter(String name, boolean required,
+ String type, ParameterStyle style, String documentation) {
+ ParameterInfo result = new ParameterInfo(name, required, type, style,
+ documentation);
+ getResponse().getParameters().add(result);
+ return result;
+ }
+
+ /**
+ * Adds a new response representation based on a given variant.
+ *
+ * @param variant
+ * The variant to describe.
+ * @return The created representation description.
+ */
+ public RepresentationInfo addResponseRepresentation(Variant variant) {
+ RepresentationInfo result = new RepresentationInfo(variant);
+ getResponse().getRepresentations().add(result);
+ return result;
+ }
+
/**
* Returns the identifier for the method.
*
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/RepresentationInfo.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/RepresentationInfo.java
index 48ff697de8..d63d13d7d0 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/RepresentationInfo.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/RepresentationInfo.java
@@ -37,6 +37,7 @@
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Status;
+import org.restlet.resource.Variant;
import org.restlet.util.XmlWriter;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
@@ -105,6 +106,16 @@ public RepresentationInfo(String documentation) {
super(documentation);
}
+ /**
+ * Constructor with a variant.
+ *
+ * @param variant
+ * The variant to describe.
+ */
+ public RepresentationInfo(Variant variant) {
+ setMediaType(variant.getMediaType());
+ }
+
/**
* Returns the identifier for that element.
*
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlResource.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlResource.java
index 62967f02f8..0e3f526d6a 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlResource.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlResource.java
@@ -196,16 +196,10 @@ protected void describeDelete(MethodInfo methodInfo) {
* The method description to update.
*/
protected void describeGet(MethodInfo methodInfo) {
- ResponseInfo responseInfo = new ResponseInfo();
-
// Describe each variant
for (final Variant variant : getVariants()) {
- responseInfo.getRepresentations().add(
- getRepresentationInfo(variant));
+ methodInfo.addResponseRepresentation(variant);
}
-
- methodInfo.setResponse(responseInfo);
-
}
/**
@@ -218,6 +212,8 @@ protected void describeGet(MethodInfo methodInfo) {
*/
protected void describeMethod(Method method, MethodInfo methodInfo) {
methodInfo.setName(method);
+ methodInfo.setRequest(new RequestInfo());
+ methodInfo.setResponse(new ResponseInfo());
if (Method.GET.equals(method)) {
describeGet(methodInfo);
@@ -241,15 +237,10 @@ protected void describeMethod(Method method, MethodInfo methodInfo) {
* The method description to update.
*/
protected void describeOptions(MethodInfo methodInfo) {
- ResponseInfo responseInfo = new ResponseInfo();
-
// Describe each variant
for (final Variant variant : getWadlVariants()) {
- responseInfo.getRepresentations().add(
- getRepresentationInfo(variant));
+ methodInfo.addResponseRepresentation(variant);
}
-
- methodInfo.setResponse(responseInfo);
}
/**
@@ -281,46 +272,6 @@ protected List<ParameterInfo> getParametersInfo() {
return result;
}
- /**
- * Returns the description of the parameters of the given representation.
- * Returns null by default.
- *
- * @param representation
- * The parent representation.
- * @return The description of the parameters.
- */
- protected List<ParameterInfo> getParametersInfo(
- RepresentationInfo representation) {
- final List<ParameterInfo> result = null;
- return result;
- }
-
- /**
- * Returns the description of the parameters of the given request. Returns
- * null by default.
- *
- * @param request
- * The parent request.
- * @return The description of the parameters.
- */
- protected List<ParameterInfo> getParametersInfo(RequestInfo request) {
- final List<ParameterInfo> result = null;
- return result;
- }
-
- /**
- * Returns the description of the parameters of the given response. Returns
- * null by default.
- *
- * @param response
- * The parent response.
- * @return The description of the parameters.
- */
- protected List<ParameterInfo> getParametersInfo(ResponseInfo response) {
- final List<ParameterInfo> result = null;
- return result;
- }
-
/**
* Returns the preferred WADL variant according to the client preferences
* specified in the request.
@@ -345,20 +296,6 @@ protected Variant getPreferredWadlVariant() {
return result;
}
- /**
- * Returns a WADL description for a given variant.
- *
- * @param variant
- * The variant to describe.
- * @return The variant description.
- */
- protected RepresentationInfo getRepresentationInfo(Variant variant) {
- final RepresentationInfo result = new RepresentationInfo();
- result.setMediaType(variant.getMediaType());
- result.setParameters(getParametersInfo(result));
- return result;
- }
-
/**
* Returns the resource's relative path.
*
|
6ebe0c30ec99df77b9d9260e8dda5d0d9a975877
|
kotlin
|
fix KT-9299 In a project with circular- dependencies between modules
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/common/moduleVisibilityImpl.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/common/moduleVisibilityImpl.kt
index 2000ecc8421ce..7b9f68cef34b7 100644
--- a/compiler/cli/src/org/jetbrains/kotlin/cli/common/moduleVisibilityImpl.kt
+++ b/compiler/cli/src/org/jetbrains/kotlin/cli/common/moduleVisibilityImpl.kt
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.load.kotlin.ModuleVisibilityManager
import org.jetbrains.kotlin.load.kotlin.getSourceElement
import org.jetbrains.kotlin.load.kotlin.isContainedByCompiledPartOfOurModule
import org.jetbrains.kotlin.modules.Module
+import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.util.ModuleVisibilityHelper
@@ -44,8 +45,18 @@ class ModuleVisibilityHelperImpl : ModuleVisibilityHelper {
val moduleVisibilityManager = ModuleVisibilityManager.SERVICE.getInstance(project)
+ fun findModule(kotlinFile: KtFile): Module? = moduleVisibilityManager.chunk.firstOrNull { it.getSourceFiles().containsRaw(kotlinFile.virtualFile.path) }
+
val whatSource = getSourceElement(what)
- if (whatSource is KotlinSourceElement) return true
+ if (whatSource is KotlinSourceElement) {
+ if (moduleVisibilityManager.chunk.size > 1 && fromSource is KotlinSourceElement) {
+ val fromSourceKotlinFile = fromSource.psi.getContainingJetFile()
+ val whatSourceKotlinFile = whatSource.psi.getContainingJetFile()
+ return findModule(whatSourceKotlinFile) === findModule(fromSourceKotlinFile)
+ }
+
+ return true
+ }
moduleVisibilityManager.friendPaths.forEach {
if (isContainedByCompiledPartOfOurModule(what, File(it))) return true
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt
index 613aee751284c..338506b33d371 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt
@@ -29,6 +29,7 @@ import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.receivers.QualifierReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
+import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.resolve.validation.SymbolUsageValidator
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.check
@@ -122,11 +123,19 @@ public class QualifiedExpressionResolver(val symbolUsageValidator: SymbolUsageVa
val importedReference = importDirective.importedReference ?: return null
val path = importedReference.asQualifierPartList(trace)
val lastPart = path.lastOrNull() ?: return null
+ val packageFragmentForCheck =
+ if (packageFragmentForVisibilityCheck is DeclarationDescriptorWithSource && packageFragmentForVisibilityCheck.source == SourceElement.NO_SOURCE) {
+ PackageFragmentWithCustomSource(packageFragmentForVisibilityCheck, KotlinSourceElement(importDirective.getContainingJetFile()))
+ }
+
+ else {
+ packageFragmentForVisibilityCheck
+ }
if (!importDirective.isAllUnder) {
- return processSingleImport(moduleDescriptor, trace, importDirective, path, lastPart, packageFragmentForVisibilityCheck)
+ return processSingleImport(moduleDescriptor, trace, importDirective, path, lastPart, packageFragmentForCheck)
}
- val packageOrClassDescriptor = resolveToPackageOrClass(path, moduleDescriptor, trace, packageFragmentForVisibilityCheck,
+ val packageOrClassDescriptor = resolveToPackageOrClass(path, moduleDescriptor, trace, packageFragmentForCheck,
scopeForFirstPart = null, inImport = true) ?: return null
if (packageOrClassDescriptor is ClassDescriptor && packageOrClassDescriptor.kind.isSingleton) {
trace.report(Errors.CANNOT_ALL_UNDER_IMPORT_FROM_SINGLETON.on(lastPart.expression, packageOrClassDescriptor)) // todo report on star
@@ -398,8 +407,17 @@ public class QualifiedExpressionResolver(val symbolUsageValidator: SymbolUsageVa
symbolUsageValidator.validateTypeUsage(descriptor, trace, referenceExpression)
}
- if (descriptor is DeclarationDescriptorWithVisibility && !isVisible(descriptor, shouldBeVisibleFrom, inImport)) {
- trace.report(Errors.INVISIBLE_REFERENCE.on(referenceExpression, descriptor, descriptor.visibility, descriptor))
+ if (descriptor is DeclarationDescriptorWithVisibility) {
+ val fromToCheck =
+ if (shouldBeVisibleFrom is PackageFragmentDescriptor && shouldBeVisibleFrom.source == SourceElement.NO_SOURCE) {
+ PackageFragmentWithCustomSource(shouldBeVisibleFrom, KotlinSourceElement(referenceExpression.getContainingJetFile()))
+ }
+ else {
+ shouldBeVisibleFrom
+ }
+ if (!isVisible(descriptor, fromToCheck, inImport)) {
+ trace.report(Errors.INVISIBLE_REFERENCE.on(referenceExpression, descriptor, descriptor.visibility, descriptor))
+ }
}
if (isQualifier) {
@@ -429,3 +447,11 @@ public class QualifiedExpressionResolver(val symbolUsageValidator: SymbolUsageVa
return Visibilities.isVisible(ReceiverValue.IRRELEVANT_RECEIVER, descriptor, shouldBeVisibleFrom)
}
}
+
+/*
+ This purpose of this class is to pass information about source file for current package fragment in order for check visibilities between modules
+ (see ModuleVisibilityHelperImpl.isInFriendModule).
+ */
+private class PackageFragmentWithCustomSource(private val original: PackageFragmentDescriptor, private val source: SourceElement) : PackageFragmentDescriptor by original {
+ override fun getSource(): SourceElement = source
+}
diff --git a/jps-plugin/test/org/jetbrains/kotlin/jps/build/IncrementalJpsTestGenerated.java b/jps-plugin/test/org/jetbrains/kotlin/jps/build/IncrementalJpsTestGenerated.java
index 00730fed6a476..896dbdd010d82 100644
--- a/jps-plugin/test/org/jetbrains/kotlin/jps/build/IncrementalJpsTestGenerated.java
+++ b/jps-plugin/test/org/jetbrains/kotlin/jps/build/IncrementalJpsTestGenerated.java
@@ -79,6 +79,18 @@ public void testSimpleDependency() throws Exception {
doTest(fileName);
}
+ @TestMetadata("simpleDependencyErrorOnAccessToInternal1")
+ public void testSimpleDependencyErrorOnAccessToInternal1() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/");
+ doTest(fileName);
+ }
+
+ @TestMetadata("simpleDependencyErrorOnAccessToInternal2")
+ public void testSimpleDependencyErrorOnAccessToInternal2() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/");
+ doTest(fileName);
+ }
+
@TestMetadata("simpleDependencyUnchanged")
public void testSimpleDependencyUnchanged() throws Exception {
String fileName = JetTestUtils.navigationMetadata("jps-plugin/testData/incremental/multiModule/simpleDependencyUnchanged/");
diff --git a/jps-plugin/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt b/jps-plugin/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt
index f5fe840ffaaa4..b4264cd694ac8 100644
--- a/jps-plugin/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt
+++ b/jps-plugin/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt
@@ -494,20 +494,14 @@ public class KotlinJpsBuildTest : AbstractKotlinJpsBuildTestCase() {
initProject()
val result = makeAll()
result.assertFailed()
-
- val actualErrors = result.getMessages(BuildMessage.Kind.ERROR)
- .map { it as CompilerMessage }
- .map { "${it.messageText} at line ${it.line}, column ${it.column}" }.sorted().joinToString("\n")
- val projectRoot = File(AbstractKotlinJpsBuildTestCase.TEST_DATA_PATH + "general/" + getTestName(false))
- val expectedFile = File(projectRoot, "errors.txt")
- JetTestUtils.assertEqualsToFile(expectedFile, actualErrors)
+ result.checkErrors()
}
- // TODO See KT-9299 In a project with circular dependencies between modules, IDE reports error on use of internal class from another module, but the corresponding code still compiles and runs.
public fun testCircularDependenciesInternalFromAnotherModule() {
initProject()
val result = makeAll()
- result.assertSuccessful()
+ result.assertFailed()
+ result.checkErrors()
}
public fun testCircularDependencyWithReferenceToOldVersionLib() {
@@ -679,6 +673,15 @@ public class KotlinJpsBuildTest : AbstractKotlinJpsBuildTestCase() {
assertFalse(File(storageRoot, "targets/java-production/module2/kotlin").exists())
}
+ private fun BuildResult.checkErrors() {
+ val actualErrors = getMessages(BuildMessage.Kind.ERROR)
+ .map { it as CompilerMessage }
+ .map { "${it.messageText} at line ${it.line}, column ${it.column}" }.sorted().joinToString("\n")
+ val projectRoot = File(AbstractKotlinJpsBuildTestCase.TEST_DATA_PATH + "general/" + getTestName(false))
+ val expectedFile = File(projectRoot, "errors.txt")
+ JetTestUtils.assertEqualsToFile(expectedFile, actualErrors)
+ }
+
private fun buildCustom(canceledStatus: CanceledStatus, logger: TestProjectBuilderLogger,buildResult: BuildResult) {
val scopeBuilder = CompileScopeTestBuilder.make().all()
val descriptor = this.createProjectDescriptor(BuildLoggingManager(logger))
diff --git a/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/errors.txt b/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/errors.txt
new file mode 100644
index 0000000000000..331aaf1316d76
--- /dev/null
+++ b/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/errors.txt
@@ -0,0 +1,7 @@
+'internal open val member: kotlin.Int defined in test.ClassBB1' has no access to 'internal abstract val member: kotlin.Int defined in test.ClassB1', so it cannot override it at line 14, column 14
+Cannot access 'InternalClass1': it is 'internal' in 'test' at line 5, column 13
+Cannot access 'InternalClass1': it is 'internal' in 'test' at line 8, column 36
+Cannot access 'InternalClass2': it is 'internal' in 'test' at line 19, column 15
+Cannot access 'InternalClassAnnotation': it is 'internal' in 'test' at line 10, column 2
+Cannot access 'InternalFileAnnotation': it is 'internal' in 'test' at line 1, column 7
+Cannot access 'member': it is 'invisible_fake' in 'ClassAA1' at line 27, column 25
\ No newline at end of file
diff --git a/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/module1/src/module1.kt b/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/module1/src/module1.kt
index 30fcc94d78088..9a7bdb153a3d6 100644
--- a/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/module1/src/module1.kt
+++ b/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/module1/src/module1.kt
@@ -2,9 +2,18 @@ package test
internal open class InternalClass1
+@Target(AnnotationTarget.FILE)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class InternalFileAnnotation()
+
+@Target(AnnotationTarget.CLASS)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class InternalClassAnnotation()
+
abstract class ClassA1(internal val member: Int)
abstract class ClassB1 {
internal abstract val member: Int
}
+class ClassD: InternalClass2()
\ No newline at end of file
diff --git a/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/module2/src/module2.kt b/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/module2/src/module2.kt
index 1f1647ddad4dc..ece01121bd2cc 100644
--- a/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/module2/src/module2.kt
+++ b/jps-plugin/testData/general/CircularDependenciesInternalFromAnotherModule/module2/src/module2.kt
@@ -1,11 +1,13 @@
-// ERROR: 'internal open val member: kotlin.Int defined in test.ClassBB1' has no access to 'internal abstract val member: kotlin.Int defined in test.ClassB1', so it cannot override it
-// ERROR: Cannot access 'InternalClass1': it is 'internal' in 'test'
-// ERROR: Cannot access 'member': it is 'invisible_fake' in 'ClassAA1'
+@file:InternalFileAnnotation
+
package test
+import test.InternalClass1
+
// InternalClass1, ClassA1, ClassB1 are in module1
class ClassInheritedFromInternal1: InternalClass1()
+@InternalClassAnnotation
class ClassAA1 : ClassA1(10)
class ClassBB1 : ClassB1() {
diff --git a/jps-plugin/testData/general/InternalFromAnotherModule/errors.txt b/jps-plugin/testData/general/InternalFromAnotherModule/errors.txt
index 13cd0c3cbf138..2fae260968a70 100644
--- a/jps-plugin/testData/general/InternalFromAnotherModule/errors.txt
+++ b/jps-plugin/testData/general/InternalFromAnotherModule/errors.txt
@@ -1,4 +1,6 @@
-'internal open val member: kotlin.Int defined in test.ClassBB1' has no access to 'internal abstract val member: kotlin.Int defined in test.ClassB1', so it cannot override it at line 11, column 14
-Cannot access 'InternalClass1': it is 'internal' in 'test' at line 3, column 13
-Cannot access 'InternalClass1': it is 'internal' in 'test' at line 6, column 36
-Cannot access 'member': it is 'invisible_fake' in 'ClassAA1' at line 24, column 25
\ No newline at end of file
+'internal open val member: kotlin.Int defined in test.ClassBB1' has no access to 'internal abstract val member: kotlin.Int defined in test.ClassB1', so it cannot override it at line 14, column 14
+Cannot access 'InternalClass1': it is 'internal' in 'test' at line 5, column 13
+Cannot access 'InternalClass1': it is 'internal' in 'test' at line 8, column 36
+Cannot access 'InternalClassAnnotation': it is 'internal' in 'test' at line 10, column 2
+Cannot access 'InternalTestAnnotation': it is 'internal' in 'test' at line 1, column 7
+Cannot access 'member': it is 'invisible_fake' in 'ClassAA1' at line 27, column 25
\ No newline at end of file
diff --git a/jps-plugin/testData/general/InternalFromAnotherModule/module1/src/module1.kt b/jps-plugin/testData/general/InternalFromAnotherModule/module1/src/module1.kt
index 30fcc94d78088..e2fc0309302f5 100644
--- a/jps-plugin/testData/general/InternalFromAnotherModule/module1/src/module1.kt
+++ b/jps-plugin/testData/general/InternalFromAnotherModule/module1/src/module1.kt
@@ -1,4 +1,13 @@
package test
+@Target(AnnotationTarget.FILE)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class InternalTestAnnotation()
+
+@Target(AnnotationTarget.CLASS)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class InternalClassAnnotation()
+
+private class PrivateClass1
internal open class InternalClass1
diff --git a/jps-plugin/testData/general/InternalFromAnotherModule/module2/src/module2.kt b/jps-plugin/testData/general/InternalFromAnotherModule/module2/src/module2.kt
index 64f4bb6cf1f45..155a4c3a341a9 100644
--- a/jps-plugin/testData/general/InternalFromAnotherModule/module2/src/module2.kt
+++ b/jps-plugin/testData/general/InternalFromAnotherModule/module2/src/module2.kt
@@ -1,3 +1,5 @@
+@file:InternalTestAnnotation
+
package test
import test.InternalClass1
@@ -5,6 +7,7 @@ import test.InternalClass1
// InternalClass1, ClassA1, ClassB1 are in module1
class ClassInheritedFromInternal1: InternalClass1()
+@InternalClassAnnotation
class ClassAA1 : ClassA1(10)
class ClassBB1 : ClassB1() {
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/build.log b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/build.log
new file mode 100644
index 0000000000000..df01db10bfd62
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/build.log
@@ -0,0 +1,26 @@
+Cleaning output files:
+out/production/module1/META-INF/module1.kotlin_module
+out/production/module1/a/A.class
+out/production/module1/a/ClassAnnotation.class
+out/production/module1/a/FileAnnotation.class
+out/production/module1/a/Module1_aKt.class
+End of files
+Compiling files:
+module1/src/module1_a.kt
+End of files
+Cleaning output files:
+out/production/module2/META-INF/module2.kotlin_module
+out/production/module2/b/B.class
+out/production/module2/b/Module2_bKt.class
+End of files
+Compiling files:
+module2/src/module2_b.kt
+End of files
+COMPILATION FAILED
+Cannot access 'FileAnnotation': it is 'internal' in 'a'
+Cannot access 'A': it is 'internal' in 'a'
+Cannot access 'FileAnnotation': it is 'internal' in 'a'
+Cannot access 'ClassAnnotation': it is 'internal' in 'a'
+Cannot access 'ClassAnnotation': it is 'internal' in 'a'
+Cannot access 'A': it is 'internal' in 'a'
+Cannot access 'a': it is 'internal' in 'a'
\ No newline at end of file
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/dependencies.txt b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/dependencies.txt
new file mode 100644
index 0000000000000..827bf04cc589b
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/dependencies.txt
@@ -0,0 +1,2 @@
+module1->
+module2->module1
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module1_a.kt b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module1_a.kt
new file mode 100644
index 0000000000000..621ede2ee51bf
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module1_a.kt
@@ -0,0 +1,14 @@
+package a
+
+@Target(AnnotationTarget.FILE)
+@Retention(AnnotationRetention.SOURCE)
+annotation class FileAnnotation()
+
+@Target(AnnotationTarget.CLASS)
+@Retention(AnnotationRetention.SOURCE)
+annotation class ClassAnnotation()
+
+class A
+
+fun a() {
+}
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module1_a.kt.new b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module1_a.kt.new
new file mode 100644
index 0000000000000..e514959008cac
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module1_a.kt.new
@@ -0,0 +1,15 @@
+package a
+
+@Target(AnnotationTarget.FILE)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class FileAnnotation()
+
+@Target(AnnotationTarget.CLASS)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class ClassAnnotation()
+
+internal class A
+
+internal fun a(): String {
+ return ":)"
+}
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module2_b.kt b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module2_b.kt
new file mode 100644
index 0000000000000..9573f5d051783
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module2_b.kt
@@ -0,0 +1,13 @@
+@file:FileAnnotation
+package b
+
+import a.A
+import a.FileAnnotation
+import a.ClassAnnotation
+
+@ClassAnnotation
+class B
+
+fun b(param: a.A) {
+ a.a()
+}
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module2_c.kt b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module2_c.kt
new file mode 100644
index 0000000000000..c4fab8fb00b47
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal1/module2_c.kt
@@ -0,0 +1,5 @@
+package c
+
+fun c() {
+ // This file doesn't use anything from module1, so it won't be recompiled after change
+}
\ No newline at end of file
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/build.log b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/build.log
new file mode 100644
index 0000000000000..1a5350845e0b1
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/build.log
@@ -0,0 +1,26 @@
+Cleaning output files:
+out/production/module1/META-INF/module1.kotlin_module
+out/production/module1/a/A.class
+out/production/module1/a/InternalA.class
+out/production/module1/a/InternalClassAnnotation.class
+out/production/module1/a/InternalFileAnnotation.class
+out/production/module1/a/Module1_aKt.class
+End of files
+Compiling files:
+module1/src/module1_a.kt
+End of files
+Cleaning output files:
+out/production/module2/META-INF/module2.kotlin_module
+out/production/module2/b/B.class
+out/production/module2/b/Module2_bKt.class
+End of files
+Compiling files:
+module2/src/module2_b.kt
+End of files
+COMPILATION FAILED
+Cannot access 'InternalFileAnnotation': it is 'internal' in 'a'
+Cannot access 'InternalFileAnnotation': it is 'internal' in 'a'
+Cannot access 'InternalClassAnnotation': it is 'internal' in 'a'
+Cannot access 'InternalClassAnnotation': it is 'internal' in 'a'
+Unresolved reference: InternalA
+Unresolved reference: internalA
\ No newline at end of file
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/dependencies.txt b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/dependencies.txt
new file mode 100644
index 0000000000000..827bf04cc589b
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/dependencies.txt
@@ -0,0 +1,2 @@
+module1->
+module2->module1
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module1_a.kt b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module1_a.kt
new file mode 100644
index 0000000000000..e7392045a0bc3
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module1_a.kt
@@ -0,0 +1,19 @@
+package a
+
+@Target(AnnotationTarget.FILE)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class InternalFileAnnotation()
+
+@Target(AnnotationTarget.CLASS)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class InternalClassAnnotation()
+
+class A
+
+internal class InternalA
+
+fun a() {
+}
+
+internal fun internalA() {
+}
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module1_a.kt.new b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module1_a.kt.new
new file mode 100644
index 0000000000000..bc69686475069
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module1_a.kt.new
@@ -0,0 +1,19 @@
+package a
+
+@Target(AnnotationTarget.FILE)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class InternalFileAnnotation()
+
+@Target(AnnotationTarget.CLASS)
+@Retention(AnnotationRetention.SOURCE)
+internal annotation class InternalClassAnnotation()
+
+class A
+
+internal class AA
+
+fun a() {
+}
+
+internal fun aa() {
+}
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_b.kt b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_b.kt
new file mode 100644
index 0000000000000..436721358e970
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_b.kt
@@ -0,0 +1,7 @@
+package b
+
+class B
+
+fun b(param: a.A) {
+ a.a()
+}
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_b.kt.new b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_b.kt.new
new file mode 100644
index 0000000000000..961d6541b9c5a
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_b.kt.new
@@ -0,0 +1,12 @@
+@file:InternalFileAnnotation
+package b
+
+import a.InternalFileAnnotation
+import a.InternalClassAnnotation
+
+@InternalClassAnnotation
+class B
+
+fun b(param: a.InternalA) {
+ a.internalA()
+}
diff --git a/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_c.kt b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_c.kt
new file mode 100644
index 0000000000000..c4fab8fb00b47
--- /dev/null
+++ b/jps-plugin/testData/incremental/multiModule/simpleDependencyErrorOnAccessToInternal2/module2_c.kt
@@ -0,0 +1,5 @@
+package c
+
+fun c() {
+ // This file doesn't use anything from module1, so it won't be recompiled after change
+}
\ No newline at end of file
|
ff7d4eebd8ebbf011656313dca8c6ee1a598c2aa
|
spring-framework
|
Polish AbstractHandlerMethodMapping---
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
index c463ee1fcb85..367dcb765bf7 100644
--- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
+++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
@@ -390,10 +390,15 @@ protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpSer
/**
* Retrieve the CORS configuration for the given handler.
+ * @param handler the handler to check (never {@code null}).
+ * @param request the current request.
+ * @return the CORS configuration for the handler or {@code null}.
*/
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
- handler = (handler instanceof HandlerExecutionChain) ? ((HandlerExecutionChain) handler).getHandler() : handler;
- if (handler != null && handler instanceof CorsConfigurationSource) {
+ if (handler instanceof HandlerExecutionChain) {
+ handler = ((HandlerExecutionChain) handler).getHandler();
+ }
+ if (handler instanceof CorsConfigurationSource) {
return ((CorsConfigurationSource) handler).getCorsConfiguration(request);
}
return null;
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
index 9a36308ce00d..4fc653eb8b7a 100644
--- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
+++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
@@ -83,7 +83,7 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
private final MultiValueMap<String, HandlerMethod> nameMap = new LinkedMultiValueMap<String, HandlerMethod>();
- private final Map<Method, CorsConfiguration> corsConfigurations = new LinkedHashMap<Method, CorsConfiguration>();
+ private final Map<Method, CorsConfiguration> corsMap = new LinkedHashMap<Method, CorsConfiguration>();
/**
@@ -113,20 +113,6 @@ public Map<T, HandlerMethod> getHandlerMethods() {
return Collections.unmodifiableMap(this.handlerMethods);
}
- protected Map<Method, CorsConfiguration> getCorsConfigurations() {
- return corsConfigurations;
- }
-
- @Override
- protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
- CorsConfiguration config = super.getCorsConfiguration(handler, request);
- if (config == null && handler instanceof HandlerMethod) {
- HandlerMethod handlerMethod = (HandlerMethod)handler;
- config = this.getCorsConfigurations().get(handlerMethod.getMethod());
- }
- return config;
- }
-
/**
* Return the handler methods mapped to the mapping with the given name.
* @param mappingName the mapping name
@@ -159,10 +145,9 @@ protected void initHandlerMethods() {
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class));
- for (String beanName : beanNames) {
- if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX) &&
- isHandler(getApplicationContext().getType(beanName))){
- detectHandlerMethods(beanName);
+ for (String name : beanNames) {
+ if (!name.startsWith(SCOPED_TARGET_NAME_PREFIX) && isHandler(getApplicationContext().getType(name))) {
+ detectHandlerMethods(name);
}
}
registerMultiMatchCorsConfiguration();
@@ -175,7 +160,7 @@ private void registerMultiMatchCorsConfiguration() {
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);
- this.corsConfigurations.put(PREFLIGHT_MULTI_MATCH_HANDLER_METHOD.getMethod(), config);
+ this.corsMap.put(PREFLIGHT_MULTI_MATCH_HANDLER_METHOD.getMethod(), config);
}
/**
@@ -262,7 +247,7 @@ protected void registerHandlerMethod(Object handler, Method method, T mapping) {
CorsConfiguration config = initCorsConfiguration(handler, method, mapping);
if (config != null) {
- this.corsConfigurations.put(method, config);
+ this.corsMap.put(method, config);
}
}
@@ -442,6 +427,14 @@ protected HandlerMethod handleNoMatch(Set<T> mappings, String lookupPath, HttpSe
return null;
}
+ @Override
+ protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
+ if (handler instanceof HandlerMethod) {
+ this.corsMap.get(((HandlerMethod) handler).getMethod());
+ }
+ return null;
+ }
+
/**
* A thin wrapper around a matched HandlerMethod and its mapping, for the purpose of
|
e8db1654df89d3c60a6620a68fc5b85137e05b42
|
orientdb
|
Renamed everywhere OTreeMap in OMVRBTree as the- new name of the algorithm: OMVRBTree--
|
p
|
https://github.com/orientechnologies/orientdb
|
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/AbstractEntryIterator.java b/commons/src/main/java/com/orientechnologies/common/collection/AbstractEntryIterator.java
index b30c3731226..70fedb1e5ae 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/AbstractEntryIterator.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/AbstractEntryIterator.java
@@ -20,15 +20,15 @@
import java.util.NoSuchElementException;
/**
- * Base class for OTreeMap Iterators
+ * Base class for OMVRBTree Iterators
*/
abstract class AbstractEntryIterator<K, V, T> implements Iterator<T> {
- OTreeMap<K, V> tree;
- OTreeMapEntry<K, V> next;
- OTreeMapEntry<K, V> lastReturned;
+ OMVRBTree<K, V> tree;
+ OMVRBTreeEntry<K, V> next;
+ OMVRBTreeEntry<K, V> lastReturned;
int expectedModCount;
- AbstractEntryIterator(OTreeMapEntry<K, V> first) {
+ AbstractEntryIterator(OMVRBTreeEntry<K, V> first) {
if (first == null)
// IN CASE OF ABSTRACTMAP.HASHCODE()
return;
@@ -41,10 +41,10 @@ abstract class AbstractEntryIterator<K, V, T> implements Iterator<T> {
}
public final boolean hasNext() {
- return next != null && (OTreeMap.successor(next) != null || tree.pageIndex < next.getSize() - 1);
+ return next != null && (OMVRBTree.successor(next) != null || tree.pageIndex < next.getSize() - 1);
}
- final OTreeMapEntry<K, V> nextEntry() {
+ final OMVRBTreeEntry<K, V> nextEntry() {
if (next == null)
throw new NoSuchElementException();
@@ -57,20 +57,20 @@ final OTreeMapEntry<K, V> nextEntry() {
throw new ConcurrentModificationException();
tree.pageIndex = 0;
- next = OTreeMap.successor(next);
+ next = OMVRBTree.successor(next);
lastReturned = next;
}
return next;
}
- final OTreeMapEntry<K, V> prevEntry() {
- OTreeMapEntry<K, V> e = next;
+ final OMVRBTreeEntry<K, V> prevEntry() {
+ OMVRBTreeEntry<K, V> e = next;
if (e == null)
throw new NoSuchElementException();
if (tree.modCount != expectedModCount)
throw new ConcurrentModificationException();
- next = OTreeMap.predecessor(e);
+ next = OMVRBTree.predecessor(e);
lastReturned = e;
return e;
}
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMap.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
similarity index 80%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMap.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
index d326af052f1..10403e270c1 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMap.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ * 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 com.orientechnologies.common.collection;
import java.io.IOException;
@@ -18,9 +33,19 @@
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.OProfiler;
+/**
+ * Base abstract class of MVRB-Tree algorithm.
+ *
+ * @author Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ * @param <K>
+ * Key type
+ * @param <V>
+ * Value type
+ */
@SuppressWarnings("unchecked")
-public abstract class OTreeMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, Cloneable, java.io.Serializable {
- protected OTreeMapEventListener<K, V> listener;
+public abstract class OMVRBTree<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, Cloneable, java.io.Serializable {
+ protected OMVRBTreeEventListener<K, V> listener;
boolean pageItemFound = false;
int pageItemComparator = 0;
protected volatile int pageIndex = -1;
@@ -41,7 +66,7 @@ public abstract class OTreeMap<K, V> extends AbstractMap<K, V> implements ONavig
*/
private final Comparator<? super K> comparator;
- protected transient OTreeMapEntry<K, V> root = null;
+ protected transient OMVRBTreeEntry<K, V> root = null;
/**
* The number of structural modifications to the tree.
@@ -50,14 +75,14 @@ public abstract class OTreeMap<K, V> extends AbstractMap<K, V> implements ONavig
transient boolean runtimeCheckEnabled = false;
- public OTreeMap(final int iSize, final float iLoadFactor) {
+ public OMVRBTree(final int iSize, final float iLoadFactor) {
lastPageSize = iSize;
pageLoadFactor = iLoadFactor;
comparator = null;
init();
}
- public OTreeMap(final OTreeMapEventListener<K, V> iListener) {
+ public OMVRBTree(final OMVRBTreeEventListener<K, V> iListener) {
init();
comparator = null;
listener = iListener;
@@ -70,7 +95,7 @@ public OTreeMap(final OTreeMapEventListener<K, V> iListener) {
* the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers),
* the <tt>put(Object key, Object value)</tt> call will throw a <tt>ClassCastException</tt>.
*/
- public OTreeMap() {
+ public OMVRBTree() {
init();
comparator = null;
}
@@ -86,7 +111,7 @@ public OTreeMap() {
* the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of
* the keys will be used.
*/
- public OTreeMap(final Comparator<? super K> comparator) {
+ public OMVRBTree(final Comparator<? super K> comparator) {
init();
this.comparator = comparator;
}
@@ -104,7 +129,7 @@ public OTreeMap(final Comparator<? super K> comparator) {
* @throws NullPointerException
* if the specified map is null
*/
- public OTreeMap(final Map<? extends K, ? extends V> m) {
+ public OMVRBTree(final Map<? extends K, ? extends V> m) {
init();
comparator = null;
putAll(m);
@@ -119,7 +144,7 @@ public OTreeMap(final Map<? extends K, ? extends V> m) {
* @throws NullPointerException
* if the specified map is null
*/
- public OTreeMap(final SortedMap<K, ? extends V> m) {
+ public OMVRBTree(final SortedMap<K, ? extends V> m) {
init();
comparator = m.comparator();
try {
@@ -132,17 +157,17 @@ public OTreeMap(final SortedMap<K, ? extends V> m) {
/**
* Create a new entry with the first key/value to handle.
*/
- protected abstract OTreeMapEntry<K, V> createEntry(final K key, final V value);
+ protected abstract OMVRBTreeEntry<K, V> createEntry(final K key, final V value);
/**
* Create a new node with the same parent of the node is splitting.
*/
- protected abstract OTreeMapEntry<K, V> createEntry(final OTreeMapEntry<K, V> parent);
+ protected abstract OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent);
public int getNodes() {
int counter = -1;
- OTreeMapEntry<K, V> entry = getFirstEntry();
+ OMVRBTreeEntry<K, V> entry = getFirstEntry();
while (entry != null) {
entry = successor(entry);
counter++;
@@ -174,7 +199,7 @@ public int size() {
*/
@Override
public boolean containsKey(final Object key) {
- OTreeMapEntry<K, V> entry = getEntry(key);
+ OMVRBTreeEntry<K, V> entry = getEntry(key);
return entry != null;
}
@@ -191,7 +216,7 @@ public boolean containsKey(final Object key) {
*/
@Override
public boolean containsValue(final Object value) {
- for (OTreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e))
+ for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = successor(e))
if (valEquals(value, e.getValue()))
return true;
return false;
@@ -220,7 +245,7 @@ public V get(final Object key) {
if (size == 0)
return null;
- OTreeMapEntry<K, V> entry = getEntry(key);
+ OMVRBTreeEntry<K, V> entry = getEntry(key);
return entry == null ? null : entry.getValue();
}
@@ -282,11 +307,11 @@ public void putAll(final Map<? extends K, ? extends V> map) {
* @throws NullPointerException
* if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
*/
- final OTreeMapEntry<K, V> getEntry(final Object key) {
+ final OMVRBTreeEntry<K, V> getEntry(final Object key) {
return getEntry(key, false);
}
- final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer) {
+ final OMVRBTreeEntry<K, V> getEntry(final Object key, final boolean iGetContainer) {
if (key == null)
return null;
@@ -296,7 +321,7 @@ final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer
if (comparator != null)
return getEntryUsingComparator(key, iGetContainer);
- OTreeMapEntry<K, V> p = getBestEntryPoint(key);
+ OMVRBTreeEntry<K, V> p = getBestEntryPoint(key);
// System.out.println("Best entry point for key " + key + " is: "+p);
@@ -305,9 +330,9 @@ final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer
if (p == null)
return null;
- OTreeMapEntry<K, V> lastNode = p;
- OTreeMapEntry<K, V> prevNode = null;
- OTreeMapEntry<K, V> tmpNode;
+ OMVRBTreeEntry<K, V> lastNode = p;
+ OMVRBTreeEntry<K, V> prevNode = null;
+ OMVRBTreeEntry<K, V> tmpNode;
int beginKey = -1;
int steps = -1;
final Comparable<? super K> k = (Comparable<? super K>) key;
@@ -375,7 +400,7 @@ final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer
} finally {
checkTreeStructure(p);
- OProfiler.getInstance().updateStat("[OTreeMap.getEntry] Steps of search", steps);
+ OProfiler.getInstance().updateStat("[OMVRBTree.getEntry] Steps of search", steps);
}
return null;
@@ -384,15 +409,15 @@ final OTreeMapEntry<K, V> getEntry(final Object key, final boolean iGetContainer
/**
* Basic implementation that returns the root node.
*/
- protected OTreeMapEntry<K, V> getBestEntryPoint(final Object key) {
+ protected OMVRBTreeEntry<K, V> getBestEntryPoint(final Object key) {
return root;
}
- public OTreeMapEventListener<K, V> getListener() {
+ public OMVRBTreeEventListener<K, V> getListener() {
return listener;
}
- public void setListener(final OTreeMapEventListener<K, V> listener) {
+ public void setListener(final OMVRBTreeEventListener<K, V> listener) {
this.listener = listener;
}
@@ -402,12 +427,12 @@ public void setListener(final OTreeMapEventListener<K, V> listener) {
*
* @param iGetContainer
*/
- final OTreeMapEntry<K, V> getEntryUsingComparator(final Object key, final boolean iGetContainer) {
+ final OMVRBTreeEntry<K, V> getEntryUsingComparator(final Object key, final boolean iGetContainer) {
K k = (K) key;
Comparator<? super K> cpr = comparator;
if (cpr != null) {
- OTreeMapEntry<K, V> p = root;
- OTreeMapEntry<K, V> lastNode = null;
+ OMVRBTreeEntry<K, V> p = root;
+ OMVRBTreeEntry<K, V> lastNode = null;
while (p != null) {
lastNode = p;
@@ -451,8 +476,8 @@ else if (beginKey > 0) {
* the specified key; if no such entry exists (i.e., the greatest key in the Tree is less than the specified key), returns
* <tt>null</tt>.
*/
- final OTreeMapEntry<K, V> getCeilingEntry(final K key) {
- OTreeMapEntry<K, V> p = root;
+ final OMVRBTreeEntry<K, V> getCeilingEntry(final K key) {
+ OMVRBTreeEntry<K, V> p = root;
while (p != null) {
int cmp = compare(key, p.getKey());
if (cmp < 0) {
@@ -464,7 +489,7 @@ final OTreeMapEntry<K, V> getCeilingEntry(final K key) {
if (p.getRight() != null) {
p = p.getRight();
} else {
- OTreeMapEntry<K, V> parent = p.getParent();
+ OMVRBTreeEntry<K, V> parent = p.getParent();
Entry<K, V> ch = p;
while (parent != null && ch == parent.getRight()) {
ch = parent;
@@ -482,8 +507,8 @@ final OTreeMapEntry<K, V> getCeilingEntry(final K key) {
* Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the greatest key less than
* the specified key; if no such entry exists, returns <tt>null</tt>.
*/
- final OTreeMapEntry<K, V> getFloorEntry(final K key) {
- OTreeMapEntry<K, V> p = root;
+ final OMVRBTreeEntry<K, V> getFloorEntry(final K key) {
+ OMVRBTreeEntry<K, V> p = root;
while (p != null) {
int cmp = compare(key, p.getKey());
if (cmp > 0) {
@@ -495,7 +520,7 @@ final OTreeMapEntry<K, V> getFloorEntry(final K key) {
if (p.getLeft() != null) {
p = p.getLeft();
} else {
- OTreeMapEntry<K, V> parent = p.getParent();
+ OMVRBTreeEntry<K, V> parent = p.getParent();
Entry<K, V> ch = p;
while (parent != null && ch == parent.getLeft()) {
ch = parent;
@@ -514,8 +539,8 @@ final OTreeMapEntry<K, V> getFloorEntry(final K key) {
* Gets the entry for the least key greater than the specified key; if no such entry exists, returns the entry for the least key
* greater than the specified key; if no such entry exists returns <tt>null</tt>.
*/
- final OTreeMapEntry<K, V> getHigherEntry(final K key) {
- OTreeMapEntry<K, V> p = root;
+ final OMVRBTreeEntry<K, V> getHigherEntry(final K key) {
+ OMVRBTreeEntry<K, V> p = root;
while (p != null) {
int cmp = compare(key, p.getKey());
if (cmp < 0) {
@@ -527,7 +552,7 @@ final OTreeMapEntry<K, V> getHigherEntry(final K key) {
if (p.getRight() != null) {
p = p.getRight();
} else {
- OTreeMapEntry<K, V> parent = p.getParent();
+ OMVRBTreeEntry<K, V> parent = p.getParent();
Entry<K, V> ch = p;
while (parent != null && ch == parent.getRight()) {
ch = parent;
@@ -544,8 +569,8 @@ final OTreeMapEntry<K, V> getHigherEntry(final K key) {
* Returns the entry for the greatest key less than the specified key; if no such entry exists (i.e., the least key in the Tree is
* greater than the specified key), returns <tt>null</tt>.
*/
- final OTreeMapEntry<K, V> getLowerEntry(final K key) {
- OTreeMapEntry<K, V> p = root;
+ final OMVRBTreeEntry<K, V> getLowerEntry(final K key) {
+ OMVRBTreeEntry<K, V> p = root;
while (p != null) {
int cmp = compare(key, p.getKey());
if (cmp > 0) {
@@ -557,7 +582,7 @@ final OTreeMapEntry<K, V> getLowerEntry(final K key) {
if (p.getLeft() != null) {
p = p.getLeft();
} else {
- OTreeMapEntry<K, V> parent = p.getParent();
+ OMVRBTreeEntry<K, V> parent = p.getParent();
Entry<K, V> ch = p;
while (parent != null && ch == parent.getLeft()) {
ch = parent;
@@ -588,7 +613,7 @@ final OTreeMapEntry<K, V> getLowerEntry(final K key) {
*/
@Override
public V put(final K key, final V value) {
- OTreeMapEntry<K, V> parentNode = null;
+ OMVRBTreeEntry<K, V> parentNode = null;
try {
if (root == null) {
@@ -625,7 +650,7 @@ public V put(final K key, final V value) {
parentNode.insert(pageIndex, key, value);
} else {
// CREATE NEW NODE AND COPY HALF OF VALUES FROM THE ORIGIN TO THE NEW ONE IN ORDER TO GET VALUES BALANCED
- final OTreeMapEntry<K, V> newNode = createEntry(parentNode);
+ final OMVRBTreeEntry<K, V> newNode = createEntry(parentNode);
// System.out.println("Created new entry: " + newEntry+ ", insert the key as index="+pageIndex);
@@ -636,7 +661,7 @@ public V put(final K key, final V value) {
// INSERT IN THE NEW NODE
newNode.insert(pageIndex - parentNode.getPageSplitItems(), key, value);
- final OTreeMapEntry<K, V> prevNode = parentNode.getRight();
+ final OMVRBTreeEntry<K, V> prevNode = parentNode.getRight();
// REPLACE THE RIGHT ONE WITH THE NEW NODE
parentNode.setRight(newNode);
@@ -667,7 +692,7 @@ public V put(final K key, final V value) {
}
/**
- * Removes the mapping for this key from this OTreeMap if present.
+ * Removes the mapping for this key from this OMVRBTree if present.
*
* @param key
* key for which mapping should be removed
@@ -680,7 +705,7 @@ public V put(final K key, final V value) {
*/
@Override
public V remove(final Object key) {
- OTreeMapEntry<K, V> p = getEntry(key);
+ OMVRBTreeEntry<K, V> p = getEntry(key);
if (p == null)
return null;
@@ -700,15 +725,15 @@ public void clear() {
}
/**
- * Returns a shallow copy of this <tt>OTreeMap</tt> instance. (The keys and values themselves are not cloned.)
+ * Returns a shallow copy of this <tt>OMVRBTree</tt> instance. (The keys and values themselves are not cloned.)
*
* @return a shallow copy of this map
*/
@Override
public Object clone() {
- OTreeMap<K, V> clone = null;
+ OMVRBTree<K, V> clone = null;
try {
- clone = (OTreeMap<K, V>) super.clone();
+ clone = (OMVRBTree<K, V>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
@@ -757,7 +782,7 @@ public Map.Entry<K, V> lastEntry() {
* @since 1.6
*/
public Entry<K, V> pollFirstEntry() {
- OTreeMapEntry<K, V> p = getFirstEntry();
+ OMVRBTreeEntry<K, V> p = getFirstEntry();
Map.Entry<K, V> result = exportEntry(p);
if (p != null)
deleteEntry(p);
@@ -768,7 +793,7 @@ public Entry<K, V> pollFirstEntry() {
* @since 1.6
*/
public Entry<K, V> pollLastEntry() {
- OTreeMapEntry<K, V> p = getLastEntry();
+ OMVRBTreeEntry<K, V> p = getLastEntry();
Map.Entry<K, V> result = exportEntry(p);
if (p != null)
deleteEntry(p);
@@ -1026,17 +1051,17 @@ public Iterator<V> iterator() {
@Override
public int size() {
- return OTreeMap.this.size();
+ return OMVRBTree.this.size();
}
@Override
public boolean contains(Object o) {
- return OTreeMap.this.containsValue(o);
+ return OMVRBTree.this.containsValue(o);
}
@Override
public boolean remove(Object o) {
- for (OTreeMapEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
+ for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
if (valEquals(e.getValue(), o)) {
deleteEntry(e);
return true;
@@ -1047,7 +1072,7 @@ public boolean remove(Object o) {
@Override
public void clear() {
- OTreeMap.this.clear();
+ OMVRBTree.this.clear();
}
}
@@ -1061,7 +1086,7 @@ public Iterator<Map.Entry<K, V>> iterator() {
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
- OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o;
+ OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
V value = entry.getValue();
V p = get(entry.getKey());
return p != null && valEquals(p, value);
@@ -1071,9 +1096,9 @@ public boolean contains(Object o) {
public boolean remove(Object o) {
if (!(o instanceof Map.Entry))
return false;
- OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o;
+ OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
V value = entry.getValue();
- OTreeMapEntry<K, V> p = getEntry(entry.getKey());
+ OMVRBTreeEntry<K, V> p = getEntry(entry.getKey());
if (p != null && valEquals(p.getValue(), value)) {
deleteEntry(p);
return true;
@@ -1083,12 +1108,12 @@ public boolean remove(Object o) {
@Override
public int size() {
- return OTreeMap.this.size();
+ return OMVRBTree.this.size();
}
@Override
public void clear() {
- OTreeMap.this.clear();
+ OMVRBTree.this.clear();
}
}
@@ -1116,17 +1141,17 @@ static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E>
@Override
public Iterator<E> iterator() {
- if (m instanceof OTreeMap)
- return ((OTreeMap<E, Object>) m).keyIterator();
+ if (m instanceof OMVRBTree)
+ return ((OMVRBTree<E, Object>) m).keyIterator();
else
- return (((OTreeMap.NavigableSubMap) m).keyIterator());
+ return (((OMVRBTree.NavigableSubMap) m).keyIterator());
}
public Iterator<E> descendingIterator() {
- if (m instanceof OTreeMap)
- return ((OTreeMap<E, Object>) m).descendingKeyIterator();
+ if (m instanceof OMVRBTree)
+ return ((OMVRBTree<E, Object>) m).descendingKeyIterator();
else
- return (((OTreeMap.NavigableSubMap) m).descendingKeyIterator());
+ return (((OMVRBTree.NavigableSubMap) m).descendingKeyIterator());
}
@Override
@@ -1195,15 +1220,15 @@ public boolean remove(Object o) {
}
public ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
- return new OTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
+ return new OMVRBTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
public ONavigableSet<E> headSet(E toElement, boolean inclusive) {
- return new OTreeSetMemory<E>(m.headMap(toElement, inclusive));
+ return new OMVRBTreeSetMemory<E>(m.headMap(toElement, inclusive));
}
public ONavigableSet<E> tailSet(E fromElement, boolean inclusive) {
- return new OTreeSetMemory<E>(m.tailMap(fromElement, inclusive));
+ return new OMVRBTreeSetMemory<E>(m.tailMap(fromElement, inclusive));
}
public SortedSet<E> subSet(E fromElement, E toElement) {
@@ -1219,12 +1244,12 @@ public SortedSet<E> tailSet(E fromElement) {
}
public ONavigableSet<E> descendingSet() {
- return new OTreeSetMemory<E>(m.descendingMap());
+ return new OMVRBTreeSetMemory<E>(m.descendingMap());
}
}
final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> {
- EntryIterator(OTreeMapEntry<K, V> first) {
+ EntryIterator(OMVRBTreeEntry<K, V> first) {
super(first);
}
@@ -1234,7 +1259,7 @@ public Map.Entry<K, V> next() {
}
final class ValueIterator extends AbstractEntryIterator<K, V, V> {
- ValueIterator(OTreeMapEntry<K, V> first) {
+ ValueIterator(OMVRBTreeEntry<K, V> first) {
super(first);
}
@@ -1244,7 +1269,7 @@ public V next() {
}
final class KeyIterator extends AbstractEntryIterator<K, V, K> {
- KeyIterator(OTreeMapEntry<K, V> first) {
+ KeyIterator(OMVRBTreeEntry<K, V> first) {
super(first);
}
@@ -1254,7 +1279,7 @@ public K next() {
}
final class DescendingKeyIterator extends AbstractEntryIterator<K, V, K> {
- DescendingKeyIterator(OTreeMapEntry<K, V> first) {
+ DescendingKeyIterator(OMVRBTreeEntry<K, V> first) {
super(first);
}
@@ -1266,7 +1291,7 @@ public K next() {
// Little utilities
/**
- * Compares two keys using the correct comparison method for this OTreeMap.
+ * Compares two keys using the correct comparison method for this OMVRBTree.
*/
final int compare(Object k1, Object k2) {
return comparator == null ? ((Comparable<? super K>) k1).compareTo((K) k2) : comparator.compare((K) k1, (K) k2);
@@ -1282,14 +1307,14 @@ final static boolean valEquals(Object o1, Object o2) {
/**
* Return SimpleImmutableEntry for entry, or null if null
*/
- static <K, V> Map.Entry<K, V> exportEntry(OTreeMapEntry<K, V> e) {
+ static <K, V> Map.Entry<K, V> exportEntry(OMVRBTreeEntry<K, V> e) {
return e == null ? null : new OSimpleImmutableEntry<K, V>(e);
}
/**
* Return key for entry, or null if null
*/
- static <K, V> K keyOrNull(OTreeMapEntry<K, V> e) {
+ static <K, V> K keyOrNull(OMVRBTreeEntry<K, V> e) {
return e == null ? null : e.getKey();
}
@@ -1299,7 +1324,7 @@ static <K, V> K keyOrNull(OTreeMapEntry<K, V> e) {
* @throws NoSuchElementException
* if the Entry is null
*/
- static <K> K key(OTreeMapEntry<K, ?> e) {
+ static <K> K key(OMVRBTreeEntry<K, ?> e) {
if (e == null)
throw new NoSuchElementException();
return e.getKey();
@@ -1315,7 +1340,7 @@ static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements
/**
* The backing map.
*/
- final OTreeMap<K, V> m;
+ final OMVRBTree<K, V> m;
/**
* Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then
@@ -1326,7 +1351,7 @@ static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements
final boolean fromStart, toEnd;
final boolean loInclusive, hiInclusive;
- NavigableSubMap(OTreeMap<K, V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) {
+ NavigableSubMap(OMVRBTree<K, V> m, boolean fromStart, K lo, boolean loInclusive, boolean toEnd, K hi, boolean hiInclusive) {
if (!fromStart && !toEnd) {
if (m.compare(lo, hi) > 0)
throw new IllegalArgumentException("fromKey > toKey");
@@ -1383,68 +1408,68 @@ final boolean inRange(Object key, boolean inclusive) {
* descending maps
*/
- final OTreeMapEntry<K, V> absLowest() {
- OTreeMapEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo)));
+ final OMVRBTreeEntry<K, V> absLowest() {
+ OMVRBTreeEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo) : m.getHigherEntry(lo)));
return (e == null || tooHigh(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absHighest() {
- OTreeMapEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi)));
+ final OMVRBTreeEntry<K, V> absHighest() {
+ OMVRBTreeEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi) : m.getLowerEntry(hi)));
return (e == null || tooLow(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absCeiling(K key) {
+ final OMVRBTreeEntry<K, V> absCeiling(K key) {
if (tooLow(key))
return absLowest();
- OTreeMapEntry<K, V> e = m.getCeilingEntry(key);
+ OMVRBTreeEntry<K, V> e = m.getCeilingEntry(key);
return (e == null || tooHigh(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absHigher(K key) {
+ final OMVRBTreeEntry<K, V> absHigher(K key) {
if (tooLow(key))
return absLowest();
- OTreeMapEntry<K, V> e = m.getHigherEntry(key);
+ OMVRBTreeEntry<K, V> e = m.getHigherEntry(key);
return (e == null || tooHigh(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absFloor(K key) {
+ final OMVRBTreeEntry<K, V> absFloor(K key) {
if (tooHigh(key))
return absHighest();
- OTreeMapEntry<K, V> e = m.getFloorEntry(key);
+ OMVRBTreeEntry<K, V> e = m.getFloorEntry(key);
return (e == null || tooLow(e.getKey())) ? null : e;
}
- final OTreeMapEntry<K, V> absLower(K key) {
+ final OMVRBTreeEntry<K, V> absLower(K key) {
if (tooHigh(key))
return absHighest();
- OTreeMapEntry<K, V> e = m.getLowerEntry(key);
+ OMVRBTreeEntry<K, V> e = m.getLowerEntry(key);
return (e == null || tooLow(e.getKey())) ? null : e;
}
/** Returns the absolute high fence for ascending traversal */
- final OTreeMapEntry<K, V> absHighFence() {
+ final OMVRBTreeEntry<K, V> absHighFence() {
return (toEnd ? null : (hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi)));
}
/** Return the absolute low fence for descending traversal */
- final OTreeMapEntry<K, V> absLowFence() {
+ final OMVRBTreeEntry<K, V> absLowFence() {
return (fromStart ? null : (loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo)));
}
// Abstract methods defined in ascending vs descending classes
// These relay to the appropriate absolute versions
- abstract OTreeMapEntry<K, V> subLowest();
+ abstract OMVRBTreeEntry<K, V> subLowest();
- abstract OTreeMapEntry<K, V> subHighest();
+ abstract OMVRBTreeEntry<K, V> subHighest();
- abstract OTreeMapEntry<K, V> subCeiling(K key);
+ abstract OMVRBTreeEntry<K, V> subCeiling(K key);
- abstract OTreeMapEntry<K, V> subHigher(K key);
+ abstract OMVRBTreeEntry<K, V> subHigher(K key);
- abstract OTreeMapEntry<K, V> subFloor(K key);
+ abstract OMVRBTreeEntry<K, V> subFloor(K key);
- abstract OTreeMapEntry<K, V> subLower(K key);
+ abstract OMVRBTreeEntry<K, V> subLower(K key);
/** Returns ascending iterator from the perspective of this submap */
abstract Iterator<K> keyIterator();
@@ -1535,7 +1560,7 @@ public final Map.Entry<K, V> lastEntry() {
}
public final Map.Entry<K, V> pollFirstEntry() {
- OTreeMapEntry<K, V> e = subLowest();
+ OMVRBTreeEntry<K, V> e = subLowest();
Map.Entry<K, V> result = exportEntry(e);
if (e != null)
m.deleteEntry(e);
@@ -1543,7 +1568,7 @@ public final Map.Entry<K, V> pollFirstEntry() {
}
public final Map.Entry<K, V> pollLastEntry() {
- OTreeMapEntry<K, V> e = subHighest();
+ OMVRBTreeEntry<K, V> e = subHighest();
Map.Entry<K, V> result = exportEntry(e);
if (e != null)
m.deleteEntry(e);
@@ -1558,7 +1583,7 @@ public final Map.Entry<K, V> pollLastEntry() {
@SuppressWarnings("rawtypes")
public final ONavigableSet<K> navigableKeySet() {
KeySet<K> nksv = navigableKeySetView;
- return (nksv != null) ? nksv : (navigableKeySetView = new OTreeMap.KeySet(this));
+ return (nksv != null) ? nksv : (navigableKeySetView = new OMVRBTree.KeySet(this));
}
@Override
@@ -1605,15 +1630,15 @@ public int size() {
@Override
public boolean isEmpty() {
- OTreeMapEntry<K, V> n = absLowest();
+ OMVRBTreeEntry<K, V> n = absLowest();
return n == null || tooHigh(n.getKey());
}
@Override
public boolean contains(final Object o) {
- if (!(o instanceof OTreeMapEntry))
+ if (!(o instanceof OMVRBTreeEntry))
return false;
- OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o;
+ OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
K key = entry.getKey();
if (!inRange(key))
return false;
@@ -1623,13 +1648,13 @@ public boolean contains(final Object o) {
@Override
public boolean remove(final Object o) {
- if (!(o instanceof OTreeMapEntry))
+ if (!(o instanceof OMVRBTreeEntry))
return false;
- final OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) o;
+ final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o;
K key = entry.getKey();
if (!inRange(key))
return false;
- final OTreeMapEntry<K, V> node = m.getEntry(key);
+ final OMVRBTreeEntry<K, V> node = m.getEntry(key);
if (node != null && valEquals(node.getValue(), entry.getValue())) {
m.deleteEntry(node);
return true;
@@ -1642,12 +1667,12 @@ public boolean remove(final Object o) {
* Iterators for SubMaps
*/
abstract class SubMapIterator<T> implements Iterator<T> {
- OTreeMapEntry<K, V> lastReturned;
- OTreeMapEntry<K, V> next;
+ OMVRBTreeEntry<K, V> lastReturned;
+ OMVRBTreeEntry<K, V> next;
final K fenceKey;
int expectedModCount;
- SubMapIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) {
+ SubMapIterator(final OMVRBTreeEntry<K, V> first, final OMVRBTreeEntry<K, V> fence) {
expectedModCount = m.modCount;
lastReturned = null;
next = first;
@@ -1658,8 +1683,8 @@ public final boolean hasNext() {
return next != null && next.getKey() != fenceKey;
}
- final OTreeMapEntry<K, V> nextEntry() {
- OTreeMapEntry<K, V> e = next;
+ final OMVRBTreeEntry<K, V> nextEntry() {
+ OMVRBTreeEntry<K, V> e = next;
if (e == null || e.getKey() == fenceKey)
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
@@ -1669,8 +1694,8 @@ final OTreeMapEntry<K, V> nextEntry() {
return e;
}
- final OTreeMapEntry<K, V> prevEntry() {
- OTreeMapEntry<K, V> e = next;
+ final OMVRBTreeEntry<K, V> prevEntry() {
+ OMVRBTreeEntry<K, V> e = next;
if (e == null || e.getKey() == fenceKey)
throw new NoSuchElementException();
if (m.modCount != expectedModCount)
@@ -1706,7 +1731,7 @@ final void removeDescending() {
}
final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
- SubMapEntryIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) {
+ SubMapEntryIterator(final OMVRBTreeEntry<K, V> first, final OMVRBTreeEntry<K, V> fence) {
super(first, fence);
}
@@ -1720,7 +1745,7 @@ public void remove() {
}
final class SubMapKeyIterator extends SubMapIterator<K> {
- SubMapKeyIterator(final OTreeMapEntry<K, V> first, final OTreeMapEntry<K, V> fence) {
+ SubMapKeyIterator(final OMVRBTreeEntry<K, V> first, final OMVRBTreeEntry<K, V> fence) {
super(first, fence);
}
@@ -1734,7 +1759,7 @@ public void remove() {
}
final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
- DescendingSubMapEntryIterator(final OTreeMapEntry<K, V> last, final OTreeMapEntry<K, V> fence) {
+ DescendingSubMapEntryIterator(final OMVRBTreeEntry<K, V> last, final OMVRBTreeEntry<K, V> fence) {
super(last, fence);
}
@@ -1748,7 +1773,7 @@ public void remove() {
}
final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
- DescendingSubMapKeyIterator(final OTreeMapEntry<K, V> last, final OTreeMapEntry<K, V> fence) {
+ DescendingSubMapKeyIterator(final OMVRBTreeEntry<K, V> last, final OMVRBTreeEntry<K, V> fence) {
super(last, fence);
}
@@ -1768,7 +1793,7 @@ public void remove() {
static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866124060L;
- AscendingSubMap(final OTreeMap<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
+ AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
@@ -1827,32 +1852,32 @@ public Set<Map.Entry<K, V>> entrySet() {
}
@Override
- OTreeMapEntry<K, V> subLowest() {
+ OMVRBTreeEntry<K, V> subLowest() {
return absLowest();
}
@Override
- OTreeMapEntry<K, V> subHighest() {
+ OMVRBTreeEntry<K, V> subHighest() {
return absHighest();
}
@Override
- OTreeMapEntry<K, V> subCeiling(final K key) {
+ OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absCeiling(key);
}
@Override
- OTreeMapEntry<K, V> subHigher(final K key) {
+ OMVRBTreeEntry<K, V> subHigher(final K key) {
return absHigher(key);
}
@Override
- OTreeMapEntry<K, V> subFloor(final K key) {
+ OMVRBTreeEntry<K, V> subFloor(final K key) {
return absFloor(key);
}
@Override
- OTreeMapEntry<K, V> subLower(final K key) {
+ OMVRBTreeEntry<K, V> subLower(final K key) {
return absLower(key);
}
}
@@ -1865,7 +1890,7 @@ static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> {
private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator);
- DescendingSubMap(final OTreeMap<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
+ DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
final K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
@@ -1924,32 +1949,32 @@ public Set<Map.Entry<K, V>> entrySet() {
}
@Override
- OTreeMapEntry<K, V> subLowest() {
+ OMVRBTreeEntry<K, V> subLowest() {
return absHighest();
}
@Override
- OTreeMapEntry<K, V> subHighest() {
+ OMVRBTreeEntry<K, V> subHighest() {
return absLowest();
}
@Override
- OTreeMapEntry<K, V> subCeiling(final K key) {
+ OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absFloor(key);
}
@Override
- OTreeMapEntry<K, V> subHigher(final K key) {
+ OMVRBTreeEntry<K, V> subHigher(final K key) {
return absLower(key);
}
@Override
- OTreeMapEntry<K, V> subFloor(final K key) {
+ OMVRBTreeEntry<K, V> subFloor(final K key) {
return absCeiling(key);
}
@Override
- OTreeMapEntry<K, V> subLower(final K key) {
+ OMVRBTreeEntry<K, V> subLower(final K key) {
return absHigher(key);
}
}
@@ -1964,10 +1989,10 @@ OTreeMapEntry<K, V> subLower(final K key) {
*/
/**
- * Returns the first Entry in the OTreeMap (according to the OTreeMap's key-sort function). Returns null if the OTreeMap is empty.
+ * Returns the first Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is empty.
*/
- protected OTreeMapEntry<K, V> getFirstEntry() {
- OTreeMapEntry<K, V> p = root;
+ protected OMVRBTreeEntry<K, V> getFirstEntry() {
+ OMVRBTreeEntry<K, V> p = root;
if (p != null) {
if (p.getSize() > 0)
pageIndex = 0;
@@ -1979,10 +2004,10 @@ protected OTreeMapEntry<K, V> getFirstEntry() {
}
/**
- * Returns the last Entry in the OTreeMap (according to the OTreeMap's key-sort function). Returns null if the OTreeMap is empty.
+ * Returns the last Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is empty.
*/
- protected final OTreeMapEntry<K, V> getLastEntry() {
- OTreeMapEntry<K, V> p = root;
+ protected final OMVRBTreeEntry<K, V> getLastEntry() {
+ OMVRBTreeEntry<K, V> p = root;
if (p != null)
while (p.getRight() != null)
p = p.getRight();
@@ -1996,11 +2021,11 @@ protected final OTreeMapEntry<K, V> getLastEntry() {
/**
* Returns the successor of the specified Entry, or null if no such.
*/
- public static <K, V> OTreeMapEntry<K, V> successor(final OTreeMapEntry<K, V> t) {
+ public static <K, V> OMVRBTreeEntry<K, V> successor(final OMVRBTreeEntry<K, V> t) {
if (t == null)
return null;
- OTreeMapEntry<K, V> p = null;
+ OMVRBTreeEntry<K, V> p = null;
if (t.getRight() != null) {
p = t.getRight();
@@ -2008,7 +2033,7 @@ public static <K, V> OTreeMapEntry<K, V> successor(final OTreeMapEntry<K, V> t)
p = p.getLeft();
} else {
p = t.getParent();
- OTreeMapEntry<K, V> ch = t;
+ OMVRBTreeEntry<K, V> ch = t;
while (p != null && ch == p.getRight()) {
ch = p;
p = p.getParent();
@@ -2021,16 +2046,16 @@ public static <K, V> OTreeMapEntry<K, V> successor(final OTreeMapEntry<K, V> t)
/**
* Returns the predecessor of the specified Entry, or null if no such.
*/
- public static <K, V> OTreeMapEntry<K, V> predecessor(final OTreeMapEntry<K, V> t) {
+ public static <K, V> OMVRBTreeEntry<K, V> predecessor(final OMVRBTreeEntry<K, V> t) {
if (t == null)
return null;
else if (t.getLeft() != null) {
- OTreeMapEntry<K, V> p = t.getLeft();
+ OMVRBTreeEntry<K, V> p = t.getLeft();
while (p.getRight() != null)
p = p.getRight();
return p;
} else {
- OTreeMapEntry<K, V> p = t.getParent();
+ OMVRBTreeEntry<K, V> p = t.getParent();
Entry<K, V> ch = t;
while (p != null && ch == p.getLeft()) {
ch = p;
@@ -2048,31 +2073,31 @@ else if (t.getLeft() != null) {
* checks in the main algorithms.
*/
- private static <K, V> boolean colorOf(final OTreeMapEntry<K, V> p) {
+ private static <K, V> boolean colorOf(final OMVRBTreeEntry<K, V> p) {
return (p == null ? BLACK : p.getColor());
}
- private static <K, V> OTreeMapEntry<K, V> parentOf(final OTreeMapEntry<K, V> p) {
+ private static <K, V> OMVRBTreeEntry<K, V> parentOf(final OMVRBTreeEntry<K, V> p) {
return (p == null ? null : p.getParent());
}
- private static <K, V> void setColor(final OTreeMapEntry<K, V> p, final boolean c) {
+ private static <K, V> void setColor(final OMVRBTreeEntry<K, V> p, final boolean c) {
if (p != null)
p.setColor(c);
}
- private static <K, V> OTreeMapEntry<K, V> leftOf(final OTreeMapEntry<K, V> p) {
+ private static <K, V> OMVRBTreeEntry<K, V> leftOf(final OMVRBTreeEntry<K, V> p) {
return (p == null) ? null : p.getLeft();
}
- private static <K, V> OTreeMapEntry<K, V> rightOf(final OTreeMapEntry<K, V> p) {
+ private static <K, V> OMVRBTreeEntry<K, V> rightOf(final OMVRBTreeEntry<K, V> p) {
return (p == null) ? null : p.getRight();
}
/** From CLR */
- private void rotateLeft(final OTreeMapEntry<K, V> p) {
+ private void rotateLeft(final OMVRBTreeEntry<K, V> p) {
if (p != null) {
- OTreeMapEntry<K, V> r = p.getRight();
+ OMVRBTreeEntry<K, V> r = p.getRight();
p.setRight(r.getLeft());
if (r.getLeft() != null)
r.getLeft().setParent(p);
@@ -2088,14 +2113,14 @@ else if (p.getParent().getLeft() == p)
}
}
- protected void setRoot(final OTreeMapEntry<K, V> iRoot) {
+ protected void setRoot(final OMVRBTreeEntry<K, V> iRoot) {
root = iRoot;
}
/** From CLR */
- private void rotateRight(final OTreeMapEntry<K, V> p) {
+ private void rotateRight(final OMVRBTreeEntry<K, V> p) {
if (p != null) {
- OTreeMapEntry<K, V> l = p.getLeft();
+ OMVRBTreeEntry<K, V> l = p.getLeft();
p.setLeft(l.getRight());
if (l.getRight() != null)
l.getRight().setParent(p);
@@ -2113,22 +2138,22 @@ else if (p.getParent().getRight() == p)
/** From CLR */
/*
- * private void fixAfterInsertion(OTreeMapEntry<K, V> x) { x.setColor(RED);
+ * private void fixAfterInsertion(OMVRBTreeEntry<K, V> x) { x.setColor(RED);
*
* // if (x != null && x != root && x.getParent() != null && x.getParent().getColor() == RED) { //
* //System.out.println("BEFORE FIX on node: " + x); // printInMemoryStructure(x);
*
- * OTreeMapEntry<K, V> parent; OTreeMapEntry<K, V> grandParent;
+ * OMVRBTreeEntry<K, V> parent; OMVRBTreeEntry<K, V> grandParent;
*
* while (x != null && x != root && x.getParent() != null && x.getParent().getColor() == RED) { parent = parentOf(x); grandParent
* = parentOf(parent);
*
- * if (parent == leftOf(grandParent)) { // MY PARENT IS THE LEFT OF THE GRANDFATHER. GET MY UNCLE final OTreeMapEntry<K, V> uncle
+ * if (parent == leftOf(grandParent)) { // MY PARENT IS THE LEFT OF THE GRANDFATHER. GET MY UNCLE final OMVRBTreeEntry<K, V> uncle
* = rightOf(grandParent); if (colorOf(uncle) == RED) { // SET MY PARENT AND UNCLE TO BLACK setColor(parent, BLACK);
* setColor(uncle, BLACK); // SET GRANDPARENT'S COLOR TO RED setColor(grandParent, RED); // CONTINUE RECURSIVELY WITH MY
* GRANDFATHER x = grandParent; } else { if (x == rightOf(parent)) { // I'M THE RIGHT x = parent; parent = parentOf(x);
* grandParent = parentOf(parent); rotateLeft(x); } setColor(parent, BLACK); setColor(grandParent, RED); rotateRight(grandParent);
- * } } else { // MY PARENT IS THE RIGHT OF THE GRANDFATHER. GET MY UNCLE final OTreeMapEntry<K, V> uncle = leftOf(grandParent); if
+ * } } else { // MY PARENT IS THE RIGHT OF THE GRANDFATHER. GET MY UNCLE final OMVRBTreeEntry<K, V> uncle = leftOf(grandParent); if
* (colorOf(uncle) == RED) { setColor(parent, BLACK); setColor(uncle, BLACK); setColor(grandParent, RED); x = grandParent; } else
* { if (x == leftOf(parent)) { x = parentOf(x); parent = parentOf(x); grandParent = parentOf(parent); rotateRight(x); }
* setColor(parent, BLACK); setColor(grandParent, RED); rotateLeft(grandParent); } } }
@@ -2138,32 +2163,32 @@ else if (p.getParent().getRight() == p)
* root.setColor(BLACK); }
*/
- private OTreeMapEntry<K, V> grandparent(final OTreeMapEntry<K, V> n) {
+ private OMVRBTreeEntry<K, V> grandparent(final OMVRBTreeEntry<K, V> n) {
return parentOf(parentOf(n));
}
- private OTreeMapEntry<K, V> uncle(final OTreeMapEntry<K, V> n) {
+ private OMVRBTreeEntry<K, V> uncle(final OMVRBTreeEntry<K, V> n) {
if (parentOf(n) == leftOf(grandparent(n)))
return rightOf(grandparent(n));
else
return leftOf(grandparent(n));
}
- private void fixAfterInsertion(final OTreeMapEntry<K, V> n) {
+ private void fixAfterInsertion(final OMVRBTreeEntry<K, V> n) {
if (parentOf(n) == null)
setColor(n, BLACK);
else
insert_case2(n);
}
- private void insert_case2(final OTreeMapEntry<K, V> n) {
+ private void insert_case2(final OMVRBTreeEntry<K, V> n) {
if (colorOf(parentOf(n)) == BLACK)
return; /* Tree is still valid */
else
insert_case3(n);
}
- private void insert_case3(final OTreeMapEntry<K, V> n) {
+ private void insert_case3(final OMVRBTreeEntry<K, V> n) {
if (uncle(n) != null && colorOf(uncle(n)) == RED) {
setColor(parentOf(n), BLACK);
setColor(uncle(n), BLACK);
@@ -2173,7 +2198,7 @@ private void insert_case3(final OTreeMapEntry<K, V> n) {
insert_case4(n);
}
- private void insert_case4(OTreeMapEntry<K, V> n) {
+ private void insert_case4(OMVRBTreeEntry<K, V> n) {
if (n == rightOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) {
rotateLeft(parentOf(n));
n = leftOf(n);
@@ -2184,7 +2209,7 @@ private void insert_case4(OTreeMapEntry<K, V> n) {
insert_case5(n);
}
- private void insert_case5(final OTreeMapEntry<K, V> n) {
+ private void insert_case5(final OMVRBTreeEntry<K, V> n) {
setColor(parentOf(n), BLACK);
setColor(grandparent(n), RED);
if (n == leftOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) {
@@ -2201,7 +2226,7 @@ private void insert_case5(final OTreeMapEntry<K, V> n) {
* @param iIndex
* -1 = delete the node, otherwise the item inside of it
*/
- void deleteEntry(OTreeMapEntry<K, V> p) {
+ void deleteEntry(OMVRBTreeEntry<K, V> p) {
size--;
if (listener != null)
@@ -2221,13 +2246,13 @@ void deleteEntry(OTreeMapEntry<K, V> p) {
// If strictly internal, copy successor's element to p and then make p
// point to successor.
if (p.getLeft() != null && p.getRight() != null) {
- OTreeMapEntry<K, V> s = successor(p);
+ OMVRBTreeEntry<K, V> s = successor(p);
p.copyFrom(s);
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
- final OTreeMapEntry<K, V> replacement = (p.getLeft() != null ? p.getLeft() : p.getRight());
+ final OMVRBTreeEntry<K, V> replacement = (p.getLeft() != null ? p.getLeft() : p.getRight());
if (replacement != null) {
// Link replacement to parent
@@ -2262,10 +2287,10 @@ else if (p == p.getParent().getRight())
}
/** From CLR */
- private void fixAfterDeletion(OTreeMapEntry<K, V> x) {
+ private void fixAfterDeletion(OMVRBTreeEntry<K, V> x) {
while (x != root && colorOf(x) == BLACK) {
if (x == leftOf(parentOf(x))) {
- OTreeMapEntry<K, V> sib = rightOf(parentOf(x));
+ OMVRBTreeEntry<K, V> sib = rightOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
@@ -2291,7 +2316,7 @@ private void fixAfterDeletion(OTreeMapEntry<K, V> x) {
x = root;
}
} else { // symmetric
- OTreeMapEntry<K, V> sib = leftOf(parentOf(x));
+ OMVRBTreeEntry<K, V> sib = leftOf(parentOf(x));
if (colorOf(sib) == RED) {
setColor(sib, BLACK);
@@ -2325,11 +2350,11 @@ private void fixAfterDeletion(OTreeMapEntry<K, V> x) {
private static final long serialVersionUID = 919286545866124006L;
/**
- * Save the state of the <tt>OTreeMap</tt> instance to a stream (i.e., serialize it).
+ * Save the state of the <tt>OMVRBTree</tt> instance to a stream (i.e., serialize it).
*
- * @serialData The <i>size</i> of the OTreeMap (the number of key-value mappings) is emitted (int), followed by the key (Object)
- * and value (Object) for each key-value mapping represented by the OTreeMap. The key-value mappings are emitted in
- * key-order (as determined by the OTreeMap's Comparator, or by the keys' natural ordering if the OTreeMap has no
+ * @serialData The <i>size</i> of the OMVRBTree (the number of key-value mappings) is emitted (int), followed by the key (Object)
+ * and value (Object) for each key-value mapping represented by the OMVRBTree. The key-value mappings are emitted in
+ * key-order (as determined by the OMVRBTree's Comparator, or by the keys' natural ordering if the OMVRBTree has no
* Comparator).
*/
private void writeObject(final java.io.ObjectOutputStream s) throws java.io.IOException {
@@ -2348,7 +2373,7 @@ private void writeObject(final java.io.ObjectOutputStream s) throws java.io.IOEx
}
/**
- * Reconstitute the <tt>OTreeMap</tt> instance from a stream (i.e., deserialize it).
+ * Reconstitute the <tt>OMVRBTree</tt> instance from a stream (i.e., deserialize it).
*/
private void readObject(final java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
// Read in the Comparator and any hidden stuff
@@ -2382,7 +2407,7 @@ void addAllForOTreeSet(SortedSet<? extends K> set, V defaultVal) {
* stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it ==
* null, defaultVal != null).
*
- * It is assumed that the comparator of the OTreeMap is already set prior to calling this method.
+ * It is assumed that the comparator of the OMVRBTree is already set prior to calling this method.
*
* @param size
* the number of keys (or key-value pairs) to be read from the iterator or stream
@@ -2407,7 +2432,7 @@ private void buildFromSorted(final int size, final Iterator<?> it, final java.io
/**
* Recursive "helper method" that does the real work of the previous method. Identically named parameters have identical
- * definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the OTreeMap are
+ * definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the OMVRBTree are
* already set prior to calling this method. (It ignores both fields.)
*
* @param level
@@ -2419,7 +2444,7 @@ private void buildFromSorted(final int size, final Iterator<?> it, final java.io
* @param redLevel
* the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size.
*/
- private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo, final int hi, final int redLevel,
+ private final OMVRBTreeEntry<K, V> buildFromSorted(final int level, final int lo, final int hi, final int redLevel,
final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException,
ClassNotFoundException {
/*
@@ -2435,7 +2460,7 @@ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo,
final int mid = (lo + hi) / 2;
- OTreeMapEntry<K, V> left = null;
+ OMVRBTreeEntry<K, V> left = null;
if (lo < mid)
left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it, str, defaultVal);
@@ -2444,7 +2469,7 @@ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo,
V value;
if (it != null) {
if (defaultVal == null) {
- OTreeMapEntry<K, V> entry = (OTreeMapEntry<K, V>) it.next();
+ OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) it.next();
key = entry.getKey();
value = entry.getValue();
} else {
@@ -2456,7 +2481,7 @@ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo,
value = (defaultVal != null ? defaultVal : (V) str.readObject());
}
- final OTreeMapEntry<K, V> middle = createEntry(key, value);
+ final OMVRBTreeEntry<K, V> middle = createEntry(key, value);
// color nodes in non-full bottom most level red
if (level == redLevel)
@@ -2468,7 +2493,7 @@ private final OTreeMapEntry<K, V> buildFromSorted(final int level, final int lo,
}
if (mid < hi) {
- OTreeMapEntry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal);
+ OMVRBTreeEntry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal);
middle.setRight(right);
right.setParent(middle);
}
@@ -2500,15 +2525,15 @@ public int getPageIndex() {
private void init() {
}
- public OTreeMapEntry<K, V> getRoot() {
+ public OMVRBTreeEntry<K, V> getRoot() {
return root;
}
- protected void printInMemoryStructure(final OTreeMapEntry<K, V> iRootNode) {
+ protected void printInMemoryStructure(final OMVRBTreeEntry<K, V> iRootNode) {
printInMemoryNode("root", iRootNode, 0);
}
- private void printInMemoryNode(final String iLabel, OTreeMapEntry<K, V> iNode, int iLevel) {
+ private void printInMemoryNode(final String iLabel, OMVRBTreeEntry<K, V> iNode, int iLevel) {
if (iNode == null)
return;
@@ -2524,52 +2549,52 @@ private void printInMemoryNode(final String iLabel, OTreeMapEntry<K, V> iNode, i
}
@SuppressWarnings("rawtypes")
- public void checkTreeStructure(final OTreeMapEntry<K, V> iRootNode) {
+ public void checkTreeStructure(final OMVRBTreeEntry<K, V> iRootNode) {
if (!runtimeCheckEnabled || iRootNode == null)
return;
int currPageIndex = pageIndex;
- OTreeMapEntry<K, V> prevNode = null;
+ OMVRBTreeEntry<K, V> prevNode = null;
int i = 0;
- for (OTreeMapEntry<K, V> e = iRootNode.getFirstInMemory(); e != null; e = e.getNextInMemory()) {
+ for (OMVRBTreeEntry<K, V> e = iRootNode.getFirstInMemory(); e != null; e = e.getNextInMemory()) {
if (prevNode != null) {
if (prevNode.getTree() == null)
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Freed record %d found in memory\n", i);
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Freed record %d found in memory\n", i);
if (((Comparable) e.getFirstKey()).compareTo(((Comparable) e.getLastKey())) > 0) {
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] begin key is > than last key\n", e.getFirstKey(),
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] begin key is > than last key\n", e.getFirstKey(),
e.getLastKey());
printInMemoryStructure(iRootNode);
}
if (((Comparable) e.getFirstKey()).compareTo(((Comparable) prevNode.getLastKey())) < 0) {
OLogManager.instance().error(this,
- "[OTreeMap.checkTreeStructure] Node %s starts with a key minor than the last key of the previous node %s\n", e,
+ "[OMVRBTree.checkTreeStructure] Node %s starts with a key minor than the last key of the previous node %s\n", e,
prevNode);
printInMemoryStructure(e.getParentInMemory() != null ? e.getParentInMemory() : e);
}
}
if (e.getLeftInMemory() != null && e.getLeftInMemory() == e) {
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has left that points to itself!\n", e);
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left that points to itself!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getRightInMemory() != null && e.getRightInMemory() == e) {
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has right that points to itself!\n", e);
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has right that points to itself!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getLeftInMemory() != null && e.getLeftInMemory() == e.getRightInMemory()) {
- OLogManager.instance().error(this, "[OTreeMap.checkTreeStructure] Node %s has left and right equals!\n", e);
+ OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left and right equals!\n", e);
printInMemoryStructure(iRootNode);
}
if (e.getParentInMemory() != null && e.getParentInMemory().getRightInMemory() != e
&& e.getParentInMemory().getLeftInMemory() != e) {
OLogManager.instance().error(this,
- "[OTreeMap.checkTreeStructure] Node %s is the children of node %s but the cross-reference is missed!\n", e,
+ "[OMVRBTree.checkTreeStructure] Node %s is the children of node %s but the cross-reference is missed!\n", e,
e.getParentInMemory());
printInMemoryStructure(iRootNode);
}
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntry.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntry.java
similarity index 82%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntry.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntry.java
index 35e74c2f810..5948ec13f1a 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntry.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntry.java
@@ -18,15 +18,15 @@
import java.util.Map;
@SuppressWarnings("unchecked")
-public abstract class OTreeMapEntry<K, V> implements Map.Entry<K, V> {
- protected OTreeMap<K, V> tree;
+public abstract class OMVRBTreeEntry<K, V> implements Map.Entry<K, V> {
+ protected OMVRBTree<K, V> tree;
protected int size = 1;
protected int pageSize;
protected K[] keys;
protected V[] values;
- protected boolean color = OTreeMap.RED;
+ protected boolean color = OMVRBTree.RED;
private int pageSplitItems;
public static final int BINARY_SEARCH_THRESHOLD = 10;
@@ -35,7 +35,7 @@ public abstract class OTreeMapEntry<K, V> implements Map.Entry<K, V> {
* Constructor called on unmarshalling.
*
*/
- protected OTreeMapEntry(final OTreeMap<K, V> iTree) {
+ protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree) {
this.tree = iTree;
init();
}
@@ -43,7 +43,7 @@ protected OTreeMapEntry(final OTreeMap<K, V> iTree) {
/**
* Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color.
*/
- protected OTreeMapEntry(final OTreeMap<K, V> iTree, final K iKey, final V iValue, final OTreeMapEntry<K, V> iParent) {
+ protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree, final K iKey, final V iValue, final OMVRBTreeEntry<K, V> iParent) {
this.tree = iTree;
setParent(iParent);
this.pageSize = tree.getPageSize();
@@ -61,7 +61,7 @@ protected OTreeMapEntry(final OTreeMap<K, V> iTree, final K iKey, final V iValue
* @param iPosition
* @param iLeft
*/
- protected OTreeMapEntry(final OTreeMapEntry<K, V> iParent, final int iPosition) {
+ protected OMVRBTreeEntry(final OMVRBTreeEntry<K, V> iParent, final int iPosition) {
this.tree = iParent.tree;
this.pageSize = tree.getPageSize();
this.keys = (K[]) new Object[pageSize];
@@ -75,32 +75,32 @@ protected OTreeMapEntry(final OTreeMapEntry<K, V> iParent, final int iPosition)
init();
}
- public abstract void setLeft(OTreeMapEntry<K, V> left);
+ public abstract void setLeft(OMVRBTreeEntry<K, V> left);
- public abstract OTreeMapEntry<K, V> getLeft();
+ public abstract OMVRBTreeEntry<K, V> getLeft();
- public abstract OTreeMapEntry<K, V> setRight(OTreeMapEntry<K, V> right);
+ public abstract OMVRBTreeEntry<K, V> setRight(OMVRBTreeEntry<K, V> right);
- public abstract OTreeMapEntry<K, V> getRight();
+ public abstract OMVRBTreeEntry<K, V> getRight();
- public abstract OTreeMapEntry<K, V> setParent(OTreeMapEntry<K, V> parent);
+ public abstract OMVRBTreeEntry<K, V> setParent(OMVRBTreeEntry<K, V> parent);
- public abstract OTreeMapEntry<K, V> getParent();
+ public abstract OMVRBTreeEntry<K, V> getParent();
- protected abstract OTreeMapEntry<K, V> getLeftInMemory();
+ protected abstract OMVRBTreeEntry<K, V> getLeftInMemory();
- protected abstract OTreeMapEntry<K, V> getParentInMemory();
+ protected abstract OMVRBTreeEntry<K, V> getParentInMemory();
- protected abstract OTreeMapEntry<K, V> getRightInMemory();
+ protected abstract OMVRBTreeEntry<K, V> getRightInMemory();
- protected abstract OTreeMapEntry<K, V> getNextInMemory();
+ protected abstract OMVRBTreeEntry<K, V> getNextInMemory();
/**
* Returns the first Entry only by traversing the memory, or null if no such.
*/
- public OTreeMapEntry<K, V> getFirstInMemory() {
- OTreeMapEntry<K, V> node = this;
- OTreeMapEntry<K, V> prev = this;
+ public OMVRBTreeEntry<K, V> getFirstInMemory() {
+ OMVRBTreeEntry<K, V> node = this;
+ OMVRBTreeEntry<K, V> prev = this;
while (node != null) {
prev = node;
@@ -113,9 +113,9 @@ public OTreeMapEntry<K, V> getFirstInMemory() {
/**
* Returns the previous of the current Entry only by traversing the memory, or null if no such.
*/
- public OTreeMapEntry<K, V> getPreviousInMemory() {
- OTreeMapEntry<K, V> t = this;
- OTreeMapEntry<K, V> p = null;
+ public OMVRBTreeEntry<K, V> getPreviousInMemory() {
+ OMVRBTreeEntry<K, V> t = this;
+ OMVRBTreeEntry<K, V> p = null;
if (t.getLeftInMemory() != null) {
p = t.getLeftInMemory();
@@ -132,13 +132,13 @@ public OTreeMapEntry<K, V> getPreviousInMemory() {
return p;
}
- protected OTreeMap<K, V> getTree() {
+ protected OMVRBTree<K, V> getTree() {
return tree;
}
public int getDepth() {
int level = 0;
- OTreeMapEntry<K, V> entry = this;
+ OMVRBTreeEntry<K, V> entry = this;
while (entry.getParent() != null) {
level++;
entry = entry.getParent();
@@ -382,7 +382,7 @@ public K getFirstKey() {
return getKey(0);
}
- protected void copyFrom(final OTreeMapEntry<K, V> iSource) {
+ protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) {
keys = (K[]) new Object[iSource.keys.length];
for (int i = 0; i < iSource.keys.length; ++i)
keys[i] = iSource.keys[i];
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntryMemory.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntryMemory.java
similarity index 56%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntryMemory.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntryMemory.java
index 771cee6e36e..0a31d9f9269 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEntryMemory.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEntryMemory.java
@@ -15,23 +15,23 @@
*/
package com.orientechnologies.common.collection;
-public class OTreeMapEntryMemory<K, V> extends OTreeMapEntry<K, V> {
- protected OTreeMapEntryMemory<K, V> left = null;
- protected OTreeMapEntryMemory<K, V> right = null;
- protected OTreeMapEntryMemory<K, V> parent;
+public class OMVRBTreeEntryMemory<K, V> extends OMVRBTreeEntry<K, V> {
+ protected OMVRBTreeEntryMemory<K, V> left = null;
+ protected OMVRBTreeEntryMemory<K, V> right = null;
+ protected OMVRBTreeEntryMemory<K, V> parent;
/**
* Constructor called on unmarshalling.
*
*/
- protected OTreeMapEntryMemory(final OTreeMap<K, V> iTree) {
+ protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree) {
super(iTree);
}
/**
* Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color.
*/
- protected OTreeMapEntryMemory(final OTreeMap<K, V> iTree, final K iKey, final V iValue, final OTreeMapEntryMemory<K, V> iParent) {
+ protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree, final K iKey, final V iValue, final OMVRBTreeEntryMemory<K, V> iParent) {
super(iTree, iKey, iValue, iParent);
}
@@ -42,26 +42,26 @@ protected OTreeMapEntryMemory(final OTreeMap<K, V> iTree, final K iKey, final V
* @param iPosition
* @param iLeft
*/
- protected OTreeMapEntryMemory(final OTreeMapEntry<K, V> iParent, final int iPosition) {
+ protected OMVRBTreeEntryMemory(final OMVRBTreeEntry<K, V> iParent, final int iPosition) {
super(iParent, iPosition);
setParent(iParent);
}
@Override
- public void setLeft(final OTreeMapEntry<K, V> left) {
- this.left = (OTreeMapEntryMemory<K, V>) left;
+ public void setLeft(final OMVRBTreeEntry<K, V> left) {
+ this.left = (OMVRBTreeEntryMemory<K, V>) left;
if (left != null && left.getParent() != this)
left.setParent(this);
}
@Override
- public OTreeMapEntry<K, V> getLeft() {
+ public OMVRBTreeEntry<K, V> getLeft() {
return left;
}
@Override
- public OTreeMapEntry<K, V> setRight(final OTreeMapEntry<K, V> right) {
- this.right = (OTreeMapEntryMemory<K, V>) right;
+ public OMVRBTreeEntry<K, V> setRight(final OMVRBTreeEntry<K, V> right) {
+ this.right = (OMVRBTreeEntryMemory<K, V>) right;
if (right != null && right.getParent() != this)
right.setParent(this);
@@ -69,27 +69,27 @@ public OTreeMapEntry<K, V> setRight(final OTreeMapEntry<K, V> right) {
}
@Override
- public OTreeMapEntry<K, V> getRight() {
+ public OMVRBTreeEntry<K, V> getRight() {
return right;
}
@Override
- public OTreeMapEntry<K, V> setParent(final OTreeMapEntry<K, V> parent) {
- this.parent = (OTreeMapEntryMemory<K, V>) parent;
+ public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> parent) {
+ this.parent = (OMVRBTreeEntryMemory<K, V>) parent;
return parent;
}
@Override
- public OTreeMapEntry<K, V> getParent() {
+ public OMVRBTreeEntry<K, V> getParent() {
return parent;
}
/**
* Returns the successor of the current Entry only by traversing the memory, or null if no such.
*/
- public OTreeMapEntryMemory<K, V> getNextInMemory() {
- OTreeMapEntryMemory<K, V> t = this;
- OTreeMapEntryMemory<K, V> p = null;
+ public OMVRBTreeEntryMemory<K, V> getNextInMemory() {
+ OMVRBTreeEntryMemory<K, V> t = this;
+ OMVRBTreeEntryMemory<K, V> p = null;
if (t.right != null) {
p = t.right;
@@ -107,17 +107,17 @@ public OTreeMapEntryMemory<K, V> getNextInMemory() {
}
@Override
- protected OTreeMapEntry<K, V> getLeftInMemory() {
+ protected OMVRBTreeEntry<K, V> getLeftInMemory() {
return left;
}
@Override
- protected OTreeMapEntry<K, V> getParentInMemory() {
+ protected OMVRBTreeEntry<K, V> getParentInMemory() {
return parent;
}
@Override
- protected OTreeMapEntry<K, V> getRightInMemory() {
+ protected OMVRBTreeEntry<K, V> getRightInMemory() {
return right;
}
}
\ No newline at end of file
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEventListener.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEventListener.java
similarity index 81%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEventListener.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEventListener.java
index aeb6525b69b..a1b4862fbaf 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapEventListener.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeEventListener.java
@@ -20,8 +20,8 @@
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*/
-public interface OTreeMapEventListener<K, V> {
- public void signalTreeChanged(OTreeMap<K, V> iTree);
+public interface OMVRBTreeEventListener<K, V> {
+ public void signalTreeChanged(OMVRBTree<K, V> iTree);
- public void signalNodeChanged(OTreeMapEntry<K, V> iNode);
+ public void signalNodeChanged(OMVRBTreeEntry<K, V> iNode);
}
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapMemory.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeMemory.java
similarity index 65%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeMapMemory.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeMemory.java
index f089a091b99..3353de43801 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeMapMemory.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeMemory.java
@@ -20,22 +20,23 @@
import java.util.SortedMap;
@SuppressWarnings("serial")
-public class OTreeMapMemory<K, V> extends OTreeMap<K, V> {
+public class OMVRBTreeMemory<K, V> extends OMVRBTree<K, V> {
/**
- * Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the
- * {@link Comparable} interface. Furthermore, all such keys must be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not
- * throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts to put a key into
- * the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers),
- * the <tt>put(Object key, Object value)</tt> call will throw a <tt>ClassCastException</tt>.
+ * Memory based MVRB-Tree implementation. Constructs a new, empty tree map, using the natural ordering of its keys. All keys
+ * inserted into the map must implement the {@link Comparable} interface. Furthermore, all such keys must be <i>mutually
+ * comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt>
+ * in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put
+ * a string key into a map whose keys are integers), the <tt>put(Object key, Object value)</tt> call will throw a
+ * <tt>ClassCastException</tt>.
*/
- public OTreeMapMemory() {
+ public OMVRBTreeMemory() {
}
- public OTreeMapMemory(final int iSize, final float iLoadFactor) {
+ public OMVRBTreeMemory(final int iSize, final float iLoadFactor) {
super(iSize, iLoadFactor);
}
- public OTreeMapMemory(final OTreeMapEventListener<K, V> iListener) {
+ public OMVRBTreeMemory(final OMVRBTreeEventListener<K, V> iListener) {
super(iListener);
}
@@ -50,7 +51,7 @@ public OTreeMapMemory(final OTreeMapEventListener<K, V> iListener) {
* the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of
* the keys will be used.
*/
- public OTreeMapMemory(final Comparator<? super K> comparator) {
+ public OMVRBTreeMemory(final Comparator<? super K> comparator) {
super(comparator);
}
@@ -67,7 +68,7 @@ public OTreeMapMemory(final Comparator<? super K> comparator) {
* @throws NullPointerException
* if the specified map is null
*/
- public OTreeMapMemory(final Map<? extends K, ? extends V> m) {
+ public OMVRBTreeMemory(final Map<? extends K, ? extends V> m) {
super(m);
}
@@ -80,17 +81,17 @@ public OTreeMapMemory(final Map<? extends K, ? extends V> m) {
* @throws NullPointerException
* if the specified map is null
*/
- public OTreeMapMemory(final SortedMap<K, ? extends V> m) {
+ public OMVRBTreeMemory(final SortedMap<K, ? extends V> m) {
super(m);
}
@Override
- protected OTreeMapEntry<K, V> createEntry(final K key, final V value) {
- return new OTreeMapEntryMemory<K, V>(this, key, value, null);
+ protected OMVRBTreeEntry<K, V> createEntry(final K key, final V value) {
+ return new OMVRBTreeEntryMemory<K, V>(this, key, value, null);
}
@Override
- protected OTreeMapEntry<K, V> createEntry(final OTreeMapEntry<K, V> parent) {
- return new OTreeMapEntryMemory<K, V>(parent, parent.getPageSplitItems());
+ protected OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent) {
+ return new OMVRBTreeEntryMemory<K, V>(parent, parent.getPageSplitItems());
}
}
diff --git a/commons/src/main/java/com/orientechnologies/common/collection/OTreeSetMemory.java b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeSetMemory.java
similarity index 90%
rename from commons/src/main/java/com/orientechnologies/common/collection/OTreeSetMemory.java
rename to commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeSetMemory.java
index 0d07bdb049d..f09e2c4fda2 100644
--- a/commons/src/main/java/com/orientechnologies/common/collection/OTreeSetMemory.java
+++ b/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTreeSetMemory.java
@@ -24,7 +24,7 @@
import java.util.SortedSet;
@SuppressWarnings("unchecked")
-public class OTreeSetMemory<E> extends AbstractSet<E> implements ONavigableSet<E>, Cloneable, java.io.Serializable {
+public class OMVRBTreeSetMemory<E> extends AbstractSet<E> implements ONavigableSet<E>, Cloneable, java.io.Serializable {
/**
* The backing map.
*/
@@ -36,7 +36,7 @@ public class OTreeSetMemory<E> extends AbstractSet<E> implements ONavigableSet<E
/**
* Constructs a set backed by the specified navigable map.
*/
- OTreeSetMemory(ONavigableMap<E, Object> m) {
+ OMVRBTreeSetMemory(ONavigableMap<E, Object> m) {
this.m = m;
}
@@ -47,8 +47,8 @@ public class OTreeSetMemory<E> extends AbstractSet<E> implements ONavigableSet<E
* the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string
* element to a set whose elements are integers), the {@code add} call will throw a {@code ClassCastException}.
*/
- public OTreeSetMemory() {
- this(new OTreeMapMemory<E, Object>());
+ public OMVRBTreeSetMemory() {
+ this(new OMVRBTreeMemory<E, Object>());
}
/**
@@ -61,8 +61,8 @@ public OTreeSetMemory() {
* the comparator that will be used to order this set. If {@code null}, the {@linkplain Comparable natural ordering} of
* the elements will be used.
*/
- public OTreeSetMemory(Comparator<? super E> comparator) {
- this(new OTreeMapMemory<E, Object>(comparator));
+ public OMVRBTreeSetMemory(Comparator<? super E> comparator) {
+ this(new OMVRBTreeMemory<E, Object>(comparator));
}
/**
@@ -78,7 +78,7 @@ public OTreeSetMemory(Comparator<? super E> comparator) {
* @throws NullPointerException
* if the specified collection is null
*/
- public OTreeSetMemory(Collection<? extends E> c) {
+ public OMVRBTreeSetMemory(Collection<? extends E> c) {
this();
addAll(c);
}
@@ -91,7 +91,7 @@ public OTreeSetMemory(Collection<? extends E> c) {
* @throws NullPointerException
* if the specified sorted set is null
*/
- public OTreeSetMemory(SortedSet<E> s) {
+ public OMVRBTreeSetMemory(SortedSet<E> s) {
this(s.comparator());
addAll(s);
}
@@ -120,7 +120,7 @@ public Iterator<E> descendingIterator() {
* @since 1.6
*/
public ONavigableSet<E> descendingSet() {
- return new OTreeSetMemory<E>(m.descendingMap());
+ return new OMVRBTreeSetMemory<E>(m.descendingMap());
}
/**
@@ -220,9 +220,9 @@ public void clear() {
@Override
public boolean addAll(Collection<? extends E> c) {
// Use linear-time version if applicable
- if (m.size() == 0 && c.size() > 0 && c instanceof SortedSet && m instanceof OTreeMap) {
+ if (m.size() == 0 && c.size() > 0 && c instanceof SortedSet && m instanceof OMVRBTree) {
SortedSet<? extends E> set = (SortedSet<? extends E>) c;
- OTreeMap<E, Object> map = (OTreeMap<E, Object>) m;
+ OMVRBTree<E, Object> map = (OMVRBTree<E, Object>) m;
Comparator<? super E> cc = (Comparator<? super E>) set.comparator();
Comparator<? super E> mc = map.comparator();
if (cc == mc || (cc != null && cc.equals(mc))) {
@@ -244,7 +244,7 @@ public boolean addAll(Collection<? extends E> c) {
* @since 1.6
*/
public ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
- return new OTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
+ return new OMVRBTreeSetMemory<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
/**
@@ -257,7 +257,7 @@ public ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement
* @since 1.6
*/
public ONavigableSet<E> headSet(E toElement, boolean inclusive) {
- return new OTreeSetMemory<E>(m.headMap(toElement, inclusive));
+ return new OMVRBTreeSetMemory<E>(m.headMap(toElement, inclusive));
}
/**
@@ -270,7 +270,7 @@ public ONavigableSet<E> headSet(E toElement, boolean inclusive) {
* @since 1.6
*/
public ONavigableSet<E> tailSet(E fromElement, boolean inclusive) {
- return new OTreeSetMemory<E>(m.tailMap(fromElement, inclusive));
+ return new OMVRBTreeSetMemory<E>(m.tailMap(fromElement, inclusive));
}
/**
@@ -399,14 +399,14 @@ public E pollLast() {
*/
@Override
public Object clone() {
- OTreeSetMemory<E> clone = null;
+ OMVRBTreeSetMemory<E> clone = null;
try {
- clone = (OTreeSetMemory<E>) super.clone();
+ clone = (OMVRBTreeSetMemory<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
- clone.m = new OTreeMapMemory<E, Object>(m);
+ clone.m = new OMVRBTreeMemory<E, Object>(m);
return clone;
}
@@ -443,12 +443,12 @@ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException,
// Read in Comparator
Comparator<? super E> c = (Comparator<? super E>) s.readObject();
- // Create backing OTreeMap
- OTreeMap<E, Object> tm;
+ // Create backing OMVRBTree
+ OMVRBTree<E, Object> tm;
if (c == null)
- tm = new OTreeMapMemory<E, Object>();
+ tm = new OMVRBTreeMemory<E, Object>();
else
- tm = new OTreeMapMemory<E, Object>(c);
+ tm = new OMVRBTreeMemory<E, Object>(c);
m = tm;
// Read in size
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabase.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabase.java
index de3c17879c3..50226478abb 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabase.java
@@ -197,7 +197,7 @@ public interface ODatabase {
public long countClusterElements(String iClusterName);
/**
- * Adds a logical cluster. Logical clusters don't need separate files since are stored inside a OTreeMap instance. Access is
+ * Adds a logical cluster. Logical clusters don't need separate files since are stored inside a OMVRBTree instance. Access is
* slower than the physical cluster but the database size is reduced and less files are requires. This matters in some OS where a
* single process has limitation for the number of files can open. Most accessed entities should be stored inside a physical
* cluster.
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/kv/OKVDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/db/kv/OKVDatabase.java
index 818c87c50a2..8f9d19af7c2 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/kv/OKVDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/kv/OKVDatabase.java
@@ -7,27 +7,27 @@
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
import com.orientechnologies.orient.core.storage.impl.local.ODictionaryLocal;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabase;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabase;
public class OKVDatabase extends ODatabaseDocumentTx {
public OKVDatabase(final String iURL) {
super(iURL);
}
- public OTreeMapDatabase<String, String> getBucket(final ODatabaseRecordAbstract<ORecordBytes> iDb, final String iBucket)
+ public OMVRBTreeDatabase<String, String> getBucket(final ODatabaseRecordAbstract<ORecordBytes> iDb, final String iBucket)
throws IOException {
ORecordBytes rec = iDb.getDictionary().get(iBucket);
- OTreeMapDatabase<String, String> bucketTree = null;
+ OMVRBTreeDatabase<String, String> bucketTree = null;
if (rec != null) {
- bucketTree = new OTreeMapDatabase<String, String>(iDb, rec.getIdentity());
+ bucketTree = new OMVRBTreeDatabase<String, String>(iDb, rec.getIdentity());
bucketTree.load();
}
if (bucketTree == null) {
// CREATE THE BUCKET
- bucketTree = new OTreeMapDatabase<String, String>(iDb, ODictionaryLocal.DICTIONARY_DEF_CLUSTER_NAME,
+ bucketTree = new OMVRBTreeDatabase<String, String>(iDb, ODictionaryLocal.DICTIONARY_DEF_CLUSTER_NAME,
OStreamSerializerString.INSTANCE, OStreamSerializerString.INSTANCE);
bucketTree.save();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexFullText.java b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexFullText.java
index 91e6a298d28..ab4531e5465 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexFullText.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexFullText.java
@@ -32,7 +32,7 @@
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerListRID;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabaseLazySave;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabaseLazySave;
/**
* Fast index for full-text searches.
@@ -81,7 +81,7 @@ public OPropertyIndex create(final ODatabaseRecord<?> iDatabase, final OProperty
while (db != null && !(db instanceof ODatabaseRecord<?>))
db = db.getUnderlying();
- map = new OTreeMapDatabaseLazySave<String, List<ORecordId>>((ODatabaseRecord<?>) db, iClusterIndexName,
+ map = new OMVRBTreeDatabaseLazySave<String, List<ORecordId>>((ODatabaseRecord<?>) db, iClusterIndexName,
OStreamSerializerString.INSTANCE, OStreamSerializerListRID.INSTANCE);
map.lazySave();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexMVRBTreeAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexMVRBTreeAbstract.java
index 55f3e730cdd..ad7783a6074 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexMVRBTreeAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexMVRBTreeAbstract.java
@@ -31,7 +31,7 @@
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerListRID;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabaseLazySave;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabaseLazySave;
/**
* Handles indexing when records change.
@@ -41,7 +41,7 @@
*/
public abstract class OPropertyIndexMVRBTreeAbstract extends OSharedResource implements OPropertyIndex {
protected OProperty owner;
- protected OTreeMapDatabaseLazySave<String, List<ORecordId>> map;
+ protected OMVRBTreeDatabaseLazySave<String, List<ORecordId>> map;
public OPropertyIndexMVRBTreeAbstract() {
}
@@ -75,7 +75,7 @@ public OPropertyIndexMVRBTreeAbstract(final ODatabaseRecord<?> iDatabase, final
public OPropertyIndex create(final ODatabaseRecord<?> iDatabase, final OProperty iProperty, final String iClusterIndexName,
final OProgressListener iProgressListener) {
owner = iProperty;
- map = new OTreeMapDatabaseLazySave<String, List<ORecordId>>(iDatabase, iClusterIndexName, OStreamSerializerString.INSTANCE,
+ map = new OMVRBTreeDatabaseLazySave<String, List<ORecordId>>(iDatabase, iClusterIndexName, OStreamSerializerString.INSTANCE,
OStreamSerializerListRID.INSTANCE);
rebuild(iProgressListener);
return this;
@@ -233,7 +233,7 @@ public Iterator<Entry<String, List<ORecordId>>> iterator() {
}
protected void init(final ODatabaseRecord<?> iDatabase, final ORID iRecordId) {
- map = new OTreeMapDatabaseLazySave<String, List<ORecordId>>(iDatabase, iRecordId);
+ map = new OMVRBTreeDatabaseLazySave<String, List<ORecordId>>(iDatabase, iRecordId);
map.load();
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java
index d83295720ac..b2bb660e3f8 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java
@@ -26,7 +26,7 @@
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OClusterPositionIterator;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
-import com.orientechnologies.orient.core.storage.tree.OTreeMapStorage;
+import com.orientechnologies.orient.core.storage.tree.OMVRBTreeStorage;
/**
* Handle a cluster using a logical structure stored into a real physical local cluster.<br/>
@@ -39,7 +39,7 @@ public class OClusterLogical implements OCluster {
private int id;
private int localClusterId;
- private OTreeMapStorage<Long, OPhysicalPosition> map;
+ private OMVRBTreeStorage<Long, OPhysicalPosition> map;
private OPhysicalPosition total;
private OSharedResourceExternal lock = new OSharedResourceExternal();
@@ -61,7 +61,7 @@ public OClusterLogical(final OStorageLocal iStorage, final int iId, final String
this(iName, iId, iPhysicalClusterId);
try {
- map = new OTreeMapStorage<Long, OPhysicalPosition>(iStorage, iStorage.getClusterById(iPhysicalClusterId).getName(),
+ map = new OMVRBTreeStorage<Long, OPhysicalPosition>(iStorage, iStorage.getClusterById(iPhysicalClusterId).getName(),
OStreamSerializerLong.INSTANCE, OStreamSerializerAnyStreamable.INSTANCE);
map.getRecord().setIdentity(iPhysicalClusterId, ORID.CLUSTER_POS_INVALID);
@@ -87,7 +87,7 @@ public OClusterLogical(final OStorageLocal iStorage, final String iName, final i
this(iName, iId, 0);
try {
- map = new OTreeMapStorage<Long, OPhysicalPosition>(iStorage, iStorage.getClusterById(iRecordId.getClusterId()).getName(),
+ map = new OMVRBTreeStorage<Long, OPhysicalPosition>(iStorage, iStorage.getClusterById(iRecordId.getClusterId()).getName(),
iRecordId);
map.load();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODictionaryLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODictionaryLocal.java
index 72a736a3874..cb87386e8c2 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODictionaryLocal.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/ODictionaryLocal.java
@@ -31,14 +31,14 @@
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyRecord;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
import com.orientechnologies.orient.core.storage.OStorage;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabase;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabase;
@SuppressWarnings("unchecked")
public class ODictionaryLocal<T extends Object> implements ODictionaryInternal<T> {
public static final String DICTIONARY_DEF_CLUSTER_NAME = OStorage.CLUSTER_INTERNAL_NAME;
private ODatabaseComplex<T> database;
- private OTreeMapDatabase<String, T> tree;
+ private OMVRBTreeDatabase<String, T> tree;
public String clusterName = DICTIONARY_DEF_CLUSTER_NAME;
@@ -75,14 +75,14 @@ public int size() {
}
public void load() {
- tree = new OTreeMapDatabase<String, T>((ODatabaseRecord<?>) database, new ORecordId(
+ tree = new OMVRBTreeDatabase<String, T>((ODatabaseRecord<?>) database, new ORecordId(
database.getStorage().getConfiguration().dictionaryRecordId));
tree.load();
}
public void create() {
try {
- tree = new OTreeMapDatabase<String, T>((ODatabaseRecord<?>) database, clusterName, OStreamSerializerString.INSTANCE,
+ tree = new OMVRBTreeDatabase<String, T>((ODatabaseRecord<?>) database, clusterName, OStreamSerializerString.INSTANCE,
new OStreamSerializerAnyRecord((ODatabaseRecord<? extends ORecord<?>>) database));
tree.save();
@@ -93,7 +93,7 @@ public void create() {
}
}
- public OTreeMapDatabase<String, T> getTree() {
+ public OMVRBTreeDatabase<String, T> getTree() {
return tree;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapEntryStorage.java b/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeEntryStorage.java
similarity index 62%
rename from core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapEntryStorage.java
rename to core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeEntryStorage.java
index 39b59a4b6b9..2c6f4d31e19 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapEntryStorage.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeEntryStorage.java
@@ -17,11 +17,11 @@
import java.io.IOException;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.storage.ORawBuffer;
-import com.orientechnologies.orient.core.type.tree.OTreeMapEntryPersistent;
-import com.orientechnologies.orient.core.type.tree.OTreeMapPersistent;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeEntryPersistent;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreePersistent;
/**
* Persistent TreeMap implementation that use a OStorage instance to handle the entries. This class can't be used also from the
@@ -34,27 +34,27 @@
* @param <V>
* Value type
*/
-public class OTreeMapEntryStorage<K, V> extends OTreeMapEntryPersistent<K, V> {
+public class OMVRBTreeEntryStorage<K, V> extends OMVRBTreeEntryPersistent<K, V> {
- public OTreeMapEntryStorage(OTreeMapEntry<K, V> iParent, int iPosition) {
+ public OMVRBTreeEntryStorage(OMVRBTreeEntry<K, V> iParent, int iPosition) {
super(iParent, iPosition);
record.setIdentity(pTree.getRecord().getIdentity().getClusterId(), ORID.CLUSTER_POS_INVALID);
}
- public OTreeMapEntryStorage(OTreeMapPersistent<K, V> iTree, K key, V value, OTreeMapEntryPersistent<K, V> iParent) {
+ public OMVRBTreeEntryStorage(OMVRBTreePersistent<K, V> iTree, K key, V value, OMVRBTreeEntryPersistent<K, V> iParent) {
super(iTree, key, value, iParent);
record.setIdentity(pTree.getRecord().getIdentity().getClusterId(), ORID.CLUSTER_POS_INVALID);
}
- public OTreeMapEntryStorage(OTreeMapPersistent<K, V> iTree, OTreeMapEntryPersistent<K, V> iParent, ORID iRecordId)
+ public OMVRBTreeEntryStorage(OMVRBTreePersistent<K, V> iTree, OMVRBTreeEntryPersistent<K, V> iParent, ORID iRecordId)
throws IOException {
super(iTree, iParent, iRecordId);
load();
}
@Override
- public OTreeMapEntryStorage<K, V> load() throws IOException {
- ORawBuffer raw = ((OTreeMapStorage<K, V>) tree).storage.readRecord(null, -1, record.getIdentity().getClusterId(), record
+ public OMVRBTreeEntryStorage<K, V> load() throws IOException {
+ ORawBuffer raw = ((OMVRBTreeStorage<K, V>) tree).storage.readRecord(null, -1, record.getIdentity().getClusterId(), record
.getIdentity().getClusterPosition(), null);
record.setVersion(raw.version);
@@ -65,18 +65,18 @@ public OTreeMapEntryStorage<K, V> load() throws IOException {
}
@Override
- public OTreeMapEntryStorage<K, V> save() throws IOException {
+ public OMVRBTreeEntryStorage<K, V> save() throws IOException {
record.fromStream(toStream());
if (record.getIdentity().isValid())
// UPDATE IT WITHOUT VERSION CHECK SINCE ALL IT'S LOCKED
- record.setVersion(((OTreeMapStorage<K, V>) tree).storage.updateRecord(0, record.getIdentity().getClusterId(), record
+ record.setVersion(((OMVRBTreeStorage<K, V>) tree).storage.updateRecord(0, record.getIdentity().getClusterId(), record
.getIdentity().getClusterPosition(), record.toStream(), -1, record.getRecordType()));
else {
// CREATE IT
record.setIdentity(
record.getIdentity().getClusterId(),
- ((OTreeMapStorage<K, V>) tree).storage.createRecord(record.getIdentity().getClusterId(), record.toStream(),
+ ((OMVRBTreeStorage<K, V>) tree).storage.createRecord(record.getIdentity().getClusterId(), record.toStream(),
record.getRecordType()));
}
record.unsetDirty();
@@ -91,17 +91,17 @@ public OTreeMapEntryStorage<K, V> save() throws IOException {
*
* @throws IOException
*/
- public OTreeMapEntryStorage<K, V> delete() throws IOException {
+ public OMVRBTreeEntryStorage<K, V> delete() throws IOException {
// EARLY LOAD LEFT AND DELETE IT RECURSIVELY
if (getLeft() != null)
- ((OTreeMapEntryPersistent<K, V>) getLeft()).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) getLeft()).delete();
// EARLY LOAD RIGHT AND DELETE IT RECURSIVELY
if (getRight() != null)
- ((OTreeMapEntryPersistent<K, V>) getRight()).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) getRight()).delete();
// DELETE MYSELF
- ((OTreeMapStorage<K, V>) tree).storage.deleteRecord(0, record.getIdentity(), record.getVersion());
+ ((OMVRBTreeStorage<K, V>) tree).storage.deleteRecord(0, record.getIdentity(), record.getVersion());
// FORCE REMOVING OF K/V AND SEIALIZED K/V AS WELL
keys = null;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapStorage.java b/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeStorage.java
similarity index 71%
rename from core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapStorage.java
rename to core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeStorage.java
index 6bdca91ed28..cb346b89e58 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OTreeMapStorage.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/tree/OMVRBTreeStorage.java
@@ -17,7 +17,7 @@
import java.io.IOException;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.serialization.OMemoryInputStream;
@@ -26,28 +26,28 @@
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.impl.local.OClusterLogical;
import com.orientechnologies.orient.core.storage.impl.local.OStorageLocal;
-import com.orientechnologies.orient.core.type.tree.OTreeMapEntryPersistent;
-import com.orientechnologies.orient.core.type.tree.OTreeMapPersistent;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeEntryPersistent;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreePersistent;
/**
- * Persistent TreeMap implementation. The difference with the class OTreeMapPersistent is the level. In facts this class works
+ * Persistent MVRB-Tree implementation. The difference with the class OMVRBTreeDatabase is the level. In facts this class works
* directly at the storage level, while the other at database level. This class is used for Logical Clusters. It can'be
* transactional.
*
* @see OClusterLogical
*/
@SuppressWarnings("serial")
-public class OTreeMapStorage<K, V> extends OTreeMapPersistent<K, V> {
+public class OMVRBTreeStorage<K, V> extends OMVRBTreePersistent<K, V> {
protected OStorageLocal storage;
int clusterId;
- public OTreeMapStorage(final OStorageLocal iStorage, final String iClusterName, final ORID iRID) {
+ public OMVRBTreeStorage(final OStorageLocal iStorage, final String iClusterName, final ORID iRID) {
super(iClusterName, iRID);
storage = iStorage;
clusterId = storage.getClusterIdByName(OStorageLocal.CLUSTER_INTERNAL_NAME);
}
- public OTreeMapStorage(final OStorageLocal iStorage, String iClusterName, final OStreamSerializer iKeySerializer,
+ public OMVRBTreeStorage(final OStorageLocal iStorage, String iClusterName, final OStreamSerializer iKeySerializer,
final OStreamSerializer iValueSerializer) {
super(iClusterName, iKeySerializer, iValueSerializer);
storage = iStorage;
@@ -55,23 +55,23 @@ public OTreeMapStorage(final OStorageLocal iStorage, String iClusterName, final
}
@Override
- protected OTreeMapEntryPersistent<K, V> createEntry(OTreeMapEntry<K, V> iParent) {
- return new OTreeMapEntryStorage<K, V>(iParent, iParent.getPageSplitItems());
+ protected OMVRBTreeEntryPersistent<K, V> createEntry(OMVRBTreeEntry<K, V> iParent) {
+ return new OMVRBTreeEntryStorage<K, V>(iParent, iParent.getPageSplitItems());
}
@Override
- protected OTreeMapEntryPersistent<K, V> createEntry(final K key, final V value) {
+ protected OMVRBTreeEntryPersistent<K, V> createEntry(final K key, final V value) {
adjustPageSize();
- return new OTreeMapEntryStorage<K, V>(this, key, value, null);
+ return new OMVRBTreeEntryStorage<K, V>(this, key, value, null);
}
@Override
- protected OTreeMapEntryStorage<K, V> loadEntry(OTreeMapEntryPersistent<K, V> iParent, ORID iRecordId) throws IOException {
- OTreeMapEntryStorage<K, V> entry = null;//(OTreeMapEntryStorage<K, V>) cache.get(iRecordId);
+ protected OMVRBTreeEntryStorage<K, V> loadEntry(OMVRBTreeEntryPersistent<K, V> iParent, ORID iRecordId) throws IOException {
+ OMVRBTreeEntryStorage<K, V> entry = null;// (OMVRBTreeEntryStorage<K, V>) cache.get(iRecordId);
if (entry == null) {
// NOT FOUND: CREATE IT AND PUT IT INTO THE CACHE
- entry = new OTreeMapEntryStorage<K, V>(this, iParent, iRecordId);
-// cache.put(iRecordId, entry);
+ entry = new OMVRBTreeEntryStorage<K, V>(this, iParent, iRecordId);
+ // cache.put(iRecordId, entry);
} else
// FOUND: ASSIGN IT
entry.setParent(iParent);
@@ -80,7 +80,7 @@ protected OTreeMapEntryStorage<K, V> loadEntry(OTreeMapEntryPersistent<K, V> iPa
}
@Override
- public OTreeMapPersistent<K, V> load() throws IOException {
+ public OMVRBTreePersistent<K, V> load() throws IOException {
lock.acquireExclusiveLock();
try {
@@ -101,7 +101,7 @@ public OTreeMapPersistent<K, V> load() throws IOException {
}
@Override
- public OTreeMapPersistent<K, V> save() throws IOException {
+ public OMVRBTreePersistent<K, V> save() throws IOException {
lock.acquireExclusiveLock();
try {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabase.java
similarity index 64%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabase.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabase.java
index 891a928909b..2139ee62b79 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabase.java
@@ -17,24 +17,29 @@
import java.io.IOException;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.serialization.OMemoryInputStream;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializer;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerFactory;
+/**
+ * Persistent MVRB-Tree implementation. The difference with the class OMVRBTreeStorage is the level. In facts this class works
+ * directly at the database level, while the other at storage level.
+ *
+ */
@SuppressWarnings("serial")
-public class OTreeMapDatabase<K, V> extends OTreeMapPersistent<K, V> {
+public class OMVRBTreeDatabase<K, V> extends OMVRBTreePersistent<K, V> {
protected ODatabaseRecord<?> database;
- public OTreeMapDatabase(final ODatabaseRecord<?> iDatabase, final ORID iRID) {
+ public OMVRBTreeDatabase(final ODatabaseRecord<?> iDatabase, final ORID iRID) {
super(iDatabase.getClusterNameById(iRID.getClusterId()), iRID);
database = iDatabase;
record.setDatabase(iDatabase);
}
- public OTreeMapDatabase(final ODatabaseRecord<?> iDatabase, String iClusterName, final OStreamSerializer iKeySerializer,
+ public OMVRBTreeDatabase(final ODatabaseRecord<?> iDatabase, String iClusterName, final OStreamSerializer iKeySerializer,
final OStreamSerializer iValueSerializer) {
super(iClusterName, iKeySerializer, iValueSerializer);
database = iDatabase;
@@ -42,26 +47,26 @@ public OTreeMapDatabase(final ODatabaseRecord<?> iDatabase, String iClusterName,
}
@Override
- protected OTreeMapEntryDatabase<K, V> createEntry(final K key, final V value) {
+ protected OMVRBTreeEntryDatabase<K, V> createEntry(final K key, final V value) {
adjustPageSize();
- return new OTreeMapEntryDatabase<K, V>(this, key, value, null);
+ return new OMVRBTreeEntryDatabase<K, V>(this, key, value, null);
}
@Override
- protected OTreeMapEntryDatabase<K, V> createEntry(final OTreeMapEntry<K, V> parent) {
+ protected OMVRBTreeEntryDatabase<K, V> createEntry(final OMVRBTreeEntry<K, V> parent) {
adjustPageSize();
- return new OTreeMapEntryDatabase<K, V>(parent, parent.getPageSplitItems());
+ return new OMVRBTreeEntryDatabase<K, V>(parent, parent.getPageSplitItems());
}
@Override
- protected OTreeMapEntryDatabase<K, V> loadEntry(final OTreeMapEntryPersistent<K, V> iParent, final ORID iRecordId)
+ protected OMVRBTreeEntryDatabase<K, V> loadEntry(final OMVRBTreeEntryPersistent<K, V> iParent, final ORID iRecordId)
throws IOException {
// SEARCH INTO THE CACHE
- OTreeMapEntryDatabase<K, V> entry = null;// (OTreeMapEntryDatabase<K, V>) cache.get(iRecordId);
+ OMVRBTreeEntryDatabase<K, V> entry = null;// (OMVRBTreeEntryDatabase<K, V>) cache.get(iRecordId);
if (entry == null) {
// NOT FOUND: CREATE IT AND PUT IT INTO THE CACHE
- entry = new OTreeMapEntryDatabase<K, V>(this, (OTreeMapEntryDatabase<K, V>) iParent, iRecordId);
+ entry = new OMVRBTreeEntryDatabase<K, V>(this, (OMVRBTreeEntryDatabase<K, V>) iParent, iRecordId);
// cache.put(iRecordId, entry);
} else {
// entry.load();
@@ -78,7 +83,7 @@ public ODatabaseRecord<?> getDatabase() {
}
@Override
- public OTreeMapPersistent<K, V> load() {
+ public OMVRBTreePersistent<K, V> load() {
if (!record.getIdentity().isValid())
// NOTHING TO LOAD
return this;
@@ -98,7 +103,7 @@ public OTreeMapPersistent<K, V> load() {
}
@Override
- public OTreeMapPersistent<K, V> save() throws IOException {
+ public OMVRBTreePersistent<K, V> save() throws IOException {
lock.acquireExclusiveLock();
try {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabaseLazySave.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabaseLazySave.java
similarity index 88%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabaseLazySave.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabaseLazySave.java
index 60b2c448337..0e5949e9969 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapDatabaseLazySave.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeDatabaseLazySave.java
@@ -33,16 +33,16 @@
* @author Luca Garulli
*/
@SuppressWarnings("serial")
-public class OTreeMapDatabaseLazySave<K, V> extends OTreeMapDatabase<K, V> implements ODatabaseLifecycleListener {
+public class OMVRBTreeDatabaseLazySave<K, V> extends OMVRBTreeDatabase<K, V> implements ODatabaseLifecycleListener {
protected int maxUpdatesBeforeSave;
protected int updates = 0;
- public OTreeMapDatabaseLazySave(ODatabaseRecord<?> iDatabase, ORID iRID) {
+ public OMVRBTreeDatabaseLazySave(ODatabaseRecord<?> iDatabase, ORID iRID) {
super(iDatabase, iRID);
init(iDatabase);
}
- public OTreeMapDatabaseLazySave(ODatabaseRecord<?> iDatabase, String iClusterName, OStreamSerializer iKeySerializer,
+ public OMVRBTreeDatabaseLazySave(ODatabaseRecord<?> iDatabase, String iClusterName, OStreamSerializer iKeySerializer,
OStreamSerializer iValueSerializer) {
super(iDatabase, iClusterName, iKeySerializer, iValueSerializer);
init(iDatabase);
@@ -78,7 +78,7 @@ public void onTxRollback(ODatabase iDatabase) {
entryPoints.clear();
try {
if (root != null)
- ((OTreeMapEntryDatabase<K, V>) root).load();
+ ((OMVRBTreeEntryDatabase<K, V>) root).load();
} catch (IOException e) {
throw new OIndexException("Error on loading root node");
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryDatabase.java
similarity index 74%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryDatabase.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryDatabase.java
index 766dba45260..e2b159ed23b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryDatabase.java
@@ -17,7 +17,7 @@
import java.io.IOException;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.id.ORID;
@@ -33,7 +33,7 @@
* @param <V>
* Value type
*/
-public class OTreeMapEntryDatabase<K, V> extends OTreeMapEntryPersistent<K, V> {
+public class OMVRBTreeEntryDatabase<K, V> extends OMVRBTreeEntryPersistent<K, V> {
/**
* Called on event of splitting an entry.
*
@@ -43,9 +43,9 @@ public class OTreeMapEntryDatabase<K, V> extends OTreeMapEntryPersistent<K, V> {
* Current position
* @param iLeft
*/
- public OTreeMapEntryDatabase(OTreeMapEntry<K, V> iParent, int iPosition) {
+ public OMVRBTreeEntryDatabase(OMVRBTreeEntry<K, V> iParent, int iPosition) {
super(iParent, iPosition);
- record.setDatabase(((OTreeMapDatabase<K, V>) pTree).database);
+ record.setDatabase(((OMVRBTreeDatabase<K, V>) pTree).database);
}
/**
@@ -58,27 +58,27 @@ public OTreeMapEntryDatabase(OTreeMapEntry<K, V> iParent, int iPosition) {
* @param iRecordId
* Record to unmarshall
*/
- public OTreeMapEntryDatabase(OTreeMapDatabase<K, V> iTree, OTreeMapEntryDatabase<K, V> iParent, ORID iRecordId)
+ public OMVRBTreeEntryDatabase(OMVRBTreeDatabase<K, V> iTree, OMVRBTreeEntryDatabase<K, V> iParent, ORID iRecordId)
throws IOException {
super(iTree, iParent, iRecordId);
record.setDatabase(iTree.database);
load();
}
- public OTreeMapEntryDatabase(OTreeMapDatabase<K, V> iTree, K key, V value, OTreeMapEntryDatabase<K, V> iParent) {
+ public OMVRBTreeEntryDatabase(OMVRBTreeDatabase<K, V> iTree, K key, V value, OMVRBTreeEntryDatabase<K, V> iParent) {
super(iTree, key, value, iParent);
record.setDatabase(iTree.database);
}
@Override
- public OTreeMapEntryDatabase<K, V> load() throws IOException {
+ public OMVRBTreeEntryDatabase<K, V> load() throws IOException {
record.load();
fromStream(record.toStream());
return this;
}
@Override
- public OTreeMapEntryDatabase<K, V> save() throws OSerializationException {
+ public OMVRBTreeEntryDatabase<K, V> save() throws OSerializationException {
if (!record.isDirty())
return this;
@@ -102,15 +102,15 @@ public OTreeMapEntryDatabase<K, V> save() throws OSerializationException {
*
* @throws IOException
*/
- public OTreeMapEntryDatabase<K, V> delete() throws IOException {
+ public OMVRBTreeEntryDatabase<K, V> delete() throws IOException {
// EARLY LOAD LEFT AND DELETE IT RECURSIVELY
if (getLeft() != null)
- ((OTreeMapEntryPersistent<K, V>) getLeft()).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) getLeft()).delete();
leftRid = null;
// EARLY LOAD RIGHT AND DELETE IT RECURSIVELY
if (getRight() != null)
- ((OTreeMapEntryPersistent<K, V>) getRight()).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) getRight()).delete();
rightRid = null;
// DELETE MYSELF
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryPersistent.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
similarity index 83%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryPersistent.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
index 183fc89f875..d82791166c1 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapEntryPersistent.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
@@ -18,7 +18,7 @@
import java.io.IOException;
import java.util.Set;
-import com.orientechnologies.common.collection.OTreeMapEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.orient.core.exception.OConfigurationException;
@@ -80,8 +80,8 @@
* @param <V>
*/
@SuppressWarnings("unchecked")
-public abstract class OTreeMapEntryPersistent<K, V> extends OTreeMapEntry<K, V> implements OSerializableStream {
- protected OTreeMapPersistent<K, V> pTree;
+public abstract class OMVRBTreeEntryPersistent<K, V> extends OMVRBTreeEntry<K, V> implements OSerializableStream {
+ protected OMVRBTreePersistent<K, V> pTree;
byte[][] serializedKeys;
byte[][] serializedValues;
@@ -92,9 +92,9 @@ public abstract class OTreeMapEntryPersistent<K, V> extends OTreeMapEntry<K, V>
public ORecordBytesLazy record;
- protected OTreeMapEntryPersistent<K, V> parent;
- protected OTreeMapEntryPersistent<K, V> left;
- protected OTreeMapEntryPersistent<K, V> right;
+ protected OMVRBTreeEntryPersistent<K, V> parent;
+ protected OMVRBTreeEntryPersistent<K, V> left;
+ protected OMVRBTreeEntryPersistent<K, V> right;
/**
* Called on event of splitting an entry.
@@ -105,9 +105,9 @@ public abstract class OTreeMapEntryPersistent<K, V> extends OTreeMapEntry<K, V>
* Current position
* @param iLeft
*/
- public OTreeMapEntryPersistent(final OTreeMapEntry<K, V> iParent, final int iPosition) {
+ public OMVRBTreeEntryPersistent(final OMVRBTreeEntry<K, V> iParent, final int iPosition) {
super(iParent, iPosition);
- pTree = (OTreeMapPersistent<K, V>) tree;
+ pTree = (OMVRBTreePersistent<K, V>) tree;
record = new ORecordBytesLazy(this);
setParent(iParent);
@@ -122,7 +122,7 @@ record = new ORecordBytesLazy(this);
serializedKeys = new byte[pageSize][];
serializedValues = new byte[pageSize][];
- final OTreeMapEntryPersistent<K, V> p = (OTreeMapEntryPersistent<K, V>) iParent;
+ final OMVRBTreeEntryPersistent<K, V> p = (OMVRBTreeEntryPersistent<K, V>) iParent;
System.arraycopy(p.serializedKeys, iPosition, serializedKeys, 0, size);
System.arraycopy(p.serializedValues, iPosition, serializedValues, 0, size);
@@ -140,19 +140,19 @@ record = new ORecordBytesLazy(this);
* @param iRecordId
* Record to unmarshall
*/
- public OTreeMapEntryPersistent(final OTreeMapPersistent<K, V> iTree, final OTreeMapEntryPersistent<K, V> iParent,
+ public OMVRBTreeEntryPersistent(final OMVRBTreePersistent<K, V> iTree, final OMVRBTreeEntryPersistent<K, V> iParent,
final ORID iRecordId) throws IOException {
super(iTree);
pTree = iTree;
record = new ORecordBytesLazy(this);
record.setIdentity((ORecordId) iRecordId);
- parent = (OTreeMapEntryPersistent<K, V>) iParent;
+ parent = (OMVRBTreeEntryPersistent<K, V>) iParent;
parentRid = iParent == null ? ORecordId.EMPTY_RECORD_ID : parent.record.getIdentity();
}
- public OTreeMapEntryPersistent(final OTreeMapPersistent<K, V> iTree, final K key, final V value,
- final OTreeMapEntryPersistent<K, V> iParent) {
+ public OMVRBTreeEntryPersistent(final OMVRBTreePersistent<K, V> iTree, final K key, final V value,
+ final OMVRBTreeEntryPersistent<K, V> iParent) {
super(iTree, key, value, iParent);
pTree = iTree;
@@ -170,22 +170,22 @@ record = new ORecordBytesLazy(this);
markDirty();
}
- public OTreeMapEntryPersistent<K, V> load() throws IOException {
+ public OMVRBTreeEntryPersistent<K, V> load() throws IOException {
return this;
}
- public OTreeMapEntryPersistent<K, V> save() throws IOException {
+ public OMVRBTreeEntryPersistent<K, V> save() throws IOException {
return this;
}
- public OTreeMapEntryPersistent<K, V> delete() throws IOException {
+ public OMVRBTreeEntryPersistent<K, V> delete() throws IOException {
pTree.removeEntryPoint(this);
// if (record.getIdentity().isValid())
// pTree.cache.remove(record.getIdentity());
// DELETE THE NODE FROM THE PENDING RECORDS TO COMMIT
- for (OTreeMapEntryPersistent<K, V> node : pTree.recordsToCommit) {
+ for (OMVRBTreeEntryPersistent<K, V> node : pTree.recordsToCommit) {
if (node.record.getIdentity().equals(record.getIdentity())) {
pTree.recordsToCommit.remove(node);
break;
@@ -274,10 +274,10 @@ protected int checkToDisconnect(final int iDepthLevel) {
public int getDepthInMemory() {
int level = 0;
- OTreeMapEntryPersistent<K, V> entry = this;
+ OMVRBTreeEntryPersistent<K, V> entry = this;
while (entry.parent != null) {
level++;
- entry = (OTreeMapEntryPersistent<K, V>) entry.parent;
+ entry = (OMVRBTreeEntryPersistent<K, V>) entry.parent;
}
return level;
}
@@ -285,16 +285,16 @@ public int getDepthInMemory() {
@Override
public int getDepth() {
int level = 0;
- OTreeMapEntryPersistent<K, V> entry = this;
+ OMVRBTreeEntryPersistent<K, V> entry = this;
while (entry.getParent() != null) {
level++;
- entry = (OTreeMapEntryPersistent<K, V>) entry.getParent();
+ entry = (OMVRBTreeEntryPersistent<K, V>) entry.getParent();
}
return level;
}
@Override
- public OTreeMapEntry<K, V> getParent() {
+ public OMVRBTreeEntry<K, V> getParent() {
if (parentRid == null)
return null;
@@ -331,11 +331,11 @@ else if (parent.rightRid.isValid() && parent.rightRid.equals(record.getIdentity(
}
@Override
- public OTreeMapEntry<K, V> setParent(final OTreeMapEntry<K, V> iParent) {
+ public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> iParent) {
if (iParent != getParent()) {
markDirty();
- this.parent = (OTreeMapEntryPersistent<K, V>) iParent;
+ this.parent = (OMVRBTreeEntryPersistent<K, V>) iParent;
this.parentRid = iParent == null ? ORecordId.EMPTY_RECORD_ID : parent.record.getIdentity();
if (parent != null) {
@@ -353,7 +353,7 @@ public OTreeMapEntry<K, V> setParent(final OTreeMapEntry<K, V> iParent) {
}
@Override
- public OTreeMapEntry<K, V> getLeft() {
+ public OMVRBTreeEntry<K, V> getLeft() {
if (left == null && leftRid.isValid()) {
try {
// System.out.println("Node " + record.getIdentity() + " is loading LEFT node " + leftRid + "...");
@@ -371,11 +371,11 @@ public OTreeMapEntry<K, V> getLeft() {
}
@Override
- public void setLeft(final OTreeMapEntry<K, V> iLeft) {
+ public void setLeft(final OMVRBTreeEntry<K, V> iLeft) {
if (iLeft == left)
return;
- left = (OTreeMapEntryPersistent<K, V>) iLeft;
+ left = (OMVRBTreeEntryPersistent<K, V>) iLeft;
// if (left == null || !left.record.getIdentity().isValid() || !left.record.getIdentity().equals(leftRid)) {
markDirty();
this.leftRid = iLeft == null ? ORecordId.EMPTY_RECORD_ID : left.record.getIdentity();
@@ -388,7 +388,7 @@ public void setLeft(final OTreeMapEntry<K, V> iLeft) {
}
@Override
- public OTreeMapEntry<K, V> getRight() {
+ public OMVRBTreeEntry<K, V> getRight() {
if (rightRid.isValid() && right == null) {
// LAZY LOADING OF THE RIGHT LEAF
try {
@@ -406,11 +406,11 @@ public OTreeMapEntry<K, V> getRight() {
}
@Override
- public OTreeMapEntry<K, V> setRight(final OTreeMapEntry<K, V> iRight) {
+ public OMVRBTreeEntry<K, V> setRight(final OMVRBTreeEntry<K, V> iRight) {
if (iRight == right)
return this;
- right = (OTreeMapEntryPersistent<K, V>) iRight;
+ right = (OMVRBTreeEntryPersistent<K, V>) iRight;
// if (right == null || !right.record.getIdentity().isValid() || !right.record.getIdentity().equals(rightRid)) {
markDirty();
rightRid = iRight == null ? ORecordId.EMPTY_RECORD_ID : right.record.getIdentity();
@@ -458,10 +458,10 @@ public void checkEntryStructure() {
}
@Override
- protected void copyFrom(final OTreeMapEntry<K, V> iSource) {
+ protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) {
markDirty();
- final OTreeMapEntryPersistent<K, V> source = (OTreeMapEntryPersistent<K, V>) iSource;
+ final OMVRBTreeEntryPersistent<K, V> source = (OMVRBTreeEntryPersistent<K, V>) iSource;
parent = source.parent;
left = source.left;
@@ -528,7 +528,7 @@ protected void remove() {
public K getKeyAt(final int iIndex) {
if (keys[iIndex] == null)
try {
- OProfiler.getInstance().updateCounter("OTreeMapEntryP.unserializeKey", 1);
+ OProfiler.getInstance().updateCounter("OMVRBTreeEntryP.unserializeKey", 1);
keys[iIndex] = (K) pTree.keySerializer.fromStream(serializedKeys[iIndex]);
} catch (IOException e) {
@@ -544,7 +544,7 @@ public K getKeyAt(final int iIndex) {
protected V getValueAt(final int iIndex) {
if (values[iIndex] == null)
try {
- OProfiler.getInstance().updateCounter("OTreeMapEntryP.unserializeValue", 1);
+ OProfiler.getInstance().updateCounter("OMVRBTreeEntryP.unserializeValue", 1);
values[iIndex] = (V) pTree.valueSerializer.fromStream(serializedValues[iIndex]);
} catch (IOException e) {
@@ -594,9 +594,9 @@ private int getMaxDepthInMemory(final int iCurrDepthLevel) {
/**
* Returns the successor of the current Entry only by traversing the memory, or null if no such.
*/
- public OTreeMapEntryPersistent<K, V> getNextInMemory() {
- OTreeMapEntryPersistent<K, V> t = this;
- OTreeMapEntryPersistent<K, V> p = null;
+ public OMVRBTreeEntryPersistent<K, V> getNextInMemory() {
+ OMVRBTreeEntryPersistent<K, V> t = this;
+ OMVRBTreeEntryPersistent<K, V> p = null;
if (t.right != null) {
p = t.right;
@@ -657,7 +657,7 @@ public final OSerializableStream fromStream(final byte[] iStream) throws OSerial
} finally {
buffer.close();
- OProfiler.getInstance().stopChrono("OTreeMapEntryP.fromStream", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreeEntryP.fromStream", timer);
}
}
@@ -675,7 +675,7 @@ public final byte[] toStream() throws OSerializationException {
// FORCE DIRTY
parent.record.setDirty();
- ((OTreeMapEntryDatabase<K, V>) parent).save();
+ ((OMVRBTreeEntryDatabase<K, V>) parent).save();
parentRid = parent.record.getIdentity();
record.setDirty();
}
@@ -684,7 +684,7 @@ public final byte[] toStream() throws OSerializationException {
// FORCE DIRTY
left.record.setDirty();
- ((OTreeMapEntryDatabase<K, V>) left).save();
+ ((OMVRBTreeEntryDatabase<K, V>) left).save();
leftRid = left.record.getIdentity();
record.setDirty();
}
@@ -693,7 +693,7 @@ public final byte[] toStream() throws OSerializationException {
// FORCE DIRTY
right.record.setDirty();
- ((OTreeMapEntryDatabase<K, V>) right).save();
+ ((OMVRBTreeEntryDatabase<K, V>) right).save();
rightRid = right.record.getIdentity();
record.setDirty();
}
@@ -736,7 +736,7 @@ public final byte[] toStream() throws OSerializationException {
checkEntryStructure();
- OProfiler.getInstance().stopChrono("OTreeMapEntryP.toStream", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreeEntryP.toStream", timer);
}
}
@@ -748,7 +748,7 @@ public final byte[] toStream() throws OSerializationException {
private void serializeNewKeys() throws IOException {
for (int i = 0; i < size; ++i) {
if (serializedKeys[i] == null) {
- OProfiler.getInstance().updateCounter("OTreeMapEntryP.serializeValue", 1);
+ OProfiler.getInstance().updateCounter("OMVRBTreeEntryP.serializeValue", 1);
serializedKeys[i] = pTree.keySerializer.toStream(keys[i]);
}
@@ -763,7 +763,7 @@ private void serializeNewKeys() throws IOException {
private void serializeNewValues() throws IOException {
for (int i = 0; i < size; ++i) {
if (serializedValues[i] == null) {
- OProfiler.getInstance().updateCounter("OTreeMapEntryP.serializeKey", 1);
+ OProfiler.getInstance().updateCounter("OMVRBTreeEntryP.serializeKey", 1);
serializedValues[i] = pTree.valueSerializer.toStream(values[i]);
}
@@ -791,10 +791,10 @@ private void markDirty() {
// public boolean equals(final Object o) {
// if (this == o)
// return true;
- // if (!(o instanceof OTreeMapEntryPersistent<?, ?>))
+ // if (!(o instanceof OMVRBTreeEntryPersistent<?, ?>))
// return false;
//
- // final OTreeMapEntryPersistent<?, ?> e = (OTreeMapEntryPersistent<?, ?>) o;
+ // final OMVRBTreeEntryPersistent<?, ?> e = (OMVRBTreeEntryPersistent<?, ?>) o;
//
// if (record != null && e.record != null)
// return record.getIdentity().equals(e.record.getIdentity());
@@ -809,17 +809,17 @@ private void markDirty() {
// }
@Override
- protected OTreeMapEntry<K, V> getLeftInMemory() {
+ protected OMVRBTreeEntry<K, V> getLeftInMemory() {
return left;
}
@Override
- protected OTreeMapEntry<K, V> getParentInMemory() {
+ protected OMVRBTreeEntry<K, V> getParentInMemory() {
return parent;
}
@Override
- protected OTreeMapEntry<K, V> getRightInMemory() {
+ protected OMVRBTreeEntry<K, V> getRightInMemory() {
return right;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapPersistent.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
similarity index 78%
rename from core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapPersistent.java
rename to core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
index 6d9bb304349..83a432d849c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OTreeMapPersistent.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
@@ -23,9 +23,9 @@
import java.util.Map;
import java.util.Set;
-import com.orientechnologies.common.collection.OTreeMap;
-import com.orientechnologies.common.collection.OTreeMapEntry;
-import com.orientechnologies.common.collection.OTreeMapEventListener;
+import com.orientechnologies.common.collection.OMVRBTree;
+import com.orientechnologies.common.collection.OMVRBTreeEntry;
+import com.orientechnologies.common.collection.OMVRBTreeEventListener;
import com.orientechnologies.common.concur.resource.OSharedResourceExternal;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.OProfiler;
@@ -43,17 +43,15 @@
import com.orientechnologies.orient.core.serialization.OSerializableStream;
import com.orientechnologies.orient.core.serialization.serializer.record.OSerializationThreadLocal;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializer;
-import com.orientechnologies.orient.core.storage.impl.local.OClusterLogical;
/**
- * Persistent TreeMap implementation. The difference with the class OTreeMapPersistent is the level. In facts this class works
- * directly at the storage level, while the other at database level. This class is used for Logical Clusters. It can'be
+ * Persistent based MVRB-Tree implementation. The difference with the class OMVRBTreePersistent is the level. In facts this class
+ * works directly at the storage level, while the other at database level. This class is used for Logical Clusters. It can'be
* transactional. It uses the entryPoints linked list to get the best entry point for searching a node.
*
- * @see OClusterLogical
*/
@SuppressWarnings("serial")
-public abstract class OTreeMapPersistent<K, V> extends OTreeMap<K, V> implements OTreeMapEventListener<K, V>, OSerializableStream {
+public abstract class OMVRBTreePersistent<K, V> extends OMVRBTree<K, V> implements OMVRBTreeEventListener<K, V>, OSerializableStream {
protected int optimizeThreshold;
protected OSharedResourceExternal lock = new OSharedResourceExternal();
@@ -61,7 +59,7 @@ public abstract class OTreeMapPersistent<K, V> extends OTreeMap<K, V> implements
protected OStreamSerializer keySerializer;
protected OStreamSerializer valueSerializer;
- protected final Set<OTreeMapEntryPersistent<K, V>> recordsToCommit = new HashSet<OTreeMapEntryPersistent<K, V>>();
+ protected final Set<OMVRBTreeEntryPersistent<K, V>> recordsToCommit = new HashSet<OMVRBTreeEntryPersistent<K, V>>();
protected final OMemoryOutputStream entryRecordBuffer;
protected final String clusterName;
@@ -72,20 +70,20 @@ public abstract class OTreeMapPersistent<K, V> extends OTreeMap<K, V> implements
// STORES IN MEMORY DIRECT REFERENCES TO PORTION OF THE TREE
protected int entryPointsSize;
protected float optimizeEntryPointsFactor;
- protected volatile List<OTreeMapEntryPersistent<K, V>> entryPoints = new ArrayList<OTreeMapEntryPersistent<K, V>>(
+ protected volatile List<OMVRBTreeEntryPersistent<K, V>> entryPoints = new ArrayList<OMVRBTreeEntryPersistent<K, V>>(
entryPointsSize);
- protected List<OTreeMapEntryPersistent<K, V>> newEntryPoints = new ArrayList<OTreeMapEntryPersistent<K, V>>(
+ protected List<OMVRBTreeEntryPersistent<K, V>> newEntryPoints = new ArrayList<OMVRBTreeEntryPersistent<K, V>>(
entryPointsSize);
- // protected Map<ORID, OTreeMapEntryPersistent<K, V>> cache = new HashMap<ORID, OTreeMapEntryPersistent<K, V>>();
+ // protected Map<ORID, OMVRBTreeEntryPersistent<K, V>> cache = new HashMap<ORID, OMVRBTreeEntryPersistent<K, V>>();
- public OTreeMapPersistent(final String iClusterName, final ORID iRID) {
+ public OMVRBTreePersistent(final String iClusterName, final ORID iRID) {
this(iClusterName, null, null);
record.setIdentity(iRID.getClusterId(), iRID.getClusterPosition());
config();
}
- public OTreeMapPersistent(String iClusterName, final OStreamSerializer iKeySerializer, final OStreamSerializer iValueSerializer) {
+ public OMVRBTreePersistent(String iClusterName, final OStreamSerializer iKeySerializer, final OStreamSerializer iValueSerializer) {
// MINIMIZE I/O USING A LARGER PAGE THAN THE DEFAULT USED IN MEMORY
super(1024, 0.7f);
config();
@@ -101,16 +99,16 @@ record = new ORecordBytesLazy(this);
setListener(this);
}
- public abstract OTreeMapPersistent<K, V> load() throws IOException;
+ public abstract OMVRBTreePersistent<K, V> load() throws IOException;
- public abstract OTreeMapPersistent<K, V> save() throws IOException;
+ public abstract OMVRBTreePersistent<K, V> save() throws IOException;
protected abstract void serializerFromStream(OMemoryInputStream stream) throws IOException;
/**
* Lazy loads a node.
*/
- protected abstract OTreeMapEntryPersistent<K, V> loadEntry(OTreeMapEntryPersistent<K, V> iParent, ORID iRecordId)
+ protected abstract OMVRBTreeEntryPersistent<K, V> loadEntry(OMVRBTreeEntryPersistent<K, V> iParent, ORID iRecordId)
throws IOException;
@Override
@@ -120,7 +118,7 @@ public void clear() {
try {
if (root != null) {
- ((OTreeMapEntryPersistent<K, V>) root).delete();
+ ((OMVRBTreeEntryPersistent<K, V>) root).delete();
super.clear();
getListener().signalTreeChanged(this);
}
@@ -135,7 +133,7 @@ public void clear() {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.clear", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.clear", timer);
}
}
@@ -148,7 +146,7 @@ public void unload() {
try {
// DISCONNECT ALL THE NODES
- for (OTreeMapEntryPersistent<K, V> entryPoint : entryPoints)
+ for (OMVRBTreeEntryPersistent<K, V> entryPoint : entryPoints)
entryPoint.disconnect(true);
entryPoints.clear();
@@ -165,7 +163,7 @@ public void unload() {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.unload", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.unload", timer);
}
}
@@ -185,7 +183,7 @@ public void optimize() {
// printInMemoryStructure();
- OTreeMapEntryPersistent<K, V> pRoot = (OTreeMapEntryPersistent<K, V>) root;
+ OMVRBTreeEntryPersistent<K, V> pRoot = (OMVRBTreeEntryPersistent<K, V>) root;
final int depth = pRoot.getMaxDepthInMemory();
@@ -196,8 +194,8 @@ public void optimize() {
pRoot.checkToDisconnect((int) (entryPointsSize * optimizeEntryPointsFactor));
if (isRuntimeCheckEnabled()) {
- for (OTreeMapEntryPersistent<K, V> entryPoint : entryPoints)
- for (OTreeMapEntryPersistent<K, V> e = (OTreeMapEntryPersistent<K, V>) entryPoint.getFirstInMemory(); e != null; e = e
+ for (OMVRBTreeEntryPersistent<K, V> entryPoint : entryPoints)
+ for (OMVRBTreeEntryPersistent<K, V> e = (OMVRBTreeEntryPersistent<K, V>) entryPoint.getFirstInMemory(); e != null; e = e
.getNextInMemory())
e.checkEntryStructure();
}
@@ -208,14 +206,14 @@ public void optimize() {
if (isRuntimeCheckEnabled()) {
if (entryPoints.size() > 0)
- for (OTreeMapEntryPersistent<K, V> entryPoint : entryPoints)
+ for (OMVRBTreeEntryPersistent<K, V> entryPoint : entryPoints)
checkTreeStructure(entryPoint.getFirstInMemory());
else
checkTreeStructure(root);
}
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.optimize", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.optimize", timer);
if (OLogManager.instance().isDebugEnabled())
OLogManager.instance().debug(this, "Optimization completed in %d ms\n", System.currentTimeMillis() - timer);
@@ -239,7 +237,7 @@ public V put(final K key, final V value) {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.put", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.put", timer);
}
}
@@ -260,7 +258,7 @@ public void putAll(final Map<? extends K, ? extends V> map) {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.putAll", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.putAll", timer);
}
}
@@ -286,7 +284,7 @@ public void commitChanges(final ODatabaseRecord<?> iDatabase) {
try {
if (recordsToCommit.size() > 0) {
- final List<OTreeMapEntryPersistent<K, V>> tmp = new ArrayList<OTreeMapEntryPersistent<K, V>>();
+ final List<OMVRBTreeEntryPersistent<K, V>> tmp = new ArrayList<OMVRBTreeEntryPersistent<K, V>>();
while (recordsToCommit.iterator().hasNext()) {
// COMMIT BEFORE THE NEW RECORDS (TO ASSURE RID IN RELATIONSHIPS)
@@ -294,7 +292,7 @@ public void commitChanges(final ODatabaseRecord<?> iDatabase) {
recordsToCommit.clear();
- for (OTreeMapEntryPersistent<K, V> node : tmp)
+ for (OMVRBTreeEntryPersistent<K, V> node : tmp)
if (node.record.isDirty()) {
if (iDatabase != null)
// REPLACE THE DATABASE WITH THE NEW ACQUIRED
@@ -325,7 +323,7 @@ public void commitChanges(final ODatabaseRecord<?> iDatabase) {
} finally {
lock.releaseExclusiveLock();
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.commitChanges", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.commitChanges", timer);
}
}
@@ -352,11 +350,11 @@ public OSerializableStream fromStream(final byte[] iStream) throws OSerializatio
} catch (Exception e) {
- OLogManager.instance().error(this, "Error on unmarshalling OTreeMapPersistent object from record: %s", e,
+ OLogManager.instance().error(this, "Error on unmarshalling OMVRBTreePersistent object from record: %s", e,
OSerializationException.class, rootRid);
} finally {
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.fromStream", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.fromStream", timer);
}
return this;
}
@@ -377,7 +375,7 @@ public byte[] toStream() throws OSerializationException {
try {
if (root != null) {
- OTreeMapEntryPersistent<K, V> pRoot = (OTreeMapEntryPersistent<K, V>) root;
+ OMVRBTreeEntryPersistent<K, V> pRoot = (OMVRBTreeEntryPersistent<K, V>) root;
if (pRoot.record.getIdentity().isNew()) {
// FIRST TIME: SAVE IT
pRoot.save();
@@ -401,16 +399,16 @@ public byte[] toStream() throws OSerializationException {
} finally {
marshalledRecords.remove(identityRecord);
- OProfiler.getInstance().stopChrono("OTreeMapPersistent.toStream", timer);
+ OProfiler.getInstance().stopChrono("OMVRBTreePersistent.toStream", timer);
}
}
- public void signalTreeChanged(final OTreeMap<K, V> iTree) {
+ public void signalTreeChanged(final OMVRBTree<K, V> iTree) {
record.setDirty();
}
- public void signalNodeChanged(final OTreeMapEntry<K, V> iNode) {
- recordsToCommit.add((OTreeMapEntryPersistent<K, V>) iNode);
+ public void signalNodeChanged(final OMVRBTreeEntry<K, V> iNode) {
+ recordsToCommit.add((OMVRBTreeEntryPersistent<K, V>) iNode);
}
@Override
@@ -601,7 +599,7 @@ protected void updateUsageCounter() {
*/
@SuppressWarnings("unchecked")
@Override
- protected OTreeMapEntry<K, V> getBestEntryPoint(final Object iKey) {
+ protected OMVRBTreeEntry<K, V> getBestEntryPoint(final Object iKey) {
final Comparable<? super K> key = (Comparable<? super K>) iKey;
if (entryPoints.size() == 0)
@@ -609,11 +607,11 @@ protected OTreeMapEntry<K, V> getBestEntryPoint(final Object iKey) {
return root;
// SEARCH THE BEST KEY
- OTreeMapEntryPersistent<K, V> e;
+ OMVRBTreeEntryPersistent<K, V> e;
int entryPointSize = entryPoints.size();
int cmp;
- OTreeMapEntryPersistent<K, V> bestNode = null;
- if (entryPointSize < OTreeMapEntry.BINARY_SEARCH_THRESHOLD) {
+ OMVRBTreeEntryPersistent<K, V> bestNode = null;
+ if (entryPointSize < OMVRBTreeEntry.BINARY_SEARCH_THRESHOLD) {
// LINEAR SEARCH
for (int i = 0; i < entryPointSize; ++i) {
e = entryPoints.get(i);
@@ -687,7 +685,7 @@ protected OTreeMapEntry<K, V> getBestEntryPoint(final Object iKey) {
/**
* Remove an entry point from the list
*/
- void removeEntryPoint(final OTreeMapEntryPersistent<K, V> iEntry) {
+ void removeEntryPoint(final OMVRBTreeEntryPersistent<K, V> iEntry) {
for (int i = 0; i < entryPoints.size(); ++i)
if (entryPoints.get(i) == iEntry) {
entryPoints.remove(i);
@@ -696,16 +694,16 @@ void removeEntryPoint(final OTreeMapEntryPersistent<K, V> iEntry) {
}
/**
- * Returns the first Entry in the OTreeMap (according to the OTreeMap's key-sort function). Returns null if the OTreeMap is empty.
+ * Returns the first Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is empty.
*/
@Override
- protected OTreeMapEntry<K, V> getFirstEntry() {
+ protected OMVRBTreeEntry<K, V> getFirstEntry() {
if (entryPoints.size() > 0) {
// FIND THE FIRST ELEMENT STARTING FROM THE FIRST NODE
- OTreeMapEntryPersistent<K, V> e = entryPoints.get(0);
+ OMVRBTreeEntryPersistent<K, V> e = entryPoints.get(0);
while (e.getLeft() != null) {
- e = (OTreeMapEntryPersistent<K, V>) e.getLeft();
+ e = (OMVRBTreeEntryPersistent<K, V>) e.getLeft();
}
return e;
}
@@ -715,12 +713,12 @@ protected OTreeMapEntry<K, V> getFirstEntry() {
// private void printInMemoryStructure() {
// System.out.println("* Entrypoints (" + entryPoints.size() + "), in cache=" + cache.size() + ": *");
- // for (OTreeMapEntryPersistent<K, V> entryPoint : entryPoints)
+ // for (OMVRBTreeEntryPersistent<K, V> entryPoint : entryPoints)
// printInMemoryStructure(entryPoint);
// }
@Override
- protected void setRoot(final OTreeMapEntry<K, V> iRoot) {
+ protected void setRoot(final OMVRBTreeEntry<K, V> iRoot) {
if (iRoot == root)
return;
diff --git a/kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynch.java b/kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynch.java
similarity index 59%
rename from kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynch.java
rename to kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynch.java
index a8dd0f816a0..952cea1fc7e 100644
--- a/kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynch.java
+++ b/kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynch.java
@@ -4,46 +4,46 @@
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializer;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabase;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabase;
import com.orientechnologies.orient.kv.OSharedBinaryDatabase;
/**
* Wrapper class for persistent tree map. It handles the asynchronous commit of changes done by the external
- * OTreeMapPersistentAsynchThread singleton thread.
+ * OMVRBTreePersistentAsynchThread singleton thread.
*
* @author Luca Garulli
*
* @param <K>
* @param <V>
- * @see OTreeMapPersistentAsynchThread
+ * @see OMVRBTreePersistentAsynchThread
*/
@SuppressWarnings("serial")
-public class OTreeMapPersistentAsynch<K, V> extends OTreeMapDatabase<K, V> {
+public class OMVRBTreePersistentAsynch<K, V> extends OMVRBTreeDatabase<K, V> {
- public OTreeMapPersistentAsynch(final ODatabaseRecord<?> iDatabase, final String iClusterName,
+ public OMVRBTreePersistentAsynch(final ODatabaseRecord<?> iDatabase, final String iClusterName,
final OStreamSerializer iKeySerializer, final OStreamSerializer iValueSerializer) {
super(iDatabase, iClusterName, iKeySerializer, iValueSerializer);
- OTreeMapPersistentAsynchThread.getInstance().registerMap(this);
+ OMVRBTreePersistentAsynchThread.getInstance().registerMap(this);
}
- public OTreeMapPersistentAsynch(final ODatabaseRecord<?> iDatabase, final ORID iRID) {
+ public OMVRBTreePersistentAsynch(final ODatabaseRecord<?> iDatabase, final ORID iRID) {
super(iDatabase, iRID);
- OTreeMapPersistentAsynchThread.getInstance().registerMap(this);
+ OMVRBTreePersistentAsynchThread.getInstance().registerMap(this);
}
/**
- * Doesn't commit changes since they are scheduled by the external OTreeMapPersistentAsynchThread singleton thread.
+ * Doesn't commit changes since they are scheduled by the external OMVRBTreePersistentAsynchThread singleton thread.
*
- * @see OTreeMapPersistentAsynchThread#execute()
+ * @see OMVRBTreePersistentAsynchThread#execute()
*/
@Override
public void commitChanges(final ODatabaseRecord<?> iDatabase) {
}
/**
- * Commits changes for real. It's called by OTreeMapPersistentAsynchThread singleton thread.
+ * Commits changes for real. It's called by OMVRBTreePersistentAsynchThread singleton thread.
*
- * @see OTreeMapPersistentAsynchThread#execute()
+ * @see OMVRBTreePersistentAsynchThread#execute()
*/
public void executeCommitChanges() {
ODatabaseBinary db = null;
diff --git a/kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynchThread.java b/kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynchThread.java
similarity index 73%
rename from kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynchThread.java
rename to kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynchThread.java
index 232780bd2e9..54251ca97c8 100644
--- a/kv/src/main/java/com/orientechnologies/orient/kv/index/OTreeMapPersistentAsynchThread.java
+++ b/kv/src/main/java/com/orientechnologies/orient/kv/index/OMVRBTreePersistentAsynchThread.java
@@ -28,13 +28,13 @@
* @author Luca Garulli
*
*/
-public class OTreeMapPersistentAsynchThread extends OSoftThread {
+public class OMVRBTreePersistentAsynchThread extends OSoftThread {
private long delay = 0;
- private Set<OTreeMapPersistentAsynch<?, ?>> maps = new HashSet<OTreeMapPersistentAsynch<?, ?>>();
- private static OTreeMapPersistentAsynchThread instance = new OTreeMapPersistentAsynchThread();
+ private Set<OMVRBTreePersistentAsynch<?, ?>> maps = new HashSet<OMVRBTreePersistentAsynch<?, ?>>();
+ private static OMVRBTreePersistentAsynchThread instance = new OMVRBTreePersistentAsynchThread();
- public OTreeMapPersistentAsynchThread setDelay(final int iDelay) {
+ public OMVRBTreePersistentAsynchThread setDelay(final int iDelay) {
delay = iDelay;
return this;
}
@@ -44,13 +44,13 @@ public OTreeMapPersistentAsynchThread setDelay(final int iDelay) {
*
* @param iMap
*/
- public synchronized void registerMap(final OTreeMapPersistentAsynch<?, ?> iMap) {
+ public synchronized void registerMap(final OMVRBTreePersistentAsynch<?, ?> iMap) {
maps.add(iMap);
}
@Override
protected synchronized void execute() throws Exception {
- for (OTreeMapPersistentAsynch<?, ?> map : maps) {
+ for (OMVRBTreePersistentAsynch<?, ?> map : maps) {
try {
synchronized (map) {
@@ -68,7 +68,7 @@ protected void afterExecution() throws InterruptedException {
pauseCurrentThread(delay);
}
- public static OTreeMapPersistentAsynchThread getInstance() {
+ public static OMVRBTreePersistentAsynchThread getInstance() {
return instance;
}
}
diff --git a/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/OKVDictionaryBucketManager.java b/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/OKVDictionaryBucketManager.java
index 3ad704979c2..39031630f10 100644
--- a/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/OKVDictionaryBucketManager.java
+++ b/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/OKVDictionaryBucketManager.java
@@ -22,8 +22,8 @@
import com.orientechnologies.orient.core.db.record.ODatabaseBinary;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerString;
-import com.orientechnologies.orient.core.type.tree.OTreeMapDatabase;
-import com.orientechnologies.orient.kv.index.OTreeMapPersistentAsynch;
+import com.orientechnologies.orient.core.type.tree.OMVRBTreeDatabase;
+import com.orientechnologies.orient.kv.index.OMVRBTreePersistentAsynch;
/**
* Caches bucket tree maps to be reused across calls.
@@ -32,12 +32,12 @@
*
*/
public class OKVDictionaryBucketManager {
- private static Map<String, OTreeMapDatabase<String, String>> bucketCache = new HashMap<String, OTreeMapDatabase<String, String>>();
+ private static Map<String, OMVRBTreeDatabase<String, String>> bucketCache = new HashMap<String, OMVRBTreeDatabase<String, String>>();
private static final String DEFAULT_CLUSTER_NAME = "default";
public static synchronized Map<String, String> getDictionaryBucket(final ODatabaseBinary iDatabase, final String iName,
final boolean iAsynchMode) throws IOException {
- OTreeMapDatabase<String, String> bucket = bucketCache.get(iDatabase.getName() + ":" + iName);
+ OMVRBTreeDatabase<String, String> bucket = bucketCache.get(iDatabase.getName() + ":" + iName);
if (bucket != null)
return bucket;
@@ -47,10 +47,10 @@ public static synchronized Map<String, String> getDictionaryBucket(final ODataba
if (record == null) {
// CREATE THE BUCKET TRANSPARENTLY
if (iAsynchMode)
- bucket = new OTreeMapPersistentAsynch<String, String>(iDatabase, DEFAULT_CLUSTER_NAME, OStreamSerializerString.INSTANCE,
+ bucket = new OMVRBTreePersistentAsynch<String, String>(iDatabase, DEFAULT_CLUSTER_NAME, OStreamSerializerString.INSTANCE,
OStreamSerializerString.INSTANCE);
else
- bucket = new OTreeMapDatabase<String, String>(iDatabase, DEFAULT_CLUSTER_NAME, OStreamSerializerString.INSTANCE,
+ bucket = new OMVRBTreeDatabase<String, String>(iDatabase, DEFAULT_CLUSTER_NAME, OStreamSerializerString.INSTANCE,
OStreamSerializerString.INSTANCE);
bucket.save();
@@ -58,9 +58,9 @@ public static synchronized Map<String, String> getDictionaryBucket(final ODataba
iDatabase.getDictionary().put(iName, bucket.getRecord());
} else {
if (iAsynchMode)
- bucket = new OTreeMapPersistentAsynch<String, String>(iDatabase, record.getIdentity());
+ bucket = new OMVRBTreePersistentAsynch<String, String>(iDatabase, record.getIdentity());
else
- bucket = new OTreeMapDatabase<String, String>(iDatabase, record.getIdentity());
+ bucket = new OMVRBTreeDatabase<String, String>(iDatabase, record.getIdentity());
bucket.load();
}
diff --git a/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/local/ONetworkProtocolHttpKVLocal.java b/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/local/ONetworkProtocolHttpKVLocal.java
index 000cebfbc77..db38c31f2cd 100644
--- a/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/local/ONetworkProtocolHttpKVLocal.java
+++ b/kv/src/main/java/com/orientechnologies/orient/kv/network/protocol/http/local/ONetworkProtocolHttpKVLocal.java
@@ -21,7 +21,7 @@
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.orient.core.db.record.ODatabaseBinary;
import com.orientechnologies.orient.kv.OSharedBinaryDatabase;
-import com.orientechnologies.orient.kv.index.OTreeMapPersistentAsynchThread;
+import com.orientechnologies.orient.kv.index.OMVRBTreePersistentAsynchThread;
import com.orientechnologies.orient.kv.network.protocol.http.OKVDictionary;
import com.orientechnologies.orient.kv.network.protocol.http.OKVDictionaryBucketManager;
import com.orientechnologies.orient.kv.network.protocol.http.ONetworkProtocolHttpKV;
@@ -37,8 +37,8 @@ public class ONetworkProtocolHttpKVLocal extends ONetworkProtocolHttpKV implemen
// START ASYNCH THREAD IF CONFIGURED
String v = OServerMain.server().getConfiguration().getProperty(ASYNCH_COMMIT_DELAY_PAR);
if (v != null) {
- OTreeMapPersistentAsynchThread.getInstance().setDelay(Integer.parseInt(v));
- OTreeMapPersistentAsynchThread.getInstance().start();
+ OMVRBTreePersistentAsynchThread.getInstance().setDelay(Integer.parseInt(v));
+ OMVRBTreePersistentAsynchThread.getInstance().start();
asynchMode = true;
}
//
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/internal/index/OTreeMapSpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/internal/index/OMVRBTreeSpeedTest.java
similarity index 82%
rename from tests/src/test/java/com/orientechnologies/orient/test/internal/index/OTreeMapSpeedTest.java
rename to tests/src/test/java/com/orientechnologies/orient/test/internal/index/OMVRBTreeSpeedTest.java
index dda27ba43f1..685c27d0e3c 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/internal/index/OTreeMapSpeedTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/internal/index/OMVRBTreeSpeedTest.java
@@ -18,13 +18,13 @@
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.orientechnologies.common.collection.OMVRBTreeMemory;
import com.orientechnologies.common.collection.ONavigableMap;
-import com.orientechnologies.common.collection.OTreeMapMemory;
import com.orientechnologies.common.test.SpeedTestMonoThread;
-public class OTreeMapSpeedTest extends SpeedTestMonoThread {
+public class OMVRBTreeSpeedTest extends SpeedTestMonoThread {
- private ONavigableMap<Integer, Integer> tree = new OTreeMapMemory<Integer, Integer>();
+ private ONavigableMap<Integer, Integer> tree = new OMVRBTreeMemory<Integer, Integer>();
@Override
@Test(enabled = false)
@@ -61,8 +61,8 @@ public void cycle() {
}
data.printSnapshot();
- // if (tree instanceof OTreeMap<?, ?>) {
- // System.out.println("Total nodes: " + ((OTreeMap<?, ?>) tree).getNodes());
+ // if (tree instanceof OMVRBTree<?, ?>) {
+ // System.out.println("Total nodes: " + ((OMVRBTree<?, ?>) tree).getNodes());
// }
System.out.println("Delete all the elements one by one...");
|
736169aa2a46f489cd8e75cf4d61cef997fc456f
|
spring-framework
|
revised WebApplicationContext lookup--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContextUtils.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContextUtils.java
index fed2015a4a71..8859e88a7c37 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContextUtils.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/support/RequestContextUtils.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2007 the original author or authors.
+ * Copyright 2002-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.
@@ -17,7 +17,6 @@
package org.springframework.web.servlet.support;
import java.util.Locale;
-
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
@@ -79,10 +78,7 @@ public static WebApplicationContext getWebApplicationContext(
if (servletContext == null) {
throw new IllegalStateException("No WebApplicationContext found: not in a DispatcherServlet request?");
}
- webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
- if (webApplicationContext == null) {
- throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
- }
+ webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
}
return webApplicationContext;
}
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/AbstractSpringPreparerFactory.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/AbstractSpringPreparerFactory.java
index 809468636854..96aec8fbd6dc 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/AbstractSpringPreparerFactory.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/AbstractSpringPreparerFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2007 the original author or authors.
+ * Copyright 2002-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.
@@ -16,16 +16,15 @@
package org.springframework.web.servlet.view.tiles2;
-import javax.servlet.ServletRequest;
-
import org.apache.tiles.TilesException;
import org.apache.tiles.context.TilesRequestContext;
import org.apache.tiles.preparer.PreparerFactory;
import org.apache.tiles.preparer.ViewPreparer;
-import org.apache.tiles.servlet.context.ServletTilesApplicationContext;
+import org.apache.tiles.servlet.context.ServletTilesRequestContext;
import org.springframework.web.context.WebApplicationContext;
-import org.springframework.web.servlet.support.RequestContextUtils;
+import org.springframework.web.context.support.WebApplicationContextUtils;
+import org.springframework.web.servlet.DispatcherServlet;
/**
* Abstract implementation of the Tiles2 {@link org.apache.tiles.preparer.PreparerFactory}
@@ -41,20 +40,24 @@
public abstract class AbstractSpringPreparerFactory implements PreparerFactory {
public ViewPreparer getPreparer(String name, TilesRequestContext context) throws TilesException {
- ServletRequest servletRequest = null;
- if (context.getRequest() instanceof ServletRequest) {
- servletRequest = (ServletRequest) context.getRequest();
- }
- ServletTilesApplicationContext tilesApplicationContext = null;
- if (context instanceof ServletTilesApplicationContext) {
- tilesApplicationContext = (ServletTilesApplicationContext) context;
- }
- if (servletRequest == null && tilesApplicationContext == null) {
- throw new IllegalStateException("SpringBeanPreparerFactory requires either a " +
- "ServletRequest or a ServletTilesApplicationContext to operate on");
+ WebApplicationContext webApplicationContext = (WebApplicationContext) context.getRequestScope().get(
+ DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
+ if (webApplicationContext == null) {
+ /* as of Tiles 2.1:
+ webApplicationContext = (WebApplicationContext) context.getApplicationContext().getApplicationScope().get(
+ WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
+ if (webApplicationContext == null) {
+ throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
+ }
+ */
+ if (!(context instanceof ServletTilesRequestContext)) {
+ throw new IllegalStateException(
+ getClass().getSimpleName() + " requires a ServletTilesRequestContext to operate on");
+ }
+ ServletTilesRequestContext servletRequestContext = (ServletTilesRequestContext) context;
+ webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(
+ servletRequestContext.getServletContext());
}
- WebApplicationContext webApplicationContext = RequestContextUtils.getWebApplicationContext(
- servletRequest, tilesApplicationContext.getServletContext());
return getPreparer(name, webApplicationContext);
}
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/SpringBeanPreparerFactory.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/SpringBeanPreparerFactory.java
index 3216059f8e73..527177951c94 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/SpringBeanPreparerFactory.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/tiles2/SpringBeanPreparerFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2007 the original author or authors.
+ * Copyright 2002-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.
@@ -36,7 +36,7 @@ public class SpringBeanPreparerFactory extends AbstractSpringPreparerFactory {
@Override
protected ViewPreparer getPreparer(String name, WebApplicationContext context) throws TilesException {
- return (ViewPreparer) context.getBean(name, ViewPreparer.class);
+ return context.getBean(name, ViewPreparer.class);
}
}
|
b246e68435e8d86a2a12fb8fe6c5aa9d9896ff92
|
hbase
|
HBASE-5259 Normalize the RegionLocation in- TableInputFormat by the reverse DNS lookup (Liyin Tang)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1238774 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/src/main/java/org/apache/hadoop/hbase/mapreduce/TableInputFormatBase.java b/src/main/java/org/apache/hadoop/hbase/mapreduce/TableInputFormatBase.java
index 7ebd62f18eea..b275e4e0cfe9 100644
--- a/src/main/java/org/apache/hadoop/hbase/mapreduce/TableInputFormatBase.java
+++ b/src/main/java/org/apache/hadoop/hbase/mapreduce/TableInputFormatBase.java
@@ -20,11 +20,17 @@
package org.apache.hadoop.hbase.mapreduce;
import java.io.IOException;
+import java.net.InetAddress;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import javax.naming.NamingException;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.HServerAddress;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
@@ -36,6 +42,7 @@
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.net.DNS;
/**
* A base for {@link TableInputFormat}s. Receives a {@link HTable}, an
@@ -78,6 +85,13 @@ public abstract class TableInputFormatBase
private TableRecordReader tableRecordReader = null;
+ /** The reverse DNS lookup cache mapping: IPAddress => HostName */
+ private HashMap<InetAddress, String> reverseDNSCacheMap =
+ new HashMap<InetAddress, String>();
+
+ /** The NameServer address */
+ private String nameServer = null;
+
/**
* Builds a TableRecordReader. If no TableRecordReader was provided, uses
* the default.
@@ -128,6 +142,10 @@ public List<InputSplit> getSplits(JobContext context) throws IOException {
if (table == null) {
throw new IOException("No table was provided.");
}
+ // Get the name server address and the default value is null.
+ this.nameServer =
+ context.getConfiguration().get("hbase.nameserver.address", null);
+
Pair<byte[][], byte[][]> keys = table.getStartEndKeys();
if (keys == null || keys.getFirst() == null ||
keys.getFirst().length == 0) {
@@ -138,13 +156,24 @@ public List<InputSplit> getSplits(JobContext context) throws IOException {
if ( !includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) {
continue;
}
- String regionLocation = table.getRegionLocation(keys.getFirst()[i]).
- getHostname();
- byte[] startRow = scan.getStartRow();
- byte[] stopRow = scan.getStopRow();
- // determine if the given start an stop key fall into the region
+ HServerAddress regionServerAddress =
+ table.getRegionLocation(keys.getFirst()[i]).getServerAddress();
+ InetAddress regionAddress =
+ regionServerAddress.getInetSocketAddress().getAddress();
+ String regionLocation;
+ try {
+ regionLocation = reverseDNS(regionAddress);
+ } catch (NamingException e) {
+ LOG.error("Cannot resolve the host name for " + regionAddress +
+ " because of " + e);
+ regionLocation = regionServerAddress.getHostname();
+ }
+
+ byte[] startRow = scan.getStartRow();
+ byte[] stopRow = scan.getStopRow();
+ // determine if the given start an stop key fall into the region
if ((startRow.length == 0 || keys.getSecond()[i].length == 0 ||
- Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) &&
+ Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) &&
(stopRow.length == 0 ||
Bytes.compareTo(stopRow, keys.getFirst()[i]) > 0)) {
byte[] splitStart = startRow.length == 0 ||
@@ -164,6 +193,15 @@ public List<InputSplit> getSplits(JobContext context) throws IOException {
}
return splits;
}
+
+ private String reverseDNS(InetAddress ipAddress) throws NamingException {
+ String hostName = this.reverseDNSCacheMap.get(ipAddress);
+ if (hostName == null) {
+ hostName = DNS.reverseDns(ipAddress, this.nameServer);
+ this.reverseDNSCacheMap.put(ipAddress, hostName);
+ }
+ return hostName;
+ }
/**
*
|
2ba7cee1e2a02194ac7b6536f6fa0fdd268c7c18
|
coremedia$jangaroo-tools
|
Finished the specified JIRA tickets with the following limitations:
* JOO-5: "this." is now guessed by exclusion: every identifier that is not declared in any scope is assumed to be an inherited member. Since this situation might also be a missing declaration, a warning is issued, which you can get rid of by writing "this." explicitly. Be sure to import *everything*! "window" is no longer in scope, write "window." explicitly ("window" is predefined and does not need to be declared).
* JOO-30: Type casts are now left out is a function is assumed to be a type. Since you can also import package-namespaced functions (not supported by Jangaroo, but could be "native" JavaScript), there is a heuristic that uppercase imports declare types.
* JOO-40: Automatic binding only works for methods declared in the same file. For other situations, I plan to add a [Bound] annotation.
[git-p4: depot-paths = "//coremedia/jangaroo/": change = 145172]
|
a
|
https://github.com/coremedia/jangaroo-tools
|
diff --git a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
index 0ab729498..c3aa189c0 100644
--- a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
+++ b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup
@@ -133,7 +133,7 @@ nonterminal FunctionExpr functionExpr;
nonterminal Ide ide;
nonterminal Implements implements;
nonterminal Implements interfaceExtends;
-nonterminal ImportDirective directive;
+nonterminal Node directive;
nonterminal Directives directives;
nonterminal Expr lvalue;
nonterminal MethodDeclaration methodDeclaration;
@@ -267,12 +267,12 @@ constOrVar ::=
;
directive ::=
- IMPORT:i qualifiedIde:ide
- {: RESULT = new ImportDirective(i,new IdeType(ide)); :}
+ IMPORT:i qualifiedIde:ide SEMICOLON:s
+ {: RESULT = new ImportDirective(i,new IdeType(ide), s); :}
| LBRACK:lb ide:ide RBRACK:rb
- {: RESULT = null; :}
- | LBRACK:lb ide:ide LPAREN:lb2 annotationFields:of RPAREN:rb2 RBRACK:rb
- {: RESULT = null; :}
+ {: RESULT = new Annotation(lb, ide, rb); :}
+ | LBRACK:lb ide:ide LPAREN:lb2 annotationFields:af RPAREN:rb2 RBRACK:rb
+ {: RESULT = new Annotation(lb, ide, af, rb); :}
;
nonEmptyAnnotationFields ::=
@@ -283,8 +283,10 @@ nonEmptyAnnotationFields ::=
;
annotationField ::=
- ide:name EQ:eq STRING_LITERAL:value
- {: RESULT = new ObjectField(new IdeExpr(name),eq,new LiteralExpr(value)); :}
+ ide:name EQ:eq expr:value
+ {: RESULT = new ObjectField(new IdeExpr(name),eq,value); :}
+ | expr:value
+ {: RESULT = new ObjectField(new IdeExpr(new Ide(new JooSymbol(""))),null,value); :}
;
annotationFields ::=
@@ -295,8 +297,6 @@ annotationFields ::=
directives ::=
{: RESULT = null; :}
- | SEMICOLON:s directives:ds
- {: RESULT = ds; :}
| directive:d directives:ds
{: RESULT = new Directives(d,ds); :}
;
diff --git a/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java
index 89b689865..b41b6d9e8 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java
@@ -57,12 +57,12 @@ public boolean isConst() {
return optSymConstOrVar != null && optSymConstOrVar.sym == sym.CONST;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (optInitializer == null && isConst())
Jooc.error(optSymConstOrVar, "constant must be initialized");
if (optInitializer != null)
- optInitializer.analyze(context);
+ optInitializer.analyze(this, context);
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/AccessorIde.java b/jooc/src/main/java/net/jangaroo/jooc/AccessorIde.java
index 4a436336a..eb6c4304d 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/AccessorIde.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/AccessorIde.java
@@ -20,7 +20,7 @@
*/
public class AccessorIde extends Ide {
- private JooSymbol symGetOrSet;
+ JooSymbol symGetOrSet;
public AccessorIde(JooSymbol symGetOrSet, Ide ide) {
super(ide.ide);
@@ -29,7 +29,10 @@ public AccessorIde(JooSymbol symGetOrSet, Ide ide) {
@Override
public String getName() {
- return symGetOrSet.getText()+"$"+super.getName();
+ return symGetOrSet.getText()+" "+super.getName();
}
+ public String getFunctionName() {
+ return symGetOrSet.getText()+"$"+super.getName();
+ }
}
\ No newline at end of file
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Annotation.java b/jooc/src/main/java/net/jangaroo/jooc/Annotation.java
new file mode 100644
index 000000000..02d347146
--- /dev/null
+++ b/jooc/src/main/java/net/jangaroo/jooc/Annotation.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2008 CoreMedia AG
+ *
+ * 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 net.jangaroo.jooc;
+
+import java.io.IOException;
+
+/**
+ * An annotation (sqare bracket meta data).
+ */
+public class Annotation extends NodeImplBase {
+
+ JooSymbol leftBracket;
+ Ide ide;
+ ObjectFields annotationFields;
+ JooSymbol rightBracket;
+
+ public Annotation(JooSymbol leftBracket, Ide ide, JooSymbol rightBracket) {
+ this(leftBracket, ide, null, rightBracket);
+ }
+
+ public Annotation(JooSymbol leftBracket, Ide ide, ObjectFields annotationFields, JooSymbol rightBracket) {
+ this.leftBracket = leftBracket;
+ this.ide = ide;
+ this.annotationFields = annotationFields;
+ this.rightBracket = rightBracket;
+ }
+
+ public JooSymbol getSymbol() {
+ return ide.getSymbol();
+ }
+
+ public void generateCode(JsWriter out) throws IOException {
+ out.beginComment();
+ out.writeSymbol(leftBracket);
+ ide.generateCode(out);
+ if (annotationFields!=null) {
+ annotationFields.generateCode(out);
+ }
+ out.writeSymbol(rightBracket);
+ out.endComment();
+ }
+}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java b/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java
index 4414affe5..0015ffa5c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java
@@ -23,6 +23,7 @@
class ApplyExpr extends Expr {
Expr fun;
+ boolean isType;
JooSymbol lParen;
Arguments args;
JooSymbol rParen;
@@ -34,12 +35,14 @@ public ApplyExpr(Expr fun, JooSymbol lParen, Arguments args, JooSymbol rParen) {
this.rParen = rParen;
}
- protected void generateFunCode(JsWriter out) throws IOException {
- fun.generateCode(out);
- }
-
public void generateCode(JsWriter out) throws IOException {
- generateFunCode(out);
+ if (isType) {
+ out.beginComment();
+ fun.generateCode(out);
+ out.endComment();
+ } else {
+ fun.generateCode(out);
+ }
generateArgsCode(out);
}
@@ -50,10 +53,23 @@ protected void generateArgsCode(JsWriter out) throws IOException {
out.writeSymbol(rParen);
}
- public void analyze(AnalyzeContext context) {
- fun.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ // leave out constructor function if called as type cast function!
+ if (fun instanceof IdeExpr) {
+ Ide funIde = ((IdeExpr)fun).ide;
+ // heuristic for types: start with upper case letter.
+ // otherwise, it is most likely an imported package-namespaced function.
+ if (Character.isUpperCase(funIde.getName().charAt(0))) {
+ Scope scope = context.getScope().findScopeThatDeclares(funIde);
+ if (scope!=null) {
+ isType = scope.getDeclaration()==context.getScope().getPackageDeclaration();
+ }
+ }
+ }
+ fun.analyze(this, context);
if (args != null)
- args.analyze(context);
+ args.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Arguments.java b/jooc/src/main/java/net/jangaroo/jooc/Arguments.java
index 44f2ab760..557bfcf8f 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Arguments.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Arguments.java
@@ -44,10 +44,11 @@ public void generateCode(JsWriter out) throws IOException {
}
- public void analyze(AnalyzeContext context) {
- arg.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ arg.analyze(this, context);
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ArrayLiteral.java b/jooc/src/main/java/net/jangaroo/jooc/ArrayLiteral.java
index 5058605f7..001e6b6b2 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ArrayLiteral.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ArrayLiteral.java
@@ -40,9 +40,10 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbol(rBracket);
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (args != null)
- args.analyze(context);
+ args.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/BinaryOpExpr.java b/jooc/src/main/java/net/jangaroo/jooc/BinaryOpExpr.java
index ac88b3dbd..98adaeb35 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/BinaryOpExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/BinaryOpExpr.java
@@ -37,9 +37,10 @@ public void generateCode(JsWriter out) throws IOException {
arg2.generateCode(out);
}
- public void analyze(AnalyzeContext context) {
- arg1.analyze(context);
- arg2.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ arg1.analyze(this, context);
+ arg2.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/BlockStatement.java b/jooc/src/main/java/net/jangaroo/jooc/BlockStatement.java
index cc1222f8a..1bd1bb14c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/BlockStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/BlockStatement.java
@@ -55,8 +55,9 @@ public void setParameters(Parameters params) {
this.params = params;
}
- public void analyze(AnalyzeContext context) {
- analyze(statements, context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ analyze(this, statements, context);
}
// TODO: Check when analyzing the super call
diff --git a/jooc/src/main/java/net/jangaroo/jooc/CaseStatement.java b/jooc/src/main/java/net/jangaroo/jooc/CaseStatement.java
index 1fd2da61c..8e6238025 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/CaseStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/CaseStatement.java
@@ -31,8 +31,9 @@ public CaseStatement(JooSymbol symCase, Expr expr, JooSymbol symColon) {
this.symColon = symColon;
}
- public void analyze(AnalyzeContext context) {
- expr.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ expr.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Catch.java b/jooc/src/main/java/net/jangaroo/jooc/Catch.java
index 13afa08a7..13026469f 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Catch.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Catch.java
@@ -43,9 +43,10 @@ public void generateCode(JsWriter out) throws IOException {
block.generateCode(out);
}
- public void analyze(AnalyzeContext context) {
- param.analyze(context);
- block.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ param.analyze(this, context);
+ block.analyze(this, context);
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ClassBody.java b/jooc/src/main/java/net/jangaroo/jooc/ClassBody.java
index 3daf2bdd7..d49984fe1 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ClassBody.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ClassBody.java
@@ -45,8 +45,9 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbolWhitespace(rBrace);
}
- public void analyze(AnalyzeContext context) {
- analyze(declararations, context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ analyze(this, declararations, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java
index 8dbfed9c6..25424f981 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java
@@ -114,12 +114,15 @@ public void generateCode(JsWriter out) throws IOException {
out.write("];}");
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ // do *not* call super!
+ this.parentNode = parentNode;
+ context.getScope().declareIde(getName(), this);
parentDeclaration = context.getScope().getPackageDeclaration();
context.enterScope(this);
- if (optExtends != null) optExtends.analyze(context);
- if (optImplements != null) optImplements.analyze(context);
- body.analyze(context);
+ if (optExtends != null) optExtends.analyze(this, context);
+ if (optImplements != null) optImplements.analyze(this, context);
+ body.analyze(this, context);
context.leaveScope(this);
computeModifiers();
}
@@ -145,7 +148,7 @@ public boolean isPrivateStaticMember(String memberName) {
public Type getSuperClassType() {
return optExtends != null
? optExtends.superClass
- : new IdeType(new Ide(new JooSymbol(sym.IDE, "", -1, -1, "", "Object")));
+ : new IdeType(new Ide(new JooSymbol("Object")));
}
public String getSuperClassPath() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java b/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java
index 8cbbb67cc..da94fff80 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java
@@ -83,9 +83,49 @@ public void generateCode(JsWriter out) throws IOException {
out.write(");");
}
- public void analyze(AnalyzeContext context) {
- packageDeclaration.analyze(context);
- classDeclaration.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ // establish global scope for built-in identifiers:
+ IdeType globalObject = new IdeType("globalObject");
+ context.enterScope(globalObject);
+ declareIdes(context.getScope(), new String[]{
+ "undefined",
+ "window", // TODO: or rather have to import?
+ "int",
+ "uint",
+ "Object",
+ "Function",
+ "Class",
+ "Array",
+ "Boolean",
+ "String",
+ "Number",
+ "RegExp",
+ "Date",
+ "Math",
+ "parseInt",
+ "parseFloat",
+ "isNaN",
+ "NaN",
+ "isFinite",
+ "encodeURIComponent",
+ "decodeURIComponent",
+ "trace",
+ "joo"});
+ super.analyze(parentNode, context);
+ context.enterScope(packageDeclaration);
+ packageDeclaration.analyze(this, context);
+ if (directives!=null) {
+ directives.analyze(this, context);
+ }
+ classDeclaration.analyze(this, context);
+ context.leaveScope(packageDeclaration);
+ context.leaveScope(globalObject);
+ }
+
+ private void declareIdes(Scope scope, String[] identifiers) {
+ for (String identifier: identifiers) {
+ scope.declareIde(identifier, new IdeType(identifier));
+ }
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/CompileLog.java b/jooc/src/main/java/net/jangaroo/jooc/CompileLog.java
index d090b8b36..a871c7468 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/CompileLog.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/CompileLog.java
@@ -21,10 +21,10 @@
public class CompileLog {
protected boolean errors = false;
+ protected boolean warnings = false;
public void error(JooSymbol sym, String msg) {
- error(formatError(sym.getFileName(), sym.getLine(), sym.getColumn(), msg));
- errors = true;
+ error(formatError(sym.getFileName(), sym.getLine(), sym.getColumn(), "Error", msg));
}
public void error(String msg) {
@@ -32,14 +32,24 @@ public void error(String msg) {
errors = true;
}
+ public void warning(JooSymbol sym, String msg) {
+ warning(formatError(sym.getFileName(), sym.getLine(), sym.getColumn(), "Warning", msg));
+ }
+
+ public void warning(String msg) {
+ System.out.println(msg);
+ warnings = true;
+ }
+
public boolean hasErrors() {
return errors;
}
- String formatError(String fileName, int line, int column, String message) {
+ String formatError(String fileName, int line, int column, String debugLevel, String message) {
StringBuffer m = new StringBuffer();
m.append(fileName + "(" + line + "): ");
- m.append("Error: ");
+ m.append(debugLevel);
+ m.append(": ");
m.append("in column " + column + ": ");
m.append(message);
return m.toString();
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ConditionalExpr.java b/jooc/src/main/java/net/jangaroo/jooc/ConditionalExpr.java
index 343fa8d6c..a611dcfb5 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ConditionalExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ConditionalExpr.java
@@ -44,10 +44,11 @@ public void generateCode(JsWriter out) throws IOException {
ifFalse.generateCode(out);
}
- public void analyze(AnalyzeContext context) {
- cond.analyze(context);
- ifTrue.analyze(context);
- ifFalse.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ cond.analyze(this, context);
+ ifTrue.analyze(this, context);
+ ifFalse.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ConditionalLoopStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ConditionalLoopStatement.java
index 77a38331e..a95509195 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ConditionalLoopStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ConditionalLoopStatement.java
@@ -31,7 +31,7 @@ public ConditionalLoopStatement(JooSymbol symLoop, Expr optCond, Statement body)
protected void analyzeLoopHeader(AnalyzeContext context) {
if (optCond != null)
- optCond.analyze(context);
+ optCond.analyze(this, context);
}
protected void generateLoopHeaderCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ContinueStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ContinueStatement.java
index 1c8c3d208..e5f15d407 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ContinueStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ContinueStatement.java
@@ -24,8 +24,4 @@ public ContinueStatement(JooSymbol symContinue, Ide optLabel, JooSymbol symSemic
super(symContinue, optLabel, symSemicolon);
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- }
-
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java
index cc29c88d3..e5f11d767 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java
@@ -142,8 +142,8 @@ protected boolean writeRuntimeModifiersUnclosed(JsWriter out) throws IOException
return false;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
parentDeclaration = context.getScope().getDeclaration();
classDeclaration = context.getCurrentClass();
computeModifiers();
diff --git a/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java b/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java
index fb4140116..448d3db03 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java
@@ -29,9 +29,9 @@ public DeclarationStatement(Declaration decl, JooSymbol symSemicolon) {
this.decl = decl;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- decl.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ decl.analyze(this, context);
}
protected void generateStatementCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/DefaultStatement.java b/jooc/src/main/java/net/jangaroo/jooc/DefaultStatement.java
index 162270c08..bf832161d 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/DefaultStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/DefaultStatement.java
@@ -35,10 +35,6 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbol(symColon);
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- }
-
public JooSymbol getSymbol() {
return symDefault;
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Directives.java b/jooc/src/main/java/net/jangaroo/jooc/Directives.java
index ad7862ab3..29b1ba9a2 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Directives.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Directives.java
@@ -22,20 +22,21 @@
*/
class Directives extends NodeImplBase {
- ImportDirective directive; // other directive types may follow later
+ Node directive; // other directive types may follow later
Directives tail;
- public Directives(ImportDirective directive, Directives tail) {
+ public Directives(Node directive, Directives tail) {
this.directive = directive;
this.tail = tail;
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (directive!=null) {
- directive.analyze(context);
+ directive.analyze(this, context);
}
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/DoStatement.java b/jooc/src/main/java/net/jangaroo/jooc/DoStatement.java
index 1c78c74a0..4632e0cb3 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/DoStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/DoStatement.java
@@ -34,7 +34,7 @@ protected void analyzeLoopHeader(AnalyzeContext context) {
}
protected void analyzeLoopFooter(AnalyzeContext context) {
- optCond.analyze(context);
+ optCond.analyze(this, context);
}
protected void generateLoopHeaderCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java b/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java
index 6c5155b4e..2dd88732d 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java
@@ -23,14 +23,14 @@
*/
class DotExpr extends BinaryOpExpr {
- private ClassDeclaration classDeclaration;
+ ClassDeclaration classDeclaration;
public DotExpr(Expr expr, JooSymbol symDot, Ide ide) {
super(expr, symDot, new IdeExpr(ide));
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
classDeclaration = context.getCurrentClass();
}
@@ -63,6 +63,28 @@ public void generateCode(JsWriter out) throws IOException {
if (classDeclaration!=null
&& arg2 instanceof IdeExpr) {
String property = ((IdeExpr)arg2).ide.getName();
+ // check and handle instance methods declared in same file, accessed as function:
+ if (arg1 instanceof ThisExpr
+ && !(parentNode instanceof DotExpr)
+ && !(parentNode instanceof ApplyExpr)
+ && !(parentNode instanceof DeleteStatement)
+ && !((parentNode instanceof AssignmentOpExpr) && ((AssignmentOpExpr)parentNode).arg1==this)) {
+ MemberDeclaration memberDeclaration = classDeclaration.getMemberDeclaration(property);
+ if (memberDeclaration!=null && memberDeclaration.isMethod()) {
+ //Jooc.warning(arg2.getSymbol(), "Found method used as function, have to bind!");
+ out.writeToken("joo.bind(");
+ arg1.generateCode(out);
+ out.write(",");
+ out.writeSymbolWhitespace(arg2.getSymbol());
+ if (memberDeclaration.isPrivate()) {
+ out.write("$"+property);
+ } else {
+ out.write("\""+property+"\"");
+ }
+ out.write(")");
+ return;
+ }
+ }
// check and handle private instance members and super method access:
if ( arg1 instanceof ThisExpr && classDeclaration.isPrivateMember(property)
|| arg1 instanceof SuperExpr) {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java
index da37e3913..e7e65210a 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java
@@ -36,9 +36,10 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbol(symSemicolon);
}
- public void analyze(AnalyzeContext context) {
- if (optExpr != null)
- optExpr.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ if (optExpr != null)
+ optExpr.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java
index 1d7a5475e..df515edc2 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java
@@ -46,8 +46,8 @@ protected void generateLoopHeaderCode(JsWriter out) throws IOException {
}
protected void analyzeLoopHeader(AnalyzeContext context) {
- decl.analyze(context);
- expr.analyze(context);
+ decl.analyze(this, context);
+ expr.analyze(this, context);
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ForInitializer.java b/jooc/src/main/java/net/jangaroo/jooc/ForInitializer.java
index 960960e0f..63070a2ce 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ForInitializer.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ForInitializer.java
@@ -33,12 +33,12 @@ public ForInitializer(Expr expr) {
this.expr = expr;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (decl!=null)
- decl.analyze(context);
+ decl.analyze(this, context);
if (expr!=null)
- expr.analyze(context);
+ expr.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ForStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ForStatement.java
index 982c8470a..a62e02a12 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ForStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ForStatement.java
@@ -54,7 +54,7 @@ protected void generateLoopHeaderCode(JsWriter out) throws IOException {
protected void analyzeLoopHeader(AnalyzeContext context) {
if (forInit!=null)
- forInit.analyze(context);
+ forInit.analyze(this, context);
super.analyzeLoopHeader(context);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/FunctionExpr.java b/jooc/src/main/java/net/jangaroo/jooc/FunctionExpr.java
index 282b11852..d863e308f 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/FunctionExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/FunctionExpr.java
@@ -46,16 +46,19 @@ public ClassDeclaration getClassDeclaration() {
return classDeclaration;
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
classDeclaration = context.getCurrentClass();
Debug.assertTrue(classDeclaration != null, "classDeclaration != null");
- super.analyze(context);
+ super.analyze(parentNode, context);
context.enterScope(this);
if (params != null)
- params.analyze(context);
+ params.analyze(this, context);
+ if (context.getScope().getIdeDeclaration("arguments")==null) {
+ context.getScope().declareIde("arguments", this); // is always defined inside a function!
+ }
if (optTypeRelation != null)
- optTypeRelation.analyze(context);
- body.analyze(context);
+ optTypeRelation.analyze(this, context);
+ body.analyze(this, context);
context.leaveScope(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Ide.java b/jooc/src/main/java/net/jangaroo/jooc/Ide.java
index 2a751257b..7877e2d64 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Ide.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Ide.java
@@ -33,7 +33,7 @@ public void generateCode(JsWriter out) throws IOException {
}
public String[] getQualifiedName() {
- return new String[] { ide.getText() };
+ return new String[] { getName() };
}
public String getName() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java
index ffe741f9a..fe20de111 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java
@@ -30,7 +30,7 @@ protected IdeDeclaration(JooSymbol[] modifiers, int allowedModifiers, Ide ide) {
super(modifiers, allowedModifiers);
this.ide = ide;
if (ide!=null && PRIVATE_MEMBER_NAME.matcher(ide.getName()).matches()) {
- System.err.println("WARNING: Jangaroo identifier must not be an ActionScript identifier prefixed with a dollar sign ('$'): "+ide.getName());
+ Jooc.warning(ide.getSymbol(), "Jangaroo identifier must not be an ActionScript identifier prefixed with a dollar sign ('$').");
}
}
@@ -73,9 +73,10 @@ public String getPath() {
return toPath(getQualifiedName());
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- context.getScope().declareIde(this);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ if (context.getScope().declareIde(getName(), this)!=null)
+ Jooc.error(getSymbol(), "duplicate declaration of identifier '" + getName() + "'");
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/IdeType.java b/jooc/src/main/java/net/jangaroo/jooc/IdeType.java
index e46731cda..798ec9a37 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/IdeType.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/IdeType.java
@@ -28,6 +28,10 @@ public Ide getIde() {
Ide ide;
+ public IdeType(String name) {
+ this(new Ide(new JooSymbol(name)));
+ }
+
public IdeType(Ide ide) {
this.ide = ide;
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/IfStatement.java b/jooc/src/main/java/net/jangaroo/jooc/IfStatement.java
index ad3dcff08..9e9152fd7 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/IfStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/IfStatement.java
@@ -39,11 +39,12 @@ public IfStatement(JooSymbol symIf, Expr cond, Statement ifTrue, JooSymbol symEl
this.ifFalse = ifFalse;
}
- public void analyze(AnalyzeContext context) {
- cond.analyze(context);
- ifTrue.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ cond.analyze(this, context);
+ ifTrue.analyze(this, context);
if (ifFalse != null)
- ifFalse.analyze(context);
+ ifFalse.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java b/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java
index d804e6216..8c6643104 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java
@@ -24,10 +24,23 @@ public class ImportDirective extends NodeImplBase {
JooSymbol importKeyword;
Type type;
+ JooSymbol semicolon;
- public ImportDirective(JooSymbol importKeyword, Type type) {
+ public ImportDirective(JooSymbol importKeyword, Type type, JooSymbol semicolon) {
this.importKeyword = importKeyword;
this.type = type;
+ this.semicolon = semicolon;
+ }
+
+ @Override
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ if (type instanceof IdeType) {
+ Ide ide = ((IdeType)type).ide;
+ context.getScope().declareIde(ide.getName(), this);
+ // also add first package path arc (might be the same string for top level imports):
+ context.getScope().declareIde(ide.getQualifiedName()[0], this);
+ }
}
public void generateCode(JsWriter out) throws IOException {
@@ -36,7 +49,9 @@ public void generateCode(JsWriter out) throws IOException {
out.write("\"");
out.writeSymbolToken(importKeyword);
type.generateCode(out);
- out.write("\",");
+ out.write("\"");
+ out.writeSymbolWhitespace(semicolon);
+ out.write(",");
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Initializer.java b/jooc/src/main/java/net/jangaroo/jooc/Initializer.java
index 774e25d01..ef3d2d9be 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Initializer.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Initializer.java
@@ -30,8 +30,9 @@ public Initializer(JooSymbol symEq, Expr value) {
this.value = value;
}
- public void analyze(AnalyzeContext context) {
- value.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ value.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/JooSymbol.java b/jooc/src/main/java/net/jangaroo/jooc/JooSymbol.java
index 9fb99c493..ded3f6ce5 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/JooSymbol.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/JooSymbol.java
@@ -26,6 +26,10 @@ public class JooSymbol extends java_cup.runtime.Symbol {
protected Object jooValue;
protected String fileName;
+ public JooSymbol(String text) {
+ this(net.jangaroo.jooc.sym.IDE, "", -1, -1, "", text);
+ }
+
public JooSymbol(int type, String fileName, int line, int column, String whitespace, String text) {
this(type, fileName, line, column, whitespace, text, null);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Jooc.java b/jooc/src/main/java/net/jangaroo/jooc/Jooc.java
index e7c014135..bf3a37157 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Jooc.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Jooc.java
@@ -51,7 +51,7 @@ public class Jooc {
public static final String CLASS_FULLY_QUALIFIED_NAME = CLASS_PACKAGE_NAME + "." + CLASS_CLASS_NAME;
private JoocConfiguration config;
- private CompileLog log = new CompileLog();
+ private static CompileLog log = new CompileLog();
private ArrayList<CompilationUnit> compilationUnits = new ArrayList<CompilationUnit>();
@@ -64,7 +64,7 @@ public int run(JoocConfiguration config) {
CompilationUnitSinkFactory codeSinkFactory = createSinkFactory(config);
for (CompilationUnit unit : compilationUnits) {
- unit.analyze(new AnalyzeContext());
+ unit.analyze(null, new AnalyzeContext());
unit.writeOutput(codeSinkFactory, config.isVerbose());
}
return log.hasErrors() ? 1 : 0;
@@ -129,6 +129,10 @@ public static void error(String msg, Throwable t) {
throw new CompilerError(msg, t);
}
+ static void warning(JooSymbol symbol, String msg) {
+ log.warning(symbol, msg);
+ }
+
protected void processSource(String fileName) {
processSource(new File(fileName));
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/LabelRefStatement.java b/jooc/src/main/java/net/jangaroo/jooc/LabelRefStatement.java
index b257199a8..7a3f8be9f 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/LabelRefStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/LabelRefStatement.java
@@ -31,8 +31,8 @@ class LabelRefStatement extends KeywordExprStatement {
protected LabeledStatement labelDeclaration = null;
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
Scope scope = context.getScope();
if (optLabel == null) {
Statement loopOrSwitchStatement = scope.getCurrentLoopOrSwitch();
diff --git a/jooc/src/main/java/net/jangaroo/jooc/LabeledStatement.java b/jooc/src/main/java/net/jangaroo/jooc/LabeledStatement.java
index da3a29fa1..3297f2217 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/LabeledStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/LabeledStatement.java
@@ -32,8 +32,9 @@ public LabeledStatement(Ide ide, JooSymbol symColon, Statement statement) {
this.statement = statement;
}
- public void analyze(AnalyzeContext context) {
- statement.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ statement.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/LoopStatement.java b/jooc/src/main/java/net/jangaroo/jooc/LoopStatement.java
index 7d7f892ab..7d00606f0 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/LoopStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/LoopStatement.java
@@ -41,10 +41,11 @@ public void generateCode(JsWriter out) throws IOException {
protected void generateLoopFooterCode(JsWriter out) throws IOException {
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
context.getScope().enterLoop(this);
analyzeLoopHeader(context);
- body.analyze(context);
+ body.analyze(this, context);
analyzeLoopFooter(context);
context.getScope().exitLoop(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/MemberDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/MemberDeclaration.java
index bbbc204e5..bfb59d875 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/MemberDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/MemberDeclaration.java
@@ -46,8 +46,8 @@ public boolean isConstructor() {
return false;
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (isField() || isMethod()) {
getClassDeclaration().registerMember(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java
index 14c34608a..11ecafe4a 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java
@@ -76,7 +76,7 @@ public boolean isAbstract() {
return getClassDeclaration().isInterface() || super.isAbstract();
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
parentDeclaration = context.getCurrentClass();
ClassDeclaration classDeclaration = getClassDeclaration();
if (ide.getName().equals(classDeclaration.getName())) {
@@ -84,7 +84,7 @@ public void analyze(AnalyzeContext context) {
classDeclaration.setConstructor(this);
allowedModifiers = MODIFIERS_SCOPE;
}
- super.analyze(context); // computes modifiers
+ super.analyze(parentNode, context); // computes modifiers
if (overrides() && isAbstract())
Jooc.error(this, "overriding methods are not allowed to be declared abstract");
if (isAbstract()) {
@@ -100,10 +100,13 @@ public void analyze(AnalyzeContext context) {
context.enterScope(this);
if (params != null)
- params.analyze(context);
+ params.analyze(this, context);
+ if (context.getScope().getIdeDeclaration("arguments")==null) {
+ context.getScope().declareIde("arguments", this); // is always defined inside a function!
+ }
if (optTypeRelation != null)
- optTypeRelation.analyze(context);
- optBody.analyze(context);
+ optTypeRelation.analyze(this, context);
+ optBody.analyze(this, context);
context.leaveScope(this);
if (containsSuperConstructorCall()) {
@@ -130,17 +133,20 @@ public void generateCode(JsWriter out) throws IOException {
out.write(methodName);
out.write("\",");
out.writeSymbol(symFunction);
+ out.writeSymbolWhitespace(ide.ide);
if (out.getKeepSource()) {
out.write(" ");
if (isConstructor) {
// do not name the constructor initializer function like the class, or it will be called
// instead of the constructor function generated by the runtime! So we prefix it with a "$".
// The name is for debugging purposes only, anyway.
- out.write("$");
+ out.write("$"+methodName);
+ } else if (ide instanceof AccessorIde) {
+ out.write(((AccessorIde)ide).getFunctionName());
+ } else {
+ out.write(methodName);
}
- out.write(methodName);
}
- out.writeSymbolWhitespace(ide.ide);
}
out.writeSymbol(lParen);
if (params != null) {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/NewExpr.java b/jooc/src/main/java/net/jangaroo/jooc/NewExpr.java
index 0ee7c0319..42234e501 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/NewExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/NewExpr.java
@@ -36,9 +36,10 @@ public NewExpr(JooSymbol symNew, Type type, JooSymbol lParen, Arguments args, Jo
this.rParen = rParen;
}
- public void analyze(AnalyzeContext context) {
- if (args != null)
- args.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ if (args != null)
+ args.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Node.java b/jooc/src/main/java/net/jangaroo/jooc/Node.java
index 49019759e..2f37ef722 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Node.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Node.java
@@ -24,6 +24,6 @@ interface Node {
JooSymbol getSymbol();
void generateCode(JsWriter out) throws IOException;
- void analyze(AnalyzeContext context);
+ void analyze(Node parentNode, AnalyzeContext context);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/NodeImplBase.java b/jooc/src/main/java/net/jangaroo/jooc/NodeImplBase.java
index 0665c9aa0..06bd1c1cc 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/NodeImplBase.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/NodeImplBase.java
@@ -24,21 +24,23 @@
*/
public abstract class NodeImplBase implements Node {
+ Node parentNode;
+
void generateCode(Collection<Node> nodes, JsWriter out) throws IOException {
for (Node node : nodes) {
node.generateCode(out);
}
}
- public void analyze(AnalyzeContext context) {
- // default is to do nothing
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ this.parentNode = parentNode;
}
- public void analyze(Collection/*<Node>*/ nodes, AnalyzeContext context) {
+ public void analyze(Node parent, Collection/*<Node>*/ nodes, AnalyzeContext context) {
Iterator iter = nodes.iterator();
while (iter.hasNext()) {
NodeImplBase node = (NodeImplBase) iter.next();
- node.analyze(context);
+ node.analyze(parent, context);
}
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java b/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java
index 8ed5d8cbb..3831976b5 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java
@@ -32,9 +32,10 @@ public ObjectField(Expr nameExpr, JooSymbol symColon, Expr value) {
this.value = value;
}
- public void analyze(AnalyzeContext context) {
- nameExpr.analyze(context);
- value.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ nameExpr.analyze(this, context);
+ value.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ObjectFields.java b/jooc/src/main/java/net/jangaroo/jooc/ObjectFields.java
index 441fce247..725bcda4e 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ObjectFields.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ObjectFields.java
@@ -36,10 +36,11 @@ public ObjectFields(ObjectField field, JooSymbol symComma, ObjectFields tail) {
this.tail = tail;
}
- public void analyze(AnalyzeContext context) {
- field.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ field.analyze(this, context);
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ObjectLiteral.java b/jooc/src/main/java/net/jangaroo/jooc/ObjectLiteral.java
index 2aa38fc04..d5fee4cdd 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ObjectLiteral.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ObjectLiteral.java
@@ -39,9 +39,10 @@ public void generateCode(JsWriter out) throws IOException {
out.writeSymbol(rParen);
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
if (fields != null)
- fields.analyze(context);
+ fields.analyze(this, context);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java
index bf9eeb085..f82eaaf8d 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java
@@ -39,8 +39,11 @@ public void generateCode(JsWriter out) throws IOException {
out.write(",");
}
- public void analyze(AnalyzeContext context) {
- context.enterScope(this);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ // do *not* call super!
+ this.parentNode = parentNode;
+ // add first package path arc (might be the same string for top level imports):
+ context.getScope().declareIde(ide.getQualifiedName()[0], this);
}
public JooSymbol getSymbol() {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Parameters.java b/jooc/src/main/java/net/jangaroo/jooc/Parameters.java
index 617dbba61..d57b3aeae 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Parameters.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Parameters.java
@@ -45,11 +45,11 @@ public Parameters(Parameter param) {
this(param, null, null);
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
- param.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ param.analyze(this, context);
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/ParenthesizedExpr.java b/jooc/src/main/java/net/jangaroo/jooc/ParenthesizedExpr.java
index ae7759e6a..f293af14c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/ParenthesizedExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/ParenthesizedExpr.java
@@ -32,8 +32,9 @@ public ParenthesizedExpr(JooSymbol lParen, Expr expr, JooSymbol rParen) {
this.rParen = rParen;
}
- public void analyze(AnalyzeContext context) {
- expr.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ expr.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/Scope.java b/jooc/src/main/java/net/jangaroo/jooc/Scope.java
index 33016de50..5df7adb0c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/Scope.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/Scope.java
@@ -41,17 +41,13 @@ public Scope getParentScope() {
return parent;
}
- protected Map<String,IdeDeclaration> ides = new HashMap<String,IdeDeclaration>();
+ protected Map<String,Node> ides = new HashMap<String,Node>();
protected List<LabeledStatement> labels = new ArrayList<LabeledStatement>();
protected List<LoopStatement> loopStatementStack = new ArrayList<LoopStatement>();
protected List<KeywordStatement> loopOrSwitchStatementStack = new ArrayList<KeywordStatement>();
- public void declareIde(IdeDeclaration decl) {
- String name = decl.ide.getName();
- IdeDeclaration alreadyDeclared = ides.get(name);
- if (alreadyDeclared != null)
- Jooc.error(decl.ide.ide, "duplicate declaration of identifier '" + name + "'");
- ides.put(name, decl);
+ public Node declareIde(String name, Node decl) {
+ return ides.put(name, decl);
}
public void defineLabel(LabeledStatement labeledStatement) {
@@ -75,8 +71,12 @@ public LabeledStatement lookupLabel(Ide ide) {
return null; // not reached
}
- public IdeDeclaration getIdeDeclaration(Ide ide) {
- return ides.get(ide.getName());
+ public Node getIdeDeclaration(Ide ide) {
+ return getIdeDeclaration(ide.getName());
+ }
+
+ public Node getIdeDeclaration(String name) {
+ return ides.get(name);
}
public Scope findScopeThatDeclares(Ide ide) {
@@ -85,7 +85,7 @@ public Scope findScopeThatDeclares(Ide ide) {
: getParentScope().findScopeThatDeclares(ide);
}
- public IdeDeclaration lookupIde(Ide ide) {
+ public Node lookupIde(Ide ide) {
Scope scope = findScopeThatDeclares(ide);
if (scope == null)
Jooc.error(ide.ide, "undeclared identifier: '" + ide.getName() + "'");
diff --git a/jooc/src/main/java/net/jangaroo/jooc/StaticInitializer.java b/jooc/src/main/java/net/jangaroo/jooc/StaticInitializer.java
index 77ac16f46..2fc9722e3 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/StaticInitializer.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/StaticInitializer.java
@@ -38,10 +38,10 @@ public void generateCode(JsWriter out) throws IOException {
out.write(",");
}
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
context.enterScope(this);
- block.analyze(context);
+ block.analyze(this, context);
context.leaveScope(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/SuperConstructorCallStatement.java b/jooc/src/main/java/net/jangaroo/jooc/SuperConstructorCallStatement.java
index bea260f41..c3abb32b4 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/SuperConstructorCallStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/SuperConstructorCallStatement.java
@@ -37,7 +37,8 @@ public SuperConstructorCallStatement(JooSymbol symSuper, JooSymbol lParen, Argum
this.fun = new SuperExpr(symSuper);
}
- public void analyze(AnalyzeContext context) {
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
MethodDeclaration method = context.getCurrentMethod();
if (method == null || !method.isConstructor()) {
Jooc.error(symSuper, "must only call super constructor from constructor method");
@@ -48,7 +49,7 @@ public void analyze(AnalyzeContext context) {
method.setContainsSuperConstructorCall(true);
if (args != null)
- args.analyze(context);
+ args.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/SwitchStatement.java b/jooc/src/main/java/net/jangaroo/jooc/SwitchStatement.java
index 0fe499789..95bc57af3 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/SwitchStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/SwitchStatement.java
@@ -16,7 +16,6 @@
package net.jangaroo.jooc;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.List;
/**
@@ -34,10 +33,11 @@ public SwitchStatement(JooSymbol symSwitch, ParenthesizedExpr cond, JooSymbol lB
}
- public void analyze(AnalyzeContext context) {
- cond.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ cond.analyze(this, context);
context.getScope().enterSwitch(this);
- block.analyze(context);
+ block.analyze(this, context);
context.getScope().exitSwitch(this);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java b/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java
index be8c5442f..e4d27ae05 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java
@@ -22,6 +22,8 @@
*/
class TopLevelIdeExpr extends IdeExpr {
+ // TODO: add a compiler option for this:
+ public static final boolean ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS = true;
private Scope scope;
public TopLevelIdeExpr(Ide ide) {
@@ -29,8 +31,8 @@ public TopLevelIdeExpr(Ide ide) {
}
@Override
- public void analyze(AnalyzeContext context) {
- super.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
scope = context.getScope();
}
@@ -38,26 +40,27 @@ public void analyze(AnalyzeContext context) {
public void generateCode(JsWriter out) throws IOException {
if (scope!=null) {
Scope declaringScope = scope.findScopeThatDeclares(ide);
- if (declaringScope!=null) {
+ boolean addMissingThis = false;
+ if (declaringScope == null) {
+ addMissingThis = ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS && Character.isLowerCase(ide.getName().charAt(0));
+ Jooc.warning(ide.getSymbol(), "Undeclared identifier: "+ide.getName()
+ +(addMissingThis ? ", assuming it is an inherited member." : ""));
+ } else {
Node declaration = declaringScope.getDeclaration();
if (declaration instanceof ClassDeclaration) {
MemberDeclaration memberDeclaration = (MemberDeclaration)declaringScope.getIdeDeclaration(ide);
if (!memberDeclaration.isStatic() && !memberDeclaration.isConstructor()) {
- //System.out.println("WARNING: Adding probably missing 'this' to "+getSymbol());
- out.writeToken("this");
- if (memberDeclaration.isPrivate()) {
- out.write("[");
- // awkward, but we have to be careful if we add characters to tokens:
- out.writeSymbol(getSymbol(), "$", "");
- out.write("]");
- } else {
- out.write(".");
- out.writeSymbol(getSymbol());
- }
- return;
+ addMissingThis = true;
}
}
}
+ if (addMissingThis) {
+ DotExpr synthesizedDotExpr = new DotExpr(new ThisExpr(new JooSymbol("this")), new JooSymbol("."), this.ide);
+ synthesizedDotExpr.parentNode = parentNode;
+ synthesizedDotExpr.classDeclaration = scope.getClassDeclaration();
+ synthesizedDotExpr.generateCode(out);
+ return;
+ }
}
super.generateCode(out);
}
diff --git a/jooc/src/main/java/net/jangaroo/jooc/TryStatement.java b/jooc/src/main/java/net/jangaroo/jooc/TryStatement.java
index 4302a3b67..160ed45ec 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/TryStatement.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/TryStatement.java
@@ -40,11 +40,12 @@ public TryStatement(JooSymbol symTry, BlockStatement block, ArrayList catches, J
this.finallyBlock = finallyBlock;
}
- public void analyze(AnalyzeContext context) {
- block.analyze(context);
- analyze(catches, context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ block.analyze(this, context);
+ analyze(this, catches, context);
if (finallyBlock != null)
- finallyBlock.analyze(context);
+ finallyBlock.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/TypeList.java b/jooc/src/main/java/net/jangaroo/jooc/TypeList.java
index 380796543..f58280459 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/TypeList.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/TypeList.java
@@ -36,10 +36,11 @@ public TypeList(Type type, JooSymbol optComma, TypeList tail) {
this.tail = tail;
}
- public void analyze(AnalyzeContext context) {
- type.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ type.analyze(this, context);
if (tail != null)
- tail.analyze(context);
+ tail.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/TypeRelation.java b/jooc/src/main/java/net/jangaroo/jooc/TypeRelation.java
index 9f0091f85..9da96172a 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/TypeRelation.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/TypeRelation.java
@@ -35,8 +35,9 @@ public TypeRelation(JooSymbol symRelation, Type type) {
this.type = type;
}
- public void analyze(AnalyzeContext context) {
- type.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ type.analyze(this, context);
}
public void generateCode(JsWriter out) throws IOException {
diff --git a/jooc/src/main/java/net/jangaroo/jooc/UnaryOpExpr.java b/jooc/src/main/java/net/jangaroo/jooc/UnaryOpExpr.java
index 650d1ccf2..0fbc6d27c 100644
--- a/jooc/src/main/java/net/jangaroo/jooc/UnaryOpExpr.java
+++ b/jooc/src/main/java/net/jangaroo/jooc/UnaryOpExpr.java
@@ -28,8 +28,9 @@ public UnaryOpExpr(JooSymbol op, Expr arg) {
this.arg = arg;
}
- public void analyze(AnalyzeContext context) {
- arg.analyze(context);
+ public void analyze(Node parentNode, AnalyzeContext context) {
+ super.analyze(parentNode, context);
+ arg.analyze(this, context);
}
boolean isCompileTimeConstant() {
diff --git a/jooc/src/main/js/joo/Class.js b/jooc/src/main/js/joo/Class.js
index 74c7d2751..a9c5a8638 100644
--- a/jooc/src/main/js/joo/Class.js
+++ b/jooc/src/main/js/joo/Class.js
@@ -13,6 +13,21 @@
// JangarooScript runtime support. Author: Frank Wienberg
+Class = function Class(casted) {
+ return casted;
+};
+Class.$class = {
+ isInstance: function(object) {
+ return typeof object=="function";
+ }
+};
+trace = function(msg) {
+ if (window.console) {
+ console.log("AS3: "+msg);
+ } else {
+ document.writeln("AS3: "+msg);
+ }
+};
Function.prototype.getName = typeof Function.prototype.name=="string"
? (function getName() { return this.name; })
: (function() {
@@ -30,10 +45,15 @@ Function.prototype.getName = typeof Function.prototype.name=="string"
}());
Function.prototype.bind = function(object) {
+ if (this.$boundTo===object) {
+ return this;
+ }
var fn = this;
- return function() {
+ var f = function $boundMethod() {
return fn.apply(object,arguments);
};
+ f.$boundTo = object;
+ return f;
};
(function(theGlobalObject) {
@@ -67,6 +87,19 @@ Function.prototype.bind = function(object) {
function isFunction(object) {
return typeof object=="function" && object.constructor!==RegExp;
}
+ function getMethod(object, methodType, methodName) {
+ return methodType=="get" ? object.__lookupGetter__(methodName)
+ : methodType=="set" ? object.__lookupSetter__(methodName)
+ : isFunction(object[methodName]) ? object[methodName]
+ : null;
+ }
+ function setMethod(object, methodType, methodName, method) {
+ switch(methodType) {
+ case "get": object.__defineGetter__(methodName, method); break;
+ case "set": object.__defineSetter__(methodName, method); break;
+ default: object[methodName] = method;
+ }
+ }
function createEmptyConstructor($constructor) {
var emptyConstructor = function(){ this.constructor = $constructor; };
emptyConstructor.prototype = $constructor.prototype;
@@ -111,13 +144,7 @@ Function.prototype.bind = function(object) {
if (typeof member!="function" || member.$boundTo===object) {
return member;
}
- var boundMethod = function $boundMethod() {
- return member.apply(object,arguments);
- };
- // remember the object I am bound to:
- boundMethod.$boundTo = object;
- object[methodName]=boundMethod;
- return boundMethod;
+ return object[methodName]=member.bind(object);
}
function assert(cond, file, line, column) {
if (!cond)
@@ -186,7 +213,8 @@ Function.prototype.bind = function(object) {
var cd = this.classDescriptions[fullClassName];
if (!cd) {
var constr = getNativeClass(fullClassName);
- if (typeof constr=="function") {
+ var constrType = typeof constr;
+ if (constrType=="function" || constrType=="object") {
if (joo.Class.debug && theGlobalObject.console) {
console.debug("found non-Jangaroo class "+fullClassName+"!");
}
@@ -455,6 +483,7 @@ Function.prototype.bind = function(object) {
continue;
}
var memberType = "function";
+ var methodType = "method";
var memberName = undefined;
var modifiers;
if (typeof members=="string") {
@@ -467,6 +496,8 @@ Function.prototype.bind = function(object) {
visibility = "$"+modifier;
} else if (modifier=="var" || modifier=="const") {
memberType = modifier;
+ } else if (modifier=="get" || modifier=="set") {
+ methodType = modifier;
} else if (modifier=="override") {
// so far: ignore. TODO: enable super-call!
} else if (j==modifiers.length-1) {
@@ -490,19 +521,26 @@ Function.prototype.bind = function(object) {
// found static code block; execute on initialization
targetMap.$static.fieldsWithInitializer.push(members);
} else {
- setFunctionName(members, memberName);
+ if (methodType!="method") {
+ setFunctionName(members, methodType+"$"+memberName);
+ } else {
+ setFunctionName(members, memberName);
+ }
if (memberName==this.$class) {
this.$constructor = members;
} else {
if (memberKey=="$this") {
if (visibility=="$private") {
memberName = registerPrivateMember(privateStatic, classPrefix, memberName);
- } else if (isFunction(target[memberName])) {
- // Found overriding! Store super method as private method delegate for super access:
- this.Public.prototype[registerPrivateMember(privateStatic, classPrefix, memberName)] = target[memberName];
+ } else {
+ var overriddenMethod = getMethod(target, methodType, memberName);
+ if (overriddenMethod) {
+ // Found overriding! Store super method as private method delegate for super access:
+ setMethod(this.Public.prototype, methodType, registerPrivateMember(privateStatic, classPrefix, memberName), overriddenMethod);
+ }
}
}
- target[memberName] = members;
+ setMethod(target, methodType, memberName, members);
}
}
} else {
diff --git a/jooc/src/test/joo/example/Person.as b/jooc/src/test/joo/example/Person.as
index 97c1d0f0f..6d16def9a 100644
--- a/jooc/src/test/joo/example/Person.as
+++ b/jooc/src/test/joo/example/Person.as
@@ -49,14 +49,14 @@ public class Person {
* Render this person as HTML into the current document.
*/
public function render(): void {
- document.write("<div>"+this.renderInner()+"</div>");
+ window.document.write("<div>"+this.renderInner()+"</div>");
}
/**
* Get the inner HTML presenting this person.
* Subclasses should add a presentation of their additional properties.
*/
- protected function renderInner(): void {
+ protected function renderInner(): String {
this.privateTest("foo");
return "<p>name: "+this.getName()+"</p>";
}
diff --git a/jooc/src/test/joo/package1/TestBind.as b/jooc/src/test/joo/package1/TestBind.as
new file mode 100644
index 000000000..c295fa1d5
--- /dev/null
+++ b/jooc/src/test/joo/package1/TestBind.as
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2008 CoreMedia AG
+ *
+ * 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 package1 {
+
+[Event]
+public class TestBind {
+
+ public function TestBind(state : String) {
+ this.state = state;
+ //joo.bind(this,"getState");
+ }
+
+ //[Bound]
+ public function getState() : String {
+ return this.state;
+ }
+
+ //[Bound]
+ private function getStatePrivate() : String {
+ return this.state;
+ }
+
+ public function testInvokeLocalVar() : * {
+ var f : Function = this.getState;
+ return f();
+ }
+
+ public function testInvokeLocalVarUnqualified() : * {
+ var f : Function = getState;
+ return f();
+ }
+
+ public function testInvokeParameter() : String {
+ return this.invoke(this.getState);
+ }
+
+ public function testInvokeParameterUnqualified() : String {
+ return invoke(getState);
+ }
+
+ public function testInvokeParameterUnqualifiedPrivate() : String {
+ return invoke(getStatePrivate);
+ }
+
+ public function testDelete() : Boolean {
+ delete this.testDelete;
+ return "testDelete" in this;
+ }
+
+ private function invoke(f : Function) : * {
+ return f();
+ }
+
+ private var state : String;
+}
+}
\ No newline at end of file
|
69902e6dedbfeb4e44eace12a101169cdfb97def
|
restlet-framework-java
|
Add SpringRouter-style supplemental direct routing- via the attachments property. This allows for multiple routes for the same- bean or routes which would be illegal/unmatched as bean names.--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java b/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java
index 1101183992..b686612d6a 100644
--- a/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java
+++ b/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java
@@ -41,6 +41,8 @@
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
+import java.util.Map;
+
/**
* Restlet {@link Router} which behaves like Spring's
* {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping}. It
@@ -85,6 +87,9 @@ public class SpringBeanRouter extends Router implements
/** If beans should be searched for higher up in the BeanFactory hierarchy */
private volatile boolean findInAncestors = true;
+ /** Supplemental explicit mappings */
+ private Map<String, String> attachments;
+
/**
* Creates an instance of {@link SpringBeanFinder}. This can be overriden if
* necessary.
@@ -130,7 +135,14 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
for (final String name : names) {
final String uri = resolveUri(name, factory);
if (uri != null) {
- attach(uri, createFinder(bf, name));
+ if (this.attachments == null || !this.attachments.containsKey(uri)) {
+ attach(uri, createFinder(bf, name));
+ }
+ }
+ }
+ if (this.attachments != null) {
+ for (Map.Entry<String, String> attachment : this.attachments.entrySet()) {
+ attach(attachment.getKey(), createFinder(bf, attachment.getValue()));
}
}
}
@@ -180,4 +192,16 @@ public void setApplicationContext(ApplicationContext applicationContext)
public void setFindInAncestors(boolean findInAncestors) {
this.findInAncestors = findInAncestors;
}
+
+ /**
+ * Sets an explicit mapping of URI templates to bean IDs to use
+ * in addition to the usual bean name mapping behavior. If a URI template
+ * appears in both this mapping and as a bean name, the bean it is mapped
+ * to here is the one that will be used.
+ *
+ * @see SpringRouter
+ */
+ public void setAttachments(Map<String, String> attachments) {
+ this.attachments = attachments;
+ }
}
diff --git a/modules/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java
index b9bd592724..847a959a5c 100644
--- a/modules/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java
+++ b/modules/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java
@@ -31,6 +31,9 @@
package org.restlet.test.ext.spring;
import org.restlet.Restlet;
+import org.restlet.data.Method;
+import org.restlet.data.Request;
+import org.restlet.data.Response;
import org.restlet.ext.spring.SpringBeanFinder;
import org.restlet.ext.spring.SpringBeanRouter;
import org.restlet.resource.Resource;
@@ -41,9 +44,10 @@
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
+import java.util.Collections;
import java.util.HashSet;
-import java.util.Set;
import java.util.List;
+import java.util.Set;
/**
* @author Rhett Sutphin
@@ -57,7 +61,7 @@ public class SpringBeanRouterTestCase extends RestletTestCase {
private SpringBeanRouter router;
private void assertFinderForBean(String expectedBeanName, Restlet restlet) {
- assertTrue("Restlet is not a bean finder restlet",
+ assertTrue("Restlet is not a bean finder restlet: " + restlet.getClass().getName(),
restlet instanceof SpringBeanFinder);
final SpringBeanFinder actualFinder = (SpringBeanFinder) restlet;
assertEquals("Finder does not point to correct bean", expectedBeanName,
@@ -90,6 +94,11 @@ private void registerResourceBeanDefinition(String id, String alias) {
}
}
+ private RouteList actualRoutes() {
+ this.router.postProcessBeanFactory(this.factory);
+ return this.router.getRoutes();
+ }
+
private Set<String> routeUris(List<Route> routes) {
final Set<String> uris = new HashSet<String>();
for (final Route actualRoute : routes) {
@@ -119,15 +128,8 @@ public void testRoutesCreatedForBeanIdsIfAppropriate() throws Exception {
public void testRoutesPointToFindersForBeans() throws Exception {
final RouteList actualRoutes = actualRoutes();
assertEquals("Wrong number of routes", 2, actualRoutes.size());
- Route oreRoute = null, fishRoute = null;
- for (final Route actualRoute : actualRoutes) {
- if (actualRoute.getTemplate().getPattern().equals(FISH_URI)) {
- fishRoute = actualRoute;
- }
- if (actualRoute.getTemplate().getPattern().equals(ORE_URI)) {
- oreRoute = actualRoute;
- }
- }
+ Route oreRoute = matchRouteFor(ORE_URI);
+ Route fishRoute = matchRouteFor(FISH_URI);
assertNotNull("ore route not present: " + actualRoutes, oreRoute);
assertNotNull("fish route not present: " + actualRoutes, fishRoute);
@@ -135,13 +137,6 @@ public void testRoutesPointToFindersForBeans() throws Exception {
assertFinderForBean("fish", fishRoute.getNext());
}
- private RouteList actualRoutes() {
- this.router.postProcessBeanFactory(this.factory);
-
- final RouteList actualRoutes = this.router.getRoutes();
- return actualRoutes;
- }
-
public void testRoutingSkipsResourcesWithoutAppropriateAliases()
throws Exception {
final BeanDefinition bd = new RootBeanDefinition(Resource.class);
@@ -153,4 +148,35 @@ public void testRoutingSkipsResourcesWithoutAppropriateAliases()
assertEquals("Timber resource should have been skipped", 2,
actualRoutes.size());
}
+
+ public void testRoutingIncludesSpringRouterStyleExplicitlyMappedBeans() throws Exception {
+ final BeanDefinition bd = new RootBeanDefinition(Resource.class);
+ bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
+ this.factory.registerBeanDefinition("timber", bd);
+ this.factory.registerAlias("timber", "no-slash");
+
+ String expectedTemplate = "/renewable/timber/{farm_type}";
+ router.setAttachments(Collections.singletonMap(expectedTemplate, "timber"));
+ final RouteList actualRoutes = actualRoutes();
+
+ assertEquals("Wrong number of routes", 3, actualRoutes.size());
+ Route timberRoute = matchRouteFor(expectedTemplate);
+ assertNotNull("Missing timber route: " + actualRoutes, timberRoute);
+ assertFinderForBean("timber", timberRoute.getNext());
+ }
+
+ public void testExplicitAttachmentsTrumpBeanNames() throws Exception {
+ this.router.setAttachments(Collections.singletonMap(ORE_URI, "fish"));
+ RouteList actualRoutes = actualRoutes();
+ assertEquals("Wrong number of routes", 2, actualRoutes.size());
+
+ Route oreRoute = matchRouteFor(ORE_URI);
+ assertNotNull("No route for " + ORE_URI, oreRoute);
+ assertFinderForBean("fish", oreRoute.getNext());
+ }
+
+ private Route matchRouteFor(String uri) {
+ Request req = new Request(Method.GET, uri);
+ return (Route) router.getNext(req, new Response(req));
+ }
}
|
cc6bd6239a2cf8db9b661e987e22c36737621db2
|
kotlin
|
Remove unused method--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java
index 2f07308102b69..bc9a03f608cc9 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java
@@ -19,7 +19,6 @@
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.intellij.lang.ASTNode;
-import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
@@ -70,7 +69,7 @@ protected BasicExpressionTypingVisitor(@NotNull ExpressionTypingInternals facade
public JetTypeInfo visitSimpleNameExpression(JetSimpleNameExpression expression, ExpressionTypingContext context) {
// TODO : other members
// TODO : type substitutions???
- JetTypeInfo typeInfo = getSelectorReturnTypeInfo(NO_RECEIVER, null, expression, context);
+ JetTypeInfo typeInfo = getSimpleNameExpressionTypeInfo(expression, NO_RECEIVER, null, context);
JetType type = DataFlowUtils.checkType(typeInfo.getType(), expression, context);
ExpressionTypingUtils.checkWrappingInRef(expression, context.trace, context.scope);
return JetTypeInfo.create(type, typeInfo.getDataFlowInfo()); // TODO : Extensions to this
@@ -769,7 +768,7 @@ private JetType getVariableType(@NotNull JetSimpleNameExpression nameExpression,
}
@NotNull
- public JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) {
+ private JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) {
if (selectorExpression instanceof JetCallExpression) {
return getCallExpressionTypeInfo((JetCallExpression) selectorExpression, receiver, callOperationNode, context);
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java
index df4c2a5cac081..c9b826f6d6207 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java
@@ -16,20 +16,14 @@
package org.jetbrains.jet.lang.types.expressions;
-import com.intellij.lang.ASTNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.psi.JetElement;
import org.jetbrains.jet.lang.psi.JetExpression;
import org.jetbrains.jet.lang.psi.JetSimpleNameExpression;
-import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.jet.lang.types.JetTypeInfo;
/*package*/ interface ExpressionTypingInternals extends ExpressionTypingFacade {
-
- @NotNull
- JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context);
-
@NotNull
JetTypeInfo checkInExpression(JetElement callElement, @NotNull JetSimpleNameExpression operationSign, @Nullable JetExpression left, @NotNull JetExpression right, ExpressionTypingContext context);
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java
index 8d4d338837c9c..ee9a8737fb3cc 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java
@@ -16,14 +16,12 @@
package org.jetbrains.jet.lang.types.expressions;
-import com.intellij.lang.ASTNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowInfo;
import org.jetbrains.jet.lang.resolve.scopes.WritableScope;
-import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.jet.lang.types.DeferredType;
import org.jetbrains.jet.lang.types.ErrorUtils;
import org.jetbrains.jet.lang.types.JetTypeInfo;
@@ -64,11 +62,6 @@ private ExpressionTypingVisitorDispatcher(WritableScope writableScope) {
}
}
- @Override
- public JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) {
- return basic.getSelectorReturnTypeInfo(receiver, callOperationNode, selectorExpression, context);
- }
-
@NotNull
@Override
public JetTypeInfo checkInExpression(JetElement callElement, @NotNull JetSimpleNameExpression operationSign, @Nullable JetExpression left, @NotNull JetExpression right, ExpressionTypingContext context) {
|
eacef5292eec40870a44812d0389293a21a7fc49
|
tapiji
|
Fix NPE during startup of translator application.
Fixes NPE during lookup of project name for RCP translator.
|
c
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java
index bf318882..69ba753c 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/internal/MessagesBundleGroup.java
@@ -38,569 +38,578 @@
* @author Pascal Essiembre ([email protected])
*/
public class MessagesBundleGroup extends AbstractMessageModel implements
- IMessagesBundleGroup {
-
- private String projectName;
-
- private static final IMessagesBundleGroupListener[] EMPTY_GROUP_LISTENERS = new IMessagesBundleGroupListener[] {};
- private static final Message[] EMPTY_MESSAGES = new Message[] {};
-
- public static final String PROPERTY_MESSAGES_BUNDLE_COUNT = "messagesBundleCount"; //$NON-NLS-1$
- public static final String PROPERTY_KEY_COUNT = "keyCount"; //$NON-NLS-1$
-
- /** For serialization. */
- private static final long serialVersionUID = -1977849534191384324L;
- /** Bundles forming the group (key=Locale; value=MessagesBundle). */
- private final Map<Locale, IMessagesBundle> localeBundles = new HashMap<Locale, IMessagesBundle>();
- private final Set<String> keys = new TreeSet<String>();
- private final IMessagesBundleListener messagesBundleListener = new MessagesBundleListener();
-
- private final IMessagesBundleGroupStrategy groupStrategy;
- private static final Locale[] EMPTY_LOCALES = new Locale[] {};
- private final String name;
- private final String resourceBundleId;
-
- /**
- * Creates a new messages bundle group.
- *
- * @param groupStrategy
- * a IMessagesBundleGroupStrategy instance
- */
- public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) {
- super();
- this.groupStrategy = groupStrategy;
- this.name = groupStrategy.createMessagesBundleGroupName();
- this.resourceBundleId = groupStrategy.createMessagesBundleId();
-
- this.projectName = groupStrategy.getProjectName();
-
- MessagesBundle[] bundles = groupStrategy.loadMessagesBundles();
- if (bundles != null) {
- for (int i = 0; i < bundles.length; i++) {
- addMessagesBundle(bundles[i]);
- }
- }
+ IMessagesBundleGroup {
- RBManager.getInstance(this.projectName)
- .notifyMessagesBundleGroupCreated(this);
- }
+ private String projectName;
- /**
- * Called before this object will be discarded. Disposes the underlying
- * MessageBundles
- */
- @Override
- public void dispose() {
- for (IMessagesBundle mb : getMessagesBundles()) {
- try {
- mb.dispose();
- } catch (Throwable t) {
- // FIXME: remove debug:
- System.err.println("Error disposing message-bundle "
- + ((MessagesBundle) mb).getResource()
- .getResourceLocationLabel());
- // disregard crashes: this is a best effort to dispose things.
- }
- }
+ private static final IMessagesBundleGroupListener[] EMPTY_GROUP_LISTENERS = new IMessagesBundleGroupListener[] {};
+ private static final Message[] EMPTY_MESSAGES = new Message[] {};
- RBManager.getInstance(this.projectName)
- .notifyMessagesBundleGroupDeleted(this);
- }
+ public static final String PROPERTY_MESSAGES_BUNDLE_COUNT = "messagesBundleCount"; //$NON-NLS-1$
+ public static final String PROPERTY_KEY_COUNT = "keyCount"; //$NON-NLS-1$
- /**
- * Gets the messages bundle matching given locale.
- *
- * @param locale
- * locale of bundle to retreive
- * @return a bundle
- */
- @Override
- public IMessagesBundle getMessagesBundle(Locale locale) {
- return localeBundles.get(locale);
- }
+ /** For serialization. */
+ private static final long serialVersionUID = -1977849534191384324L;
+ /** Bundles forming the group (key=Locale; value=MessagesBundle). */
+ private final Map<Locale, IMessagesBundle> localeBundles = new HashMap<Locale, IMessagesBundle>();
+ private final Set<String> keys = new TreeSet<String>();
+ private final IMessagesBundleListener messagesBundleListener = new MessagesBundleListener();
- /**
- * Gets the messages bundle matching given source object. A source object
- * being a context-specific concrete underlying implementation of a
- * <code>MessagesBundle</code> as per defined in
- * <code>IMessageResource</code>.
- *
- * @param source
- * the source object to match
- * @return a messages bundle
- * @see IMessagesResource
- */
- public MessagesBundle getMessagesBundle(Object source) {
- for (IMessagesBundle messagesBundle : getMessagesBundles()) {
- if (equals(source, ((MessagesBundle) messagesBundle).getResource()
- .getSource())) {
- return (MessagesBundle) messagesBundle;
- }
- }
- return null;
- }
+ private final IMessagesBundleGroupStrategy groupStrategy;
+ private static final Locale[] EMPTY_LOCALES = new Locale[] {};
+ private final String name;
+ private final String resourceBundleId;
- /**
- * Adds an empty <code>MessagesBundle</code> to this group for the given
- * locale.
- *
- * @param locale
- * locale for the new bundle added
- */
- public void addMessagesBundle(Locale locale) {
- addMessagesBundle(groupStrategy.createMessagesBundle(locale));
- }
+ /**
+ * Creates a new messages bundle group.
+ *
+ * @param groupStrategy
+ * a IMessagesBundleGroupStrategy instance
+ */
+ public MessagesBundleGroup(IMessagesBundleGroupStrategy groupStrategy) {
+ super();
+ this.groupStrategy = groupStrategy;
+ this.name = groupStrategy.createMessagesBundleGroupName();
+ this.resourceBundleId = groupStrategy.createMessagesBundleId();
- /**
- * Gets all locales making up this messages bundle group.
- */
- public Locale[] getLocales() {
- return localeBundles.keySet().toArray(EMPTY_LOCALES);
- }
+ this.projectName = groupStrategy.getProjectName();
- /**
- * Gets all messages associated with the given message key.
- *
- * @param key
- * a message key
- * @return messages
- */
- @Override
- public IMessage[] getMessages(String key) {
- List<IMessage> messages = new ArrayList<IMessage>();
- for (IMessagesBundle messagesBundle : getMessagesBundles()) {
- IMessage message = messagesBundle.getMessage(key);
- if (message != null) {
- messages.add(message);
- }
- }
- return messages.toArray(EMPTY_MESSAGES);
+ MessagesBundle[] bundles = groupStrategy.loadMessagesBundles();
+ if (bundles != null) {
+ for (int i = 0; i < bundles.length; i++) {
+ addMessagesBundle(bundles[i]);
+ }
}
- /**
- * Gets the message matching given key and locale.
- *
- * @param locale
- * locale for which to retrieve the message
- * @param key
- * key matching entry to retrieve the message
- * @return a message
- */
- @Override
- public IMessage getMessage(String key, Locale locale) {
- IMessagesBundle messagesBundle = getMessagesBundle(locale);
- if (messagesBundle != null) {
- return messagesBundle.getMessage(key);
- }
- return null;
+ if (this.projectName != null) {
+ RBManager.getInstance(this.projectName)
+ .notifyMessagesBundleGroupCreated(this);
}
+ }
+
+ /**
+ * Called before this object will be discarded. Disposes the underlying
+ * MessageBundles
+ */
+ @Override
+ public void dispose() {
+ for (IMessagesBundle mb : getMessagesBundles()) {
+ try {
+ mb.dispose();
+ } catch (Throwable t) {
+ // FIXME: remove debug:
+ System.err.println("Error disposing message-bundle "
+ + ((MessagesBundle) mb).getResource()
+ .getResourceLocationLabel());
+ // disregard crashes: this is a best effort to dispose things.
+ }
+ }
+
+ RBManager.getInstance(this.projectName)
+ .notifyMessagesBundleGroupDeleted(this);
+ }
- /**
- * Adds a messages bundle to this group.
- *
- * @param messagesBundle
- * bundle to add
- * @throws MessageException
- * if a messages bundle for the same locale already exists.
- */
- public void addMessagesBundle(IMessagesBundle messagesBundle) {
- addMessagesBundle(messagesBundle.getLocale(), messagesBundle);
+ /**
+ * Gets the messages bundle matching given locale.
+ *
+ * @param locale
+ * locale of bundle to retreive
+ * @return a bundle
+ */
+ @Override
+ public IMessagesBundle getMessagesBundle(Locale locale) {
+ return localeBundles.get(locale);
+ }
+
+ /**
+ * Gets the messages bundle matching given source object. A source object
+ * being a context-specific concrete underlying implementation of a
+ * <code>MessagesBundle</code> as per defined in
+ * <code>IMessageResource</code>.
+ *
+ * @param source
+ * the source object to match
+ * @return a messages bundle
+ * @see IMessagesResource
+ */
+ public MessagesBundle getMessagesBundle(Object source) {
+ for (IMessagesBundle messagesBundle : getMessagesBundles()) {
+ if (equals(source, ((MessagesBundle) messagesBundle).getResource()
+ .getSource())) {
+ return (MessagesBundle) messagesBundle;
+ }
}
+ return null;
+ }
- /**
- * Adds a messages bundle to this group.
- *
- * @param locale
- * The locale of the bundle
- * @param messagesBundle
- * bundle to add
- * @throws MessageException
- * if a messages bundle for the same locale already exists.
- */
- @Override
- public void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle) {
- MessagesBundle mb = (MessagesBundle) messagesBundle;
- if (localeBundles.get(mb.getLocale()) != null) {
- throw new MessageException(
- "A bundle with the same locale already exists."); //$NON-NLS-1$
- }
+ /**
+ * Adds an empty <code>MessagesBundle</code> to this group for the given
+ * locale.
+ *
+ * @param locale
+ * locale for the new bundle added
+ */
+ public void addMessagesBundle(Locale locale) {
+ addMessagesBundle(groupStrategy.createMessagesBundle(locale));
+ }
- int oldBundleCount = localeBundles.size();
- localeBundles.put(mb.getLocale(), mb);
-
- firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount,
- localeBundles.size());
- fireMessagesBundleAdded(mb);
-
- String[] bundleKeys = mb.getKeys();
- for (int i = 0; i < bundleKeys.length; i++) {
- String key = bundleKeys[i];
- if (!keys.contains(key)) {
- int oldKeyCount = keys.size();
- keys.add(key);
- firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size());
- fireKeyAdded(key);
- }
- }
- mb.addMessagesBundleListener(messagesBundleListener);
+ /**
+ * Gets all locales making up this messages bundle group.
+ */
+ public Locale[] getLocales() {
+ return localeBundles.keySet().toArray(EMPTY_LOCALES);
+ }
+ /**
+ * Gets all messages associated with the given message key.
+ *
+ * @param key
+ * a message key
+ * @return messages
+ */
+ @Override
+ public IMessage[] getMessages(String key) {
+ List<IMessage> messages = new ArrayList<IMessage>();
+ for (IMessagesBundle messagesBundle : getMessagesBundles()) {
+ IMessage message = messagesBundle.getMessage(key);
+ if (message != null) {
+ messages.add(message);
+ }
+ }
+ return messages.toArray(EMPTY_MESSAGES);
+ }
+
+ /**
+ * Gets the message matching given key and locale.
+ *
+ * @param locale
+ * locale for which to retrieve the message
+ * @param key
+ * key matching entry to retrieve the message
+ * @return a message
+ */
+ @Override
+ public IMessage getMessage(String key, Locale locale) {
+ IMessagesBundle messagesBundle = getMessagesBundle(locale);
+ if (messagesBundle != null) {
+ return messagesBundle.getMessage(key);
}
+ return null;
+ }
- /**
- * Removes the {@link IMessagesBundle} from the group.
- * @param messagesBundle The bundle to remove.
- */
- @Override
- public void removeMessagesBundle(IMessagesBundle messagesBundle) {
- Locale locale = messagesBundle.getLocale();
+ /**
+ * Adds a messages bundle to this group.
+ *
+ * @param messagesBundle
+ * bundle to add
+ * @throws MessageException
+ * if a messages bundle for the same locale already exists.
+ */
+ public void addMessagesBundle(IMessagesBundle messagesBundle) {
+ addMessagesBundle(messagesBundle.getLocale(), messagesBundle);
+ }
- if (localeBundles.containsKey(locale)) {
- localeBundles.remove(locale);
- }
+ /**
+ * Adds a messages bundle to this group.
+ *
+ * @param locale
+ * The locale of the bundle
+ * @param messagesBundle
+ * bundle to add
+ * @throws MessageException
+ * if a messages bundle for the same locale already exists.
+ */
+ @Override
+ public void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle) {
+ MessagesBundle mb = (MessagesBundle) messagesBundle;
+ if (localeBundles.get(mb.getLocale()) != null) {
+ throw new MessageException(
+ "A bundle with the same locale already exists."); //$NON-NLS-1$
+ }
- // which keys should I not remove?
- Set<String> keysNotToRemove = new TreeSet<String>();
+ int oldBundleCount = localeBundles.size();
+ localeBundles.put(mb.getLocale(), mb);
- for (String key : messagesBundle.getKeys()) {
- for (IMessagesBundle bundle : localeBundles.values()) {
- if (bundle.getMessage(key) != null) {
- keysNotToRemove.add(key);
- }
- }
- }
+ firePropertyChange(PROPERTY_MESSAGES_BUNDLE_COUNT, oldBundleCount,
+ localeBundles.size());
+ fireMessagesBundleAdded(mb);
- // remove keys
- for (String keyToRemove : messagesBundle.getKeys()) {
- if (!keysNotToRemove.contains(keyToRemove)) { // we can remove
- keys.remove(keyToRemove);
- }
- }
+ String[] bundleKeys = mb.getKeys();
+ for (int i = 0; i < bundleKeys.length; i++) {
+ String key = bundleKeys[i];
+ if (!keys.contains(key)) {
+ int oldKeyCount = keys.size();
+ keys.add(key);
+ firePropertyChange(PROPERTY_KEY_COUNT, oldKeyCount, keys.size());
+ fireKeyAdded(key);
+ }
}
+ mb.addMessagesBundleListener(messagesBundleListener);
+
+ }
/**
- * Gets this messages bundle group name. That is the name, which is used
- * for the tab of the MultiPageEditorPart
- * @return bundle group name
+ * Removes the {@link IMessagesBundle} from the group.
+ *
+ * @param messagesBundle
+ * The bundle to remove.
*/
- @Override
- public String getName() {
- return name;
- }
+ @Override
+ public void removeMessagesBundle(IMessagesBundle messagesBundle) {
+ Locale locale = messagesBundle.getLocale();
- /**
- * Adds an empty message to every messages bundle of this group with the
- * given.
- *
- * @param key
- * message key
- */
- @Override
- public void addMessages(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- ((MessagesBundle) msgBundle).addMessage(key);
- }
+ if (localeBundles.containsKey(locale)) {
+ localeBundles.remove(locale);
}
- /**
- * Renames a key in all messages bundles forming this group.
- *
- * @param sourceKey
- * the message key to rename
- * @param targetKey
- * the new message name
- */
- public void renameMessageKeys(String sourceKey, String targetKey) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.renameMessageKey(sourceKey, targetKey);
- }
- }
+ // which keys should I not remove?
+ Set<String> keysNotToRemove = new TreeSet<String>();
- /**
- * Removes messages matching the given key from all messages bundle.
- *
- * @param key
- * key of messages to remove
- */
- @Override
- public void removeMessages(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.removeMessage(key);
+ for (String key : messagesBundle.getKeys()) {
+ for (IMessagesBundle bundle : localeBundles.values()) {
+ if (bundle.getMessage(key) != null) {
+ keysNotToRemove.add(key);
}
+ }
}
- /**
- * Removes messages matching the given key from all messages bundle and add
- * it's parent key to bundles.
- *
- * @param key
- * key of messages to remove
- */
- @Override
- public void removeMessagesAddParentKey(String key) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.removeMessageAddParentKey(key);
- }
+ // remove keys
+ for (String keyToRemove : messagesBundle.getKeys()) {
+ if (!keysNotToRemove.contains(keyToRemove)) { // we can remove
+ keys.remove(keyToRemove);
+ }
}
+ }
- /**
- * Sets whether messages matching the <code>key</code> are active or not.
- *
- * @param key
- * key of messages
- */
- public void setMessagesActive(String key, boolean active) {
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- IMessage entry = msgBundle.getMessage(key);
- if (entry != null) {
- entry.setActive(active);
- }
- }
- }
+ /**
+ * Gets this messages bundle group name. That is the name, which is used for
+ * the tab of the MultiPageEditorPart
+ *
+ * @return bundle group name
+ */
+ @Override
+ public String getName() {
+ return name;
+ }
- /**
- * Duplicates each messages matching the <code>sourceKey</code> to the
- * <code>newKey</code>.
- *
- * @param sourceKey
- * original key
- * @param targetKey
- * new key
- * @throws MessageException
- * if a target key already exists
- */
- public void duplicateMessages(String sourceKey, String targetKey) {
- if (sourceKey.equals(targetKey)) {
- return;
- }
- for (IMessagesBundle msgBundle : localeBundles.values()) {
- msgBundle.duplicateMessage(sourceKey, targetKey);
- }
+ /**
+ * Adds an empty message to every messages bundle of this group with the
+ * given.
+ *
+ * @param key
+ * message key
+ */
+ @Override
+ public void addMessages(String key) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ ((MessagesBundle) msgBundle).addMessage(key);
}
+ }
- /**
- * Returns a collection of all bundles in this group.
- *
- * @return the bundles in this group
- */
- @Override
- public Collection<IMessagesBundle> getMessagesBundles() {
- return localeBundles.values();
+ /**
+ * Renames a key in all messages bundles forming this group.
+ *
+ * @param sourceKey
+ * the message key to rename
+ * @param targetKey
+ * the new message name
+ */
+ public void renameMessageKeys(String sourceKey, String targetKey) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.renameMessageKey(sourceKey, targetKey);
}
+ }
- /**
- * Gets all keys from all messages bundles.
- *
- * @return all keys from all messages bundles
- */
- @Override
- public String[] getMessageKeys() {
- return keys.toArray(BabelUtils.EMPTY_STRINGS);
+ /**
+ * Removes messages matching the given key from all messages bundle.
+ *
+ * @param key
+ * key of messages to remove
+ */
+ @Override
+ public void removeMessages(String key) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.removeMessage(key);
}
+ }
- /**
- * Whether the given key is found in this messages bundle group.
- *
- * @param key
- * the key to find
- * @return <code>true</code> if the key exists in this bundle group.
- */
- @Override
- public boolean isMessageKey(String key) {
- return keys.contains(key);
+ /**
+ * Removes messages matching the given key from all messages bundle and add
+ * it's parent key to bundles.
+ *
+ * @param key
+ * key of messages to remove
+ */
+ @Override
+ public void removeMessagesAddParentKey(String key) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.removeMessageAddParentKey(key);
}
+ }
- /**
- * Gets the number of messages bundles in this group.
- *
- * @return the number of messages bundles in this group
- */
- @Override
- public int getMessagesBundleCount() {
- return localeBundles.size();
+ /**
+ * Sets whether messages matching the <code>key</code> are active or not.
+ *
+ * @param key
+ * key of messages
+ */
+ public void setMessagesActive(String key, boolean active) {
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ IMessage entry = msgBundle.getMessage(key);
+ if (entry != null) {
+ entry.setActive(active);
+ }
}
+ }
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof MessagesBundleGroup)) {
- return false;
- }
- MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj;
- return equals(localeBundles, messagesBundleGroup.localeBundles);
+ /**
+ * Duplicates each messages matching the <code>sourceKey</code> to the
+ * <code>newKey</code>.
+ *
+ * @param sourceKey
+ * original key
+ * @param targetKey
+ * new key
+ * @throws MessageException
+ * if a target key already exists
+ */
+ public void duplicateMessages(String sourceKey, String targetKey) {
+ if (sourceKey.equals(targetKey)) {
+ return;
}
-
- public final synchronized void addMessagesBundleGroupListener(
- final IMessagesBundleGroupListener listener) {
- addPropertyChangeListener(listener);
+ for (IMessagesBundle msgBundle : localeBundles.values()) {
+ msgBundle.duplicateMessage(sourceKey, targetKey);
}
+ }
- public final synchronized void removeMessagesBundleGroupListener(
- final IMessagesBundleGroupListener listener) {
- removePropertyChangeListener(listener);
- }
+ /**
+ * Returns a collection of all bundles in this group.
+ *
+ * @return the bundles in this group
+ */
+ @Override
+ public Collection<IMessagesBundle> getMessagesBundles() {
+ return localeBundles.values();
+ }
- public final synchronized IMessagesBundleGroupListener[] getMessagesBundleGroupListeners() {
- // TODO find more efficient way to avoid class cast.
- return Arrays.asList(getPropertyChangeListeners()).toArray(
- EMPTY_GROUP_LISTENERS);
- }
+ /**
+ * Gets all keys from all messages bundles.
+ *
+ * @return all keys from all messages bundles
+ */
+ @Override
+ public String[] getMessageKeys() {
+ return keys.toArray(BabelUtils.EMPTY_STRINGS);
+ }
- private void fireKeyAdded(String key) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.keyAdded(key);
- }
- }
+ /**
+ * Whether the given key is found in this messages bundle group.
+ *
+ * @param key
+ * the key to find
+ * @return <code>true</code> if the key exists in this bundle group.
+ */
+ @Override
+ public boolean isMessageKey(String key) {
+ return keys.contains(key);
+ }
- private void fireKeyRemoved(String key) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.keyRemoved(key);
- }
- }
+ /**
+ * Gets the number of messages bundles in this group.
+ *
+ * @return the number of messages bundles in this group
+ */
+ @Override
+ public int getMessagesBundleCount() {
+ return localeBundles.size();
+ }
- private void fireMessagesBundleAdded(MessagesBundle messagesBundle) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleAdded(messagesBundle);
- }
- }
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof MessagesBundleGroup)) {
+ return false;
+ }
+ MessagesBundleGroup messagesBundleGroup = (MessagesBundleGroup) obj;
+ return equals(localeBundles, messagesBundleGroup.localeBundles);
+ }
+
+ public final synchronized void addMessagesBundleGroupListener(
+ final IMessagesBundleGroupListener listener) {
+ addPropertyChangeListener(listener);
+ }
+
+ public final synchronized void removeMessagesBundleGroupListener(
+ final IMessagesBundleGroupListener listener) {
+ removePropertyChangeListener(listener);
+ }
+
+ public final synchronized IMessagesBundleGroupListener[] getMessagesBundleGroupListeners() {
+ // TODO find more efficient way to avoid class cast.
+ return Arrays.asList(getPropertyChangeListeners()).toArray(
+ EMPTY_GROUP_LISTENERS);
+ }
+
+ private void fireKeyAdded(String key) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.keyAdded(key);
+ }
+ }
+
+ private void fireKeyRemoved(String key) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.keyRemoved(key);
+ }
+ }
+
+ private void fireMessagesBundleAdded(MessagesBundle messagesBundle) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleAdded(messagesBundle);
+ }
+ }
+
+ private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleRemoved(messagesBundle);
+ }
+ }
- private void fireMessagesBundleRemoved(MessagesBundle messagesBundle) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleRemoved(messagesBundle);
+ /**
+ * Returns true if the supplied key is already existing in this group.
+ *
+ * @param key
+ * The key that shall be tested.
+ *
+ * @return true <=> The key is already existing.
+ */
+ @Override
+ public boolean containsKey(String key) {
+ for (Locale locale : localeBundles.keySet()) {
+ IMessagesBundle messagesBundle = localeBundles.get(locale);
+ for (String k : messagesBundle.getKeys()) {
+ if (k.equals(key)) {
+ return true;
+ } else {
+ continue;
}
+ }
}
+ return false;
+ }
+
+ /**
+ * Is the given key found in this bundle group.
+ *
+ * @param key
+ * the key to find
+ * @return <code>true</code> if the key exists in this bundle group.
+ */
+ @Override
+ public boolean isKey(String key) {
+ return keys.contains(key);
+ }
+
+ /**
+ * Gets the unique id of the bundle group. That is usually:
+ * <directory>"."<default-filename>. The default filename is without the
+ * suffix (e.g. _en, or _en_GB).
+ *
+ * @return The unique identifier for the resource bundle group
+ */
+ @Override
+ public String getResourceBundleId() {
+ return resourceBundleId;
+ }
+
+ /**
+ * Gets the name of the project, the resource bundle group is in.
+ *
+ * @return The project name
+ */
+ @Override
+ public String getProjectName() {
+ return this.projectName;
+ }
- /**
- * Returns true if the supplied key is already existing in this group.
- *
- * @param key
- * The key that shall be tested.
- *
- * @return true <=> The key is already existing.
- */
+ /**
+ * Class listening for changes in underlying messages bundle and relays them
+ * to the listeners for MessagesBundleGroup.
+ */
+ private class MessagesBundleListener implements IMessagesBundleListener {
@Override
- public boolean containsKey(String key) {
- for (Locale locale : localeBundles.keySet()) {
- IMessagesBundle messagesBundle = localeBundles.get(locale);
- for (String k : messagesBundle.getKeys()) {
- if (k.equals(key)) {
- return true;
- } else {
- continue;
- }
- }
+ public void messageAdded(MessagesBundle messagesBundle, Message message) {
+ int oldCount = keys.size();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageAdded(messagesBundle, message);
+ if (getMessages(message.getKey()).length == 1) {
+ keys.add(message.getKey());
+ firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
+ keys.size());
+ fireKeyAdded(message.getKey());
}
- return false;
+ }
}
- /**
- * Is the given key found in this bundle group.
- *
- * @param key
- * the key to find
- * @return <code>true</code> if the key exists in this bundle group.
- */
@Override
- public boolean isKey(String key) {
- return keys.contains(key);
+ public void messageRemoved(MessagesBundle messagesBundle,
+ Message message) {
+ int oldCount = keys.size();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageRemoved(messagesBundle, message);
+ int keyMessagesCount = getMessages(message.getKey()).length;
+ if (keyMessagesCount == 0 && keys.contains(message.getKey())) {
+ keys.remove(message.getKey());
+ firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
+ keys.size());
+ fireKeyRemoved(message.getKey());
+ }
+ }
}
- /**
- * Gets the unique id of the bundle group. That is usually: <directory>"."<default-filename>.
- * The default filename is without the suffix (e.g. _en, or _en_GB).
- * @return The unique identifier for the resource bundle group
- */
@Override
- public String getResourceBundleId() {
- return resourceBundleId;
+ public void messageChanged(MessagesBundle messagesBundle,
+ PropertyChangeEvent changeEvent) {
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messageChanged(messagesBundle, changeEvent);
+ }
}
- /**
- * Gets the name of the project, the resource bundle group is in.
- * @return The project name
- */
+ // MessagesBundle property changes:
@Override
- public String getProjectName() {
- return this.projectName;
- }
-
- /**
- * Class listening for changes in underlying messages bundle and relays them
- * to the listeners for MessagesBundleGroup.
- */
- private class MessagesBundleListener implements IMessagesBundleListener {
- @Override
- public void messageAdded(MessagesBundle messagesBundle, Message message) {
- int oldCount = keys.size();
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageAdded(messagesBundle, message);
- if (getMessages(message.getKey()).length == 1) {
- keys.add(message.getKey());
- firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
- keys.size());
- fireKeyAdded(message.getKey());
- }
- }
- }
-
- @Override
- public void messageRemoved(MessagesBundle messagesBundle,
- Message message) {
- int oldCount = keys.size();
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageRemoved(messagesBundle, message);
- int keyMessagesCount = getMessages(message.getKey()).length;
- if (keyMessagesCount == 0 && keys.contains(message.getKey())) {
- keys.remove(message.getKey());
- firePropertyChange(PROPERTY_KEY_COUNT, oldCount,
- keys.size());
- fireKeyRemoved(message.getKey());
- }
- }
- }
-
- @Override
- public void messageChanged(MessagesBundle messagesBundle,
- PropertyChangeEvent changeEvent) {
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messageChanged(messagesBundle, changeEvent);
- }
- }
-
- // MessagesBundle property changes:
- @Override
- public void propertyChange(PropertyChangeEvent evt) {
- MessagesBundle bundle = (MessagesBundle) evt.getSource();
- IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
- for (int i = 0; i < listeners.length; i++) {
- IMessagesBundleGroupListener listener = listeners[i];
- listener.messagesBundleChanged(bundle, evt);
- }
- }
+ public void propertyChange(PropertyChangeEvent evt) {
+ MessagesBundle bundle = (MessagesBundle) evt.getSource();
+ IMessagesBundleGroupListener[] listeners = getMessagesBundleGroupListeners();
+ for (int i = 0; i < listeners.length; i++) {
+ IMessagesBundleGroupListener listener = listeners[i];
+ listener.messagesBundleChanged(bundle, evt);
+ }
}
+ }
- /**
- * @return <code>true</code> if the bundle group has {@link PropertiesFileGroupStrategy} as strategy,
- * else <code>false</code>. This is the case, when only TapiJI edits the resource bundles and no
- * have been opened.
- */
- @Override
- public boolean hasPropertiesFileGroupStrategy() {
- return groupStrategy instanceof PropertiesFileGroupStrategy;
- }
+ /**
+ * @return <code>true</code> if the bundle group has
+ * {@link PropertiesFileGroupStrategy} as strategy, else
+ * <code>false</code>. This is the case, when only TapiJI edits the
+ * resource bundles and no have been opened.
+ */
+ @Override
+ public boolean hasPropertiesFileGroupStrategy() {
+ return groupStrategy instanceof PropertiesFileGroupStrategy;
+ }
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
index d1c760c6..892b8aa8 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
@@ -12,6 +12,7 @@
package org.eclipse.babel.core.message.manager;
+import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
@@ -94,7 +95,11 @@ private boolean isResourceBundleFile(IResource file) {
private List<CheckItem> getBlacklistItems() {
IConfiguration configuration = ConfigurationManager.getInstance()
.getConfiguration();
- return convertStringToList(configuration.getNonRbPattern());
+ if (configuration != null) {
+ return convertStringToList(configuration.getNonRbPattern());
+ } else {
+ return new ArrayList<CheckItem>();
+ }
}
private static final String DELIMITER = ";";
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
index 2a2f8db4..c8c5b147 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/strategy/PropertiesFileGroupStrategy.java
@@ -31,20 +31,19 @@
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
-
/**
* MessagesBundleGroup strategy for standard Java properties file structure.
* That is, all *.properties files of the same base name within the same
- * directory. This implementation works on files outside the Eclipse
- * workspace.
+ * directory. This implementation works on files outside the Eclipse workspace.
+ *
* @author Pascal Essiembre
*/
-public class PropertiesFileGroupStrategy implements IMessagesBundleGroupStrategy {
+public class PropertiesFileGroupStrategy implements
+ IMessagesBundleGroupStrategy {
/** Empty bundle array. */
- private static final MessagesBundle[] EMPTY_MESSAGES =
- new MessagesBundle[] {};
-
+ private static final MessagesBundle[] EMPTY_MESSAGES = new MessagesBundle[] {};
+
/** File being open, triggering the creation of a bundle group. */
private File file;
/** MessagesBundle group base name. */
@@ -57,153 +56,153 @@ public class PropertiesFileGroupStrategy implements IMessagesBundleGroupStrategy
private final IPropertiesSerializerConfig serializerConfig;
/** Properties file deserializer configuration. */
private final IPropertiesDeserializerConfig deserializerConfig;
-
-
+
/**
* Constructor.
- * @param file file from which to derive the group
+ *
+ * @param file
+ * file from which to derive the group
*/
- public PropertiesFileGroupStrategy(
- File file,
- IPropertiesSerializerConfig serializerConfig,
- IPropertiesDeserializerConfig deserializerConfig) {
- super();
- this.serializerConfig = serializerConfig;
- this.deserializerConfig = deserializerConfig;
- this.file = file;
- this.fileExtension = file.getName().replaceFirst(
- "(.*\\.)(.*)", "$2"); //$NON-NLS-1$ //$NON-NLS-2$
-
- String patternCore =
- "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
- + fileExtension + ")$"; //$NON-NLS-1$
-
- // Compute and cache name
- String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$
- this.baseName = file.getName().replaceFirst(
- namePattern, "$1"); //$NON-NLS-1$
-
- // File matching pattern
- this.fileMatchPattern =
- "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$
+ public PropertiesFileGroupStrategy(File file,
+ IPropertiesSerializerConfig serializerConfig,
+ IPropertiesDeserializerConfig deserializerConfig) {
+ super();
+ this.serializerConfig = serializerConfig;
+ this.deserializerConfig = deserializerConfig;
+ this.file = file;
+ this.fileExtension = file.getName().replaceFirst("(.*\\.)(.*)", "$2"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ String patternCore = "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ + fileExtension + ")$"; //$NON-NLS-1$
+
+ // Compute and cache name
+ String namePattern = "^(.*?)" + patternCore; //$NON-NLS-1$
+ this.baseName = file.getName().replaceFirst(namePattern, "$1"); //$NON-NLS-1$
+
+ // File matching pattern
+ this.fileMatchPattern = "^(" + baseName + ")" + patternCore; //$NON-NLS-1$//$NON-NLS-2$
}
/**
* @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy
- * #getMessagesBundleGroupName()
+ * #getMessagesBundleGroupName()
*/
public String createMessagesBundleGroupName() {
- return baseName + "[...]." + fileExtension; //$NON-NLS-1$
+ return baseName + "[...]." + fileExtension; //$NON-NLS-1$
}
/**
* @see org.eclipse.babel.core.bundle.IMessagesBundleGroupStrategy
- * #loadMessagesBundles()
+ * #loadMessagesBundles()
*/
public MessagesBundle[] loadMessagesBundles() throws MessageException {
- File[] resources = null;
- File parentDir = file.getParentFile();
- if (parentDir != null) {
- resources = parentDir.listFiles();
- }
- Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
- if (resources != null) {
- for (int i = 0; i < resources.length; i++) {
- File resource = resources[i];
- String resourceName = resource.getName();
- if (resource.isFile()
- && resourceName.matches(fileMatchPattern)) {
- // Build local title
- String localeText = resourceName.replaceFirst(
- fileMatchPattern, "$2"); //$NON-NLS-1$
- Locale locale = BabelUtils.parseLocale(localeText);
- bundles.add(createBundle(locale, resource));
- }
- }
- }
- return bundles.toArray(EMPTY_MESSAGES);
+ File[] resources = null;
+ File parentDir = file.getParentFile();
+ if (parentDir != null) {
+ resources = parentDir.listFiles();
+ }
+ Collection<MessagesBundle> bundles = new ArrayList<MessagesBundle>();
+ if (resources != null) {
+ for (int i = 0; i < resources.length; i++) {
+ File resource = resources[i];
+ String resourceName = resource.getName();
+ if (resource.isFile() && resourceName.matches(fileMatchPattern)) {
+ // Build local title
+ String localeText = resourceName.replaceFirst(
+ fileMatchPattern, "$2"); //$NON-NLS-1$
+ Locale locale = BabelUtils.parseLocale(localeText);
+ bundles.add(createBundle(locale, resource));
+ }
+ }
+ }
+ return bundles.toArray(EMPTY_MESSAGES);
}
/**
* @see org.eclipse.babel.core.bundle.IBundleGroupStrategy
- * #createBundle(java.util.Locale)
+ * #createBundle(java.util.Locale)
*/
public MessagesBundle createMessagesBundle(Locale locale) {
- // TODO Implement me (code exists in SourceForge version)
- return null;
+ // TODO Implement me (code exists in SourceForge version)
+ return null;
}
-
+
/**
* Creates a resource bundle for an existing resource.
- * @param locale locale for which to create a bundle
- * @param resource resource used to create bundle
+ *
+ * @param locale
+ * locale for which to create a bundle
+ * @param resource
+ * resource used to create bundle
* @return an initialized bundle
*/
protected MessagesBundle createBundle(Locale locale, File resource)
- throws MessageException {
- try {
- //TODO have the text de/serializer tied to Eclipse preferences,
- //singleton per project, and listening for changes
- return new MessagesBundle(new PropertiesFileResource(
- locale,
- new PropertiesSerializer(serializerConfig),
- new PropertiesDeserializer(deserializerConfig),
- resource));
- } catch (FileNotFoundException e) {
- throw new MessageException(
- "Cannot create bundle for locale " //$NON-NLS-1$
- + locale + " and resource " + resource, e); //$NON-NLS-1$
- }
+ throws MessageException {
+ try {
+ // TODO have the text de/serializer tied to Eclipse preferences,
+ // singleton per project, and listening for changes
+ return new MessagesBundle(new PropertiesFileResource(locale,
+ new PropertiesSerializer(serializerConfig),
+ new PropertiesDeserializer(deserializerConfig), resource));
+ } catch (FileNotFoundException e) {
+ throw new MessageException("Cannot create bundle for locale " //$NON-NLS-1$
+ + locale + " and resource " + resource, e); //$NON-NLS-1$
+ }
}
-
+
public String createMessagesBundleId() {
- String path = file.getAbsolutePath();
- int index = path.indexOf("src");
- String pathBeforeSrc = path.substring(0, index - 1);
- int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
- String projectName = path.substring(lastIndexOf + 1, index - 1);
- String relativeFilePath = path.substring(index, path.length());
-
- IFile f = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName).getFile(relativeFilePath);
-
- return NameUtils.getResourceBundleId(f);
+ String path = file.getAbsolutePath();
+ int index = path.indexOf("src");
+ String pathBeforeSrc = path.substring(0, index - 1);
+ int lastIndexOf = pathBeforeSrc.lastIndexOf(File.separatorChar);
+ String projectName = path.substring(lastIndexOf + 1, index - 1);
+ String relativeFilePath = path.substring(index, path.length());
+
+ IFile f = ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(projectName).getFile(relativeFilePath);
+
+ return NameUtils.getResourceBundleId(f);
}
-
+
public String getProjectName() {
- IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation();
- IPath fullPath = null;
- if (this.file.getAbsolutePath().contains(path.toOSString())) {
- fullPath = new Path(this.file.getAbsolutePath());
- } else {
- fullPath = new Path(path.toOSString() + this.file.getAbsolutePath());
- }
-
- IFile file = ResourcesPlugin
- .getWorkspace()
- .getRoot()
- .getFileForLocation(fullPath);
-
- return ResourcesPlugin.getWorkspace().getRoot().getProject(file.getFullPath().segments()[0]).getName();
+ IPath path = ResourcesPlugin.getWorkspace().getRoot().getLocation();
+ IPath fullPath = null;
+ if (this.file.getAbsolutePath().contains(path.toOSString())) {
+ fullPath = new Path(this.file.getAbsolutePath());
+ } else {
+ fullPath = new Path(path.toOSString() + this.file.getAbsolutePath());
+ }
+
+ IFile file = ResourcesPlugin.getWorkspace().getRoot()
+ .getFileForLocation(fullPath);
+
+ if (file != null) {
+ return ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(file.getFullPath().segments()[0]).getName();
+ } else {
+ return null;
+ }
+
}
-
-// public static String getResourceBundleId (IResource resource) {
-// String packageFragment = "";
-//
-// IJavaElement propertyFile = JavaCore.create(resource.getParent());
-// if (propertyFile != null && propertyFile instanceof IPackageFragment)
-// packageFragment = ((IPackageFragment) propertyFile).getElementName();
-//
-// return (packageFragment.length() > 0 ? packageFragment + "." : "") +
-// getResourceBundleName(resource);
-// }
-//
-// public static String getResourceBundleName(IResource res) {
-// String name = res.getName();
-// String regex = "^(.*?)" //$NON-NLS-1$
-// + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
-// + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
-// + res.getFileExtension() + ")$"; //$NON-NLS-1$
-// return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
-// }
+
+ // public static String getResourceBundleId (IResource resource) {
+ // String packageFragment = "";
+ //
+ // IJavaElement propertyFile = JavaCore.create(resource.getParent());
+ // if (propertyFile != null && propertyFile instanceof IPackageFragment)
+ // packageFragment = ((IPackageFragment) propertyFile).getElementName();
+ //
+ // return (packageFragment.length() > 0 ? packageFragment + "." : "") +
+ // getResourceBundleName(resource);
+ // }
+ //
+ // public static String getResourceBundleName(IResource res) {
+ // String name = res.getName();
+ // String regex = "^(.*?)" //$NON-NLS-1$
+ // + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ // + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ // + res.getFileExtension() + ")$"; //$NON-NLS-1$
+ // return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
+ // }
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
index 887626f7..cd4a9d88 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
@@ -1,290 +1,245 @@
-/*
- * Copyright (C) 2007 Uwe Voigt
+/*******************************************************************************
+ * Copyright (c) 2012 Stefan Reiterer.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
*
- * This file is part of Essiembre ResourceBundle Editor.
- *
- * Essiembre ResourceBundle Editor is free software; you can redistribute it
- * and/or modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * Essiembre ResourceBundle Editor is distributed in the hope that it will be
- * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Essiembre ResourceBundle Editor; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
- * Boston, MA 02111-1307 USA
- */
+ * Contributors:
+ * Stefan Reiterer - initial API and implementation
+ ******************************************************************************/
+
package org.eclipse.babel.core.util;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
-import java.util.StringTokenizer;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.osgi.framework.Constants;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.osgi.service.resolver.BundleDescription;
+import org.eclipse.osgi.service.resolver.HostSpecification;
+import org.eclipse.pde.core.plugin.IFragmentModel;
+import org.eclipse.pde.core.plugin.IPluginBase;
+import org.eclipse.pde.core.plugin.IPluginModelBase;
+import org.eclipse.pde.core.plugin.PluginRegistry;
-/**
- * A class that helps to find fragment and plugin projects.
- *
- * @author Uwe Voigt (http://sourceforge.net/users/uwe_ewald/)
- */
public class PDEUtils {
-
- /** Bundle manifest name */
- public static final String OSGI_BUNDLE_MANIFEST = "META-INF/MANIFEST.MF"; //$NON-NLS-1$
- /** Plugin manifest name */
- public static final String PLUGIN_MANIFEST = "plugin.xml"; //$NON-NLS-1$
- /** Fragment manifest name */
- public static final String FRAGMENT_MANIFEST = "fragment.xml"; //$NON-NLS-1$
- /**
- * Returns the plugin-id of the project if it is a plugin project. Else
- * null is returned.
+ // The same as PDE.PLUGIN_NATURE, because the PDE provided constant is not accessible (internal class)
+ private static final String PLUGIN_NATURE = "org.eclipse.pde.PluginNature";
+
+ /**
+ * Get the project's plug-in Id if the given project is an eclipse plug-in.
*
- * @param project the project
- * @return the plugin-id or null
+ * @param project the workspace project.
+ * @return the project's plug-in Id. Null if the project is no plug-in project.
*/
public static String getPluginId(IProject project) {
- if (project == null)
+
+ if (project == null || !isPluginProject(project)) {
+ return null;
+ }
+
+ IPluginModelBase pluginModelBase = PluginRegistry.findModel(project);
+
+ if (pluginModelBase == null) {
+ // plugin not found in registry
return null;
- IResource manifest = project.findMember(OSGI_BUNDLE_MANIFEST);
- String id = getManifestEntryValue(manifest, Constants.BUNDLE_SYMBOLICNAME);
- if (id != null)
- return id;
- manifest = project.findMember(PLUGIN_MANIFEST);
- if (manifest == null)
- manifest = project.findMember(FRAGMENT_MANIFEST);
- if (manifest instanceof IFile) {
- InputStream in = null;
- try {
- DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- in = ((IFile) manifest).getContents();
- Document document = builder.parse(in);
- Node node = getXMLElement(document, "plugin"); //$NON-NLS-1$
- if (node == null)
- node = getXMLElement(document, "fragment"); //$NON-NLS-1$
- if (node != null)
- node = node.getAttributes().getNamedItem("id"); //$NON-NLS-1$
- if (node != null)
- return node.getNodeValue();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (in != null)
- in.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- return null;
+ }
+
+ IPluginBase pluginBase = pluginModelBase.getPluginBase();
+
+ return pluginBase.getId();
}
/**
- * Returns all project containing plugin/fragment of the specified
- * project. If the specified project itself is a fragment, then only this is returned.
- *
- * @param pluginProject the plugin project
- * @return the all project containing a fragment or null if none
- */
- public static IProject[] lookupFragment(IProject pluginProject) {
- List<IProject> fragmentIds = new ArrayList<IProject>();
-
- String pluginId = PDEUtils.getPluginId(pluginProject);
- if (pluginId == null)
+ * Returns all project containing plugin/fragment of the specified project.
+ * If the specified project itself is a fragment, then only this is
+ * returned.
+ *
+ * @param pluginProject
+ * the plugin project
+ * @return the all project containing a fragment or null if none
+ */
+ public static IProject[] lookupFragment(IProject pluginProject) {
+ if (isFragment(pluginProject) && pluginProject.isOpen()) {
+ return new IProject[] {pluginProject};
+ }
+
+ IProject[] workspaceProjects = pluginProject.getWorkspace().getRoot().getProjects();
+ String hostPluginId = getPluginId(pluginProject);
+
+ if (hostPluginId == null) {
+ // project is not a plugin project
return null;
- String fragmentId = getFragmentId(pluginProject, getPluginId(getFragmentHost(pluginProject)));
- if (fragmentId != null){
- fragmentIds.add(pluginProject);
- return fragmentIds.toArray(new IProject[0]);
}
- IProject[] projects = pluginProject.getWorkspace().getRoot().getProjects();
- for (int i = 0; i < projects.length; i++) {
- IProject project = projects[i];
- if (!project.isOpen())
+ List<IProject> fragmentProjects = new ArrayList<IProject>();
+ for (IProject project : workspaceProjects) {
+ if (!project.isOpen() || getFragmentId(project, hostPluginId) == null) {
+ // project is not open or it is no fragment where given project is the host project.
continue;
- if (getFragmentId(project, pluginId) == null)
- continue;
- fragmentIds.add(project);
+ }
+ fragmentProjects.add(project);
}
-
- if (fragmentIds.size() > 0) return fragmentIds.toArray(new IProject[0]);
- else return null;
- }
- public static boolean isFragment(IProject pluginProject){
- String pluginId = PDEUtils.getPluginId(pluginProject);
- if (pluginId == null)
+ if (fragmentProjects.isEmpty()) {
+ return null;
+ }
+
+ return fragmentProjects.toArray(new IProject[0]);
+ }
+
+ /**
+ * Check if the given plug-in project is a fragment.
+ *
+ * @param pluginProject the plug-in project in the workspace.
+ * @return true if it is a fragment, otherwise false.
+ */
+ public static boolean isFragment(IProject pluginProject) {
+ if (pluginProject == null) {
return false;
- String fragmentId = getFragmentId(pluginProject, getPluginId(getFragmentHost(pluginProject)));
- if (fragmentId != null)
- return true;
- else
+ }
+
+ IPluginModelBase pModel = PluginRegistry.findModel(pluginProject);
+
+ if (pModel == null) {
+ // this project is not a plugin/fragment
return false;
- }
-
- public static List<IProject> getFragments(IProject hostProject){
- List<IProject> fragmentIds = new ArrayList<IProject>();
-
- String pluginId = PDEUtils.getPluginId(hostProject);
- IProject[] projects = hostProject.getWorkspace().getRoot().getProjects();
-
- for (int i = 0; i < projects.length; i++) {
- IProject project = projects[i];
- if (!project.isOpen())
- continue;
- if (getFragmentId(project, pluginId) == null)
- continue;
- fragmentIds.add(project);
}
-
- return fragmentIds;
- }
-
- /**
+
+ return pModel.isFragmentModel();
+ }
+
+ /**
+ * Get all fragments for the given host project.
+ *
+ * @param hostProject the host plug-in project in the workspace.
+ * @return a list of all fragment projects for the given host project which are in the same workspace as the host project.
+ */
+ public static List<IProject> getFragments(IProject hostProject) {
+ // Check preconditions
+ String hostId = getPluginId(hostProject);
+ if (hostProject == null || hostId == null) {
+ // no valid host project given.
+ return Collections.emptyList();
+ }
+
+ // Get the fragments of the host project
+ IPluginModelBase pModelBase = PluginRegistry.findModel(hostProject);
+ BundleDescription desc = pModelBase.getBundleDescription();
+
+ ArrayList<IPluginModelBase> fragmentModels = new ArrayList<IPluginModelBase>();
+ if (desc == null) {
+ // There is no bundle description for the host project
+ return Collections.emptyList();
+ }
+
+ BundleDescription[] f = desc.getFragments();
+ for (BundleDescription candidateDesc : f) {
+ IPluginModelBase candidate = PluginRegistry.findModel(candidateDesc);
+ if (candidate instanceof IFragmentModel) {
+ fragmentModels.add(candidate);
+ }
+ }
+
+ // Get the fragment project which is in the current workspace
+ ArrayList<IProject> fragments = getFragmentsAsWorkspaceProjects(hostProject, fragmentModels);
+
+ return fragments;
+ }
+
+ /**
* Returns the fragment-id of the project if it is a fragment project with
* the specified host plugin id as host. Else null is returned.
*
- * @param project the project
- * @param hostPluginId the host plugin id
+ * @param project
+ * the project
+ * @param hostPluginId
+ * the host plugin id
* @return the plugin-id or null
*/
- public static String getFragmentId(IProject project, String hostPluginId) {
- IResource manifest = project.findMember(FRAGMENT_MANIFEST);
- Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$
- if (fragmentNode != null) {
- Node hostNode = fragmentNode.getAttributes().getNamedItem("plugin-id"); //$NON-NLS-1$
- if (hostNode != null && hostNode.getNodeValue().equals(hostPluginId)) {
- Node idNode = fragmentNode.getAttributes().getNamedItem("id"); //$NON-NLS-1$
- if (idNode != null)
- return idNode.getNodeValue();
- }
+ public static String getFragmentId(IProject project, String hostPluginId) {
+ if (!isFragment(project) || hostPluginId == null) {
+ return null;
}
- manifest = project.findMember(OSGI_BUNDLE_MANIFEST);
- String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST);
- if (hostId != null && hostId.equals(hostPluginId))
- return getManifestEntryValue(manifest, Constants.BUNDLE_SYMBOLICNAME);
- return null;
- }
-
- /**
- * Returns the host plugin project of the specified project if it contains a fragment.
- *
- * @param fragment the fragment project
- * @return the host plugin project or null
- */
- public static IProject getFragmentHost(IProject fragment) {
- IResource manifest = fragment.findMember(FRAGMENT_MANIFEST);
- Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$
- if (fragmentNode != null) {
- Node hostNode = fragmentNode.getAttributes().getNamedItem("plugin-id"); //$NON-NLS-1$
- if (hostNode != null)
- return fragment.getWorkspace().getRoot().getProject(hostNode.getNodeValue());
+
+ IPluginModelBase pluginModelBase = PluginRegistry.findModel(project);
+ if (pluginModelBase instanceof IFragmentModel) {
+ IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase;
+ BundleDescription description = fragmentModel.getBundleDescription();
+ HostSpecification hostSpecification = description.getHost();
+
+ if (hostPluginId.equals(hostSpecification.getName())) {
+ return getPluginId(project);
+ }
}
- manifest = fragment.findMember(OSGI_BUNDLE_MANIFEST);
- String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST);
- if (hostId != null)
- return fragment.getWorkspace().getRoot().getProject(hostId);
return null;
}
/**
- * Returns the file content as UTF8 string.
+ * Returns the host plugin project of the specified project if it contains a
+ * fragment.
*
- * @param file
- * @param charset
- * @return
+ * @param fragment
+ * the fragment project
+ * @return the host plugin project or null
*/
- public static String getFileContent(IFile file, String charset) {
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- InputStream in = null;
- try {
- in = file.getContents(true);
- byte[] buf = new byte[8000];
- for (int count; (count = in.read(buf)) != -1;)
- outputStream.write(buf, 0, count);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException ignore) {
- }
- }
- }
- try {
- return outputStream.toString(charset);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- return outputStream.toString();
+ public static IProject getFragmentHost(IProject fragment) {
+ if (!isFragment(fragment)) {
+ return null;
+ }
+
+ IPluginModelBase pluginModelBase = PluginRegistry.findModel(fragment);
+ if (pluginModelBase instanceof IFragmentModel) {
+ IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase;
+ BundleDescription description = fragmentModel.getBundleDescription();
+ HostSpecification hostSpecification = description.getHost();
+
+ IPluginModelBase hostProject = PluginRegistry.findModel(hostSpecification.getName());
+ IProject[] projects = fragment.getWorkspace().getRoot().getProjects();
+ ArrayList<IProject> hostProjects = getPluginProjects(Arrays.asList(hostProject), projects);
+
+ if (hostProjects.size() != 1) {
+ // hostproject not in workspace
+ return null;
+ } else {
+ return hostProjects.get(0);
+ }
}
+
+ return null;
}
- private static String getManifestEntryValue(IResource manifest, String entryKey) {
- if (manifest instanceof IFile) {
- String content = getFileContent((IFile) manifest, "UTF8"); //$NON-NLS-1$
- int index = content.indexOf(entryKey);
- if (index != -1) {
- StringTokenizer st = new StringTokenizer(content.substring(index
- + entryKey.length()), ";:\r\n"); //$NON-NLS-1$
- return st.nextToken().trim();
- }
- }
- return null;
- }
+ private static ArrayList<IProject> getFragmentsAsWorkspaceProjects(IProject hostProject, ArrayList<IPluginModelBase> fragmentModels) {
+ IProject[] projects = hostProject.getWorkspace().getRoot().getProjects();
+
+ ArrayList<IProject> fragments = getPluginProjects(fragmentModels, projects);
+
+ return fragments;
+ }
- private static Document getXMLDocument(IResource resource) {
- if (!(resource instanceof IFile))
- return null;
- InputStream in = null;
- try {
- DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- in = ((IFile) resource).getContents();
- return builder.parse(in);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- } finally {
- try {
- if (in != null)
- in.close();
- } catch (Exception e) {
- e.printStackTrace();
+ private static ArrayList<IProject> getPluginProjects(List<IPluginModelBase> fragmentModels, IProject[] projects) {
+ ArrayList<IProject> fragments = new ArrayList<IProject>();
+ for (IProject project : projects) {
+ IPluginModelBase pModel = PluginRegistry.findModel(project);
+
+ if (fragmentModels.contains(pModel)) {
+ fragments.add(project);
}
}
- }
-
- private static Node getXMLElement(Document document, String name) {
- if (document == null)
- return null;
- NodeList list = document.getChildNodes();
- for (int i = 0; i < list.getLength(); i++) {
- Node node = list.item(i);
- if (node.getNodeType() != Node.ELEMENT_NODE)
- continue;
- if (name.equals(node.getNodeName()))
- return node;
+
+ return fragments;
+ }
+
+ private static boolean isPluginProject(IProject project) {
+ try {
+ return project.hasNature(PLUGIN_NATURE);
+ } catch (CoreException ce) {
+ //Logger.logError(ce);
}
- return null;
- }
-
-}
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java
index b0ead893..f0710190 100644
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java
+++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java
@@ -10,10 +10,11 @@
******************************************************************************/
package org.eclipse.babel.editor.api;
+import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer;
import org.eclipse.babel.core.message.checks.proximity.LevenshteinDistanceAnalyzer;
/**
- * Provides the {@link ILevenshteinDistanceAnalyzer}
+ * Provides the {@link IProximityAnalyzer}
* <br><br>
*
* @author Alexej Strelzow
@@ -23,7 +24,7 @@ public class AnalyzerFactory {
/**
* @return An instance of the {@link LevenshteinDistanceAnalyzer}
*/
- public static ILevenshteinDistanceAnalyzer getLevenshteinDistanceAnalyzer () {
- return (ILevenshteinDistanceAnalyzer) LevenshteinDistanceAnalyzer.getInstance();
+ public static IProximityAnalyzer getLevenshteinDistanceAnalyzer () {
+ return (IProximityAnalyzer) LevenshteinDistanceAnalyzer.getInstance();
}
}
diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java
deleted file mode 100644
index fcf0ff6c..00000000
--- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2012 Martin Reiterer.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Martin Reiterer - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.editor.api;
-
-public interface ILevenshteinDistanceAnalyzer {
-
- double analyse(Object value, Object pattern);
-
-}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
index 41af9dce..aee3c114 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
@@ -12,15 +12,15 @@
import java.util.Locale;
+import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer;
import org.eclipse.babel.editor.api.AnalyzerFactory;
-import org.eclipse.babel.editor.api.ILevenshteinDistanceAnalyzer;
import org.eclipse.babel.editor.api.IValuedKeyTreeNode;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
public class FuzzyMatcher extends ExactMatcher {
- protected ILevenshteinDistanceAnalyzer lvda;
+ protected IProximityAnalyzer lvda;
protected float minimumSimilarity = 0.75f;
public FuzzyMatcher(StructuredViewer viewer) {
diff --git a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF
index 3f1023cd..d9209fe7 100644
--- a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF
+++ b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF
@@ -12,7 +12,7 @@ Require-Bundle: org.eclipse.core.runtime,
org.eclipse.ui.ide;bundle-version="3.7.0",
org.eclipse.ui;bundle-version="3.7.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Import-Package: org.apache.commons.io,
+Import-Package:
org.eclipse.core.filebuffers,
org.eclipse.core.resources,
org.eclipse.jdt.core,
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
index 733b4f78..8bfd10a5 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
@@ -15,30 +15,30 @@
public class Logger {
- public static void logInfo(String message) {
- log(IStatus.INFO, IStatus.OK, message, null);
- }
-
- public static void logError(Throwable exception) {
- logError("Unexpected Exception", exception);
- }
-
- public static void logError(String message, Throwable exception) {
- log(IStatus.ERROR, IStatus.OK, message, exception);
- }
-
- public static void log(int severity, int code, String message,
- Throwable exception) {
- log(createStatus(severity, code, message, exception));
- }
-
- public static IStatus createStatus(int severity, int code, String message,
- Throwable exception) {
- return new Status(severity, Activator.PLUGIN_ID, code, message,
- exception);
- }
-
- public static void log(IStatus status) {
- Activator.getDefault().getLog().log(status);
- }
+ public static void logInfo(String message) {
+ log(IStatus.INFO, IStatus.OK, message, null);
+ }
+
+ public static void logError(Throwable exception) {
+ logError("Unexpected Exception", exception);
+ }
+
+ public static void logError(String message, Throwable exception) {
+ log(IStatus.ERROR, IStatus.OK, message, exception);
+ }
+
+ public static void log(int severity, int code, String message,
+ Throwable exception) {
+ log(createStatus(severity, code, message, exception));
+ }
+
+ public static IStatus createStatus(int severity, int code, String message,
+ Throwable exception) {
+ return new Status(severity, Activator.PLUGIN_ID, code, message,
+ exception);
+ }
+
+ public static void log(IStatus status) {
+ Activator.getDefault().getLog().log(status);
+ }
}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
index 208bd033..491d0872 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
@@ -11,13 +11,13 @@
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.util;
+import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
-import java.io.IOException;
+import java.io.FileReader;
import org.eclipse.babel.tapiji.tools.core.Activator;
import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.core.internal.resources.ResourceException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
@@ -25,46 +25,57 @@
public class FileUtils {
- public static String readFile(IResource resource) {
- return readFileAsString(resource.getRawLocation().toFile());
- }
+ public static String readFile(IResource resource) {
+ return readFileAsString(resource.getRawLocation().toFile());
+ }
- protected static String readFileAsString(File filePath) {
- String content = "";
+ protected static String readFileAsString(File filePath) {
+ String content = "";
- try {
- content = org.apache.commons.io.FileUtils
- .readFileToString(filePath);
- } catch (IOException e) {
- Logger.logError(e);
- }
+ if (!filePath.exists())
+ return content;
+ try {
+ BufferedReader fileReader = new BufferedReader(new FileReader(
+ filePath));
+ String line = "";
- return content;
- }
+ while ((line = fileReader.readLine()) != null) {
+ content += line + "\n";
+ }
- public static File getRBManagerStateFile() {
- return Activator.getDefault().getStateLocation()
- .append("internationalization.xml").toFile();
+ // close filereader
+ fileReader.close();
+ } catch (Exception e) {
+ // TODO log error output
+ Logger.logError(e);
}
- /**
- * Don't use that -> causes {@link ResourceException} -> because File out of
- * sync
- *
- * @param file
- * @param editorContent
- * @throws CoreException
- * @throws OperationCanceledException
- */
- public synchronized void saveTextFile(IFile file, String editorContent)
- throws CoreException, OperationCanceledException {
- try {
- file.setContents(
- new ByteArrayInputStream(editorContent.getBytes()), false,
- true, null);
- } catch (Exception e) {
- e.printStackTrace();
- }
+ return content;
+ }
+
+ public static File getRBManagerStateFile() {
+ return Activator.getDefault().getStateLocation()
+ .append("internationalization.xml").toFile();
+ }
+
+ /**
+ * Don't use that -> causes {@link ResourceException} -> because File out of
+ * sync
+ *
+ * @param file
+ * @param editorContent
+ * @throws CoreException
+ * @throws OperationCanceledException
+ */
+ public synchronized void saveTextFile(IFile file, String editorContent)
+ throws CoreException, OperationCanceledException {
+ try {
+ file.setContents(
+ new ByteArrayInputStream(editorContent.getBytes()), false,
+ true, null);
+ } catch (Exception e) {
+ e.printStackTrace();
}
+ }
}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
index 3e7e03d8..fcb60328 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
@@ -10,8 +10,8 @@
******************************************************************************/
package org.eclipselabs.tapiji.translator.views.widgets.filter;
+import org.eclipse.babel.core.message.checks.proximity.IProximityAnalyzer;
import org.eclipse.babel.editor.api.AnalyzerFactory;
-import org.eclipse.babel.editor.api.ILevenshteinDistanceAnalyzer;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipselabs.tapiji.translator.model.Term;
@@ -19,7 +19,7 @@
public class FuzzyMatcher extends ExactMatcher {
- protected ILevenshteinDistanceAnalyzer lvda;
+ protected IProximityAnalyzer lvda;
protected float minimumSimilarity = 0.75f;
public FuzzyMatcher(StructuredViewer viewer) {
|
da5ff665396d5f0cbd70b9ea8a53387c0b40cbd1
|
orientdb
|
Fixed problem with linkeset modified right after- query in remote configuration--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java
index c3c0d2514ff..2bc08a33eda 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java
@@ -101,6 +101,8 @@ public OMVRBTreePersistent<OIdentifiable, OIdentifiable> load() {
@Override
public OIdentifiable internalPut(final OIdentifiable e, final OIdentifiable v) {
+ ((OMVRBTreeRIDProvider) dataProvider).lazyUnmarshall();
+
if (e.getIdentity().isNew()) {
final ORecord<?> record = e.getRecord();
@@ -114,7 +116,6 @@ else if (newEntries.containsKey(record))
return null;
}
- ((OMVRBTreeRIDProvider) dataProvider).lazyUnmarshall();
return super.internalPut(e, null);
}
|
bfad7226bf99c488f5e5063a44cc4a5282c9344d
|
orientdb
|
Fixed issue on set password for OUser.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
index 19b54223d12..248ca2b419d 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
@@ -148,10 +148,10 @@ public String getPassword() {
}
public OUser setPassword(final String iPassword) {
- return setPasswordEncoded(encryptPassword(iPassword));
+ return setPasswordEncoded(iPassword);
}
- public OUser setPasswordEncoded(String iPassword) {
+ public OUser setPasswordEncoded(final String iPassword) {
document.field("password", iPassword);
return this;
}
@@ -164,7 +164,7 @@ public STATUSES getAccountStatus() {
return STATUSES.valueOf((String) document.field("status"));
}
- public void setAccountStatus(STATUSES accountStatus) {
+ public void setAccountStatus(final STATUSES accountStatus) {
document.field("status", accountStatus);
}
|
c1c63c500a3d0737c081b3eb5616b17767d965e6
|
hunterhacker$jdom
|
Remove duplicate TextHelper functionality. Move tests of Format to TestElement
|
p
|
https://github.com/hunterhacker/jdom
|
diff --git a/core/src/java/org/jdom2/util/TextHelper.java b/core/src/java/org/jdom2/util/TextHelper.java
deleted file mode 100644
index 0a922b678..000000000
--- a/core/src/java/org/jdom2/util/TextHelper.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*--
-
- Copyright (C) 2000-2004 Jason Hunter & Brett McLaughlin.
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
-
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions, and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions, and the disclaimer that follows
- these conditions in the documentation and/or other materials
- provided with the distribution.
-
- 3. The name "JDOM" must not be used to endorse or promote products
- derived from this software without prior written permission. For
- written permission, please contact <request_AT_jdom_DOT_org>.
-
- 4. Products derived from this software may not be called "JDOM", nor
- may "JDOM" appear in their name, without prior written permission
- from the JDOM Project Management <request_AT_jdom_DOT_org>.
-
- In addition, we request (but do not require) that you include in the
- end-user documentation provided with the redistribution and/or in the
- software itself an acknowledgement equivalent to the following:
- "This product includes software developed by the
- JDOM Project (http://www.jdom.org/)."
- Alternatively, the acknowledgment may be graphical using the logos
- available at http://www.jdom.org/images/logos.
-
- THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JDOM AUTHORS OR THE PROJECT
- 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.
-
- This software consists of voluntary contributions made by many
- individuals on behalf of the JDOM Project and was originally
- created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
- Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information
- on the JDOM Project, please see <http://www.jdom.org/>.
-
- */
-
-package org.jdom2.util;
-
-import org.jdom2.Element;
-import org.jdom2.Namespace;
-import org.jdom2.output.Format;
-
-/**
- * <p>
- * This class contains static helper methods for accessing Text content of JDOM
- * Elements.
- * </p>
- *
- * @author Alex Rosen
- * @author Rolf Lear
- */
-public class TextHelper {
-
- private TextHelper() {
- // make constructor inaccessible.
- }
-
- /**
- * <p>
- * This convenience method returns the textual content of the first child
- * element with the given name and in no Namespace, or returns an empty
- * <code>String</code> ("") if the child has no textual content. However, if
- * the child does not exist, <code>null</code> is returned.
- * </p>
- *
- * @param parent
- * the parent element
- * @param name
- * the name of the child
- * @return text content for the named child, or null if no such child exists
- * @see Element#getChild(String)
- */
- public static String getChildText(final Element parent, final String name) {
- final Element child = parent.getChild(name);
- if (child == null) {
- return null;
- }
- return child.getText();
- }
-
- /**
- * <p>
- * This convenience method returns the textual content of the first named
- * child element, or returns an empty <code>String</code> ("") if the child
- * has no textual content. However, if the child does not exist,
- * <code>null</code> is returned.
- * </p>
- *
- * @param parent
- * the parent element
- * @param name
- * the name of the child
- * @param ns
- * the namespace of the child
- * @return text content for the named child, or null if no such child exists
- * @see Element#getChild(String, Namespace)
- */
- public static String getChildText(final Element parent, final String name,
- final Namespace ns) {
- final Element child = parent.getChild(name, ns);
- if (child == null) {
- return null;
- }
- return child.getText();
- }
-
- /**
- * <p>
- * This convenience method returns the trimmed textual content of the first
- * named child element, or returns null if there's no such child. See
- * {@link Format#trimBoth(String)} for details of text trimming.
- * </p>
- *
- * @param parent
- * the parent element
- * @param name
- * the name of the child
- * @return trimmed text content for the named child, or null if no such
- * child exists
- * @see Element#getChild(String)
- */
- public static String getChildTextTrim(final Element parent,
- final String name) {
- final Element child = parent.getChild(name);
- if (child == null) {
- return null;
- }
- return Format.trimBoth(child.getText());
- }
-
- /**
- * <p>
- * This convenience method returns the trimmed textual content of the named
- * child element, or returns null if there's no such child. See
- * <code>String.trim()</code> for details of text trimming.
- * </p>
- *
- * @param parent
- * the parent element
- * @param name
- * the name of the child
- * @param ns
- * the namespace of the child
- * @return trimmed text content for the named child, or null if no such
- * child exists
- * @see Element#getChild(String, Namespace)
- */
- public static String getChildTextTrim(final Element parent,
- final String name, final Namespace ns) {
- final Element child = parent.getChild(name, ns);
- if (child == null) {
- return null;
- }
- return child.getText().trim();
- }
-
- /**
- * <p>
- * This convenience method returns the normalized textual content of the
- * named child element, or returns null if there's no such child. See
- * {@link Format#compact(String)} for details of text normalization.
- * </p>
- *
- * @param parent
- * the parent element
- * @param name
- * the name of the child
- * @return normalized text content for the named child, or null if no such
- * child exists
- * @see Element#getChild(String)
- */
- public static String getChildTextNormalize(final Element parent,
- final String name) {
- final Element child = parent.getChild(name);
- if (child == null) {
- return null;
- }
- return Format.compact(child.getText());
- }
-
- /**
- * <p>
- * This convenience method returns the normalized textual content of the
- * named child element, or returns null if there's no such child. See
- * {@link Format#compact(String)} for details of text normalization.
- * </p>
- *
- * @param parent
- * the parent element
- * @param name
- * the name of the child
- * @param ns
- * the namespace of the child
- * @return normalized text content for the named child, or null if no such
- * child exists
- * @see Element#getChild(String, Namespace)
- */
- public static String getChildTextNormalize(final Element parent,
- final String name, final Namespace ns) {
- final Element child = parent.getChild(name, ns);
- if (child == null) {
- return null;
- }
- return Format.compact(child.getText());
- }
-}
diff --git a/test/src/java/org/jdom2/test/cases/TestElement.java b/test/src/java/org/jdom2/test/cases/TestElement.java
index 60deb0e02..7a015ca2b 100644
--- a/test/src/java/org/jdom2/test/cases/TestElement.java
+++ b/test/src/java/org/jdom2/test/cases/TestElement.java
@@ -101,6 +101,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
import org.jdom2.filter.ContentFilter;
import org.jdom2.filter.ElementFilter;
import org.jdom2.filter.Filters;
+import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.test.util.UnitTestUtil;
@@ -2886,4 +2887,102 @@ private void checkAttOrder(List<Attribute> attributes, Attribute...atts) {
}
+ private String getTestString() {
+ return " this has space ";
+ }
+
+ private String getComp() {
+ return Format.compact(getTestString());
+ }
+
+ private String getTrim() {
+ return Format.trimBoth(getTestString());
+ }
+
+ private String getPlain() {
+ return getTestString();
+ }
+
+ private Namespace getNamespace() {
+ return Namespace.getNamespace("jdomtest");
+ }
+
+ public Element getTextHelperRoot() {
+ final Namespace ns = getNamespace();
+
+ final Element root = new Element("root");
+ final Element childa = new Element("child");
+ final Element childb = new Element("child", ns);
+ final Element childc = new Element("child");
+ final Element childd = new Element("child", ns);
+ final Element childe = new Element("kid");
+ final Element childf = new Element("kid", ns);
+
+ childa.setText(getTestString());
+ childb.setText(getTestString());
+ childc.setText(getTestString());
+ childd.setText(getTestString());
+ root.addContent(childa);
+ root.addContent(childb);
+ root.addContent(childc);
+ root.addContent(childd);
+ root.addContent(childe);
+ root.addContent(childf);
+
+ return root;
+ }
+
+ @Test
+ public void testGetChildTextElementString() {
+ Element root = getTextHelperRoot();
+ assertEquals(getPlain(), root.getChildText("child"));
+ assertEquals(null, root.getChildText("dummy"));
+ assertEquals("", root.getChildText("kid"));
+ }
+
+ @Test
+ public void testGetChildTextElementStringNamespace() {
+ Element root = getTextHelperRoot();
+ Namespace ns = getNamespace();
+ assertEquals(getPlain(), root.getChildText("child", ns));
+ assertEquals(null, root.getChildText("dummy", ns));
+ assertEquals("", root.getChildText("kid", ns));
+ }
+
+ @Test
+ public void testGetChildTextTrimElementString() {
+ Element root = getTextHelperRoot();
+ assertEquals(getTrim(), root.getChildTextTrim("child"));
+ assertEquals(null, root.getChildTextTrim("dummy"));
+ assertEquals("", root.getChildTextTrim("kid"));
+ }
+
+ @Test
+ public void testGetChildTextTrimElementStringNamespace() {
+ Element root = getTextHelperRoot();
+ Namespace ns = getNamespace();
+ assertEquals(getTrim(), root.getChildTextTrim("child", ns));
+ assertEquals(null, root.getChildTextTrim("dummy", ns));
+ assertEquals("", root.getChildTextTrim("kid", ns));
+ }
+
+ @Test
+ public void testGetChildTextNormalizeElementString() {
+ Element root = getTextHelperRoot();
+ assertEquals(getComp(), root.getChildTextNormalize("child"));
+ assertEquals(null, root.getChildTextNormalize("dummy"));
+ assertEquals("", root.getChildTextNormalize("kid"));
+ }
+
+ @Test
+ public void testGetChildTextNormalizeElementStringNamespace() {
+ Element root = getTextHelperRoot();
+ Namespace ns = getNamespace();
+ assertEquals(getComp(), root.getChildTextNormalize("child", ns));
+ assertEquals(null, root.getChildTextNormalize("dummy", ns));
+ assertEquals("", root.getChildTextNormalize("kid", ns));
+ }
+
+
+
}
diff --git a/test/src/java/org/jdom2/test/cases/util/TestTextHelper.java b/test/src/java/org/jdom2/test/cases/util/TestTextHelper.java
deleted file mode 100644
index 036313aa1..000000000
--- a/test/src/java/org/jdom2/test/cases/util/TestTextHelper.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.jdom2.test.cases.util;
-
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-
-import org.jdom2.Element;
-import org.jdom2.Namespace;
-import org.jdom2.output.Format;
-import org.jdom2.util.TextHelper;
-
-@SuppressWarnings("javadoc")
-public class TestTextHelper {
-
- private final Namespace ns = Namespace.getNamespace("jdomtest");
-
- private final Element root = new Element("root");
- private final Element childa = new Element("child");
- private final Element childb = new Element("child", ns);
- private final Element childc = new Element("child");
- private final Element childd = new Element("child", ns);
- private final Element childe = new Element("kid");
- private final Element childf = new Element("kid", ns);
- private final String teststr = " this has space ";
- private final String comp = Format.compact(teststr);
- private final String trim = Format.trimBoth(teststr);
- private final String plain = teststr;
-
- public TestTextHelper() {
- childa.setText(teststr);
- childb.setText(teststr);
- childc.setText(teststr);
- childd.setText(teststr);
- root.addContent(childa);
- root.addContent(childb);
- root.addContent(childc);
- root.addContent(childd);
- root.addContent(childe);
- root.addContent(childf);
- }
-
- @Test
- public void testGetChildTextElementString() {
- assertEquals(plain, TextHelper.getChildText(root, "child"));
- assertEquals(null, TextHelper.getChildText(root, "dummy"));
- assertEquals("", TextHelper.getChildText(root, "kid"));
- }
-
- @Test
- public void testGetChildTextElementStringNamespace() {
- assertEquals(plain, TextHelper.getChildText(root, "child", ns));
- assertEquals(null, TextHelper.getChildText(root, "dummy", ns));
- assertEquals("", TextHelper.getChildText(root, "kid", ns));
- }
-
- @Test
- public void testGetChildTextTrimElementString() {
- assertEquals(trim, TextHelper.getChildTextTrim(root, "child"));
- assertEquals(null, TextHelper.getChildTextTrim(root, "dummy"));
- assertEquals("", TextHelper.getChildTextTrim(root, "kid"));
- }
-
- @Test
- public void testGetChildTextTrimElementStringNamespace() {
- assertEquals(trim, TextHelper.getChildTextTrim(root, "child", ns));
- assertEquals(null, TextHelper.getChildTextTrim(root, "dummy", ns));
- assertEquals("", TextHelper.getChildTextTrim(root, "kid", ns));
- }
-
- @Test
- public void testGetChildTextNormalizeElementString() {
- assertEquals(comp, TextHelper.getChildTextNormalize(root, "child"));
- assertEquals(null, TextHelper.getChildTextNormalize(root, "dummy"));
- assertEquals("", TextHelper.getChildTextNormalize(root, "kid"));
- }
-
- @Test
- public void testGetChildTextNormalizeElementStringNamespace() {
- assertEquals(comp, TextHelper.getChildTextNormalize(root, "child", ns));
- assertEquals(null, TextHelper.getChildTextNormalize(root, "dummy", ns));
- assertEquals("", TextHelper.getChildTextNormalize(root, "kid", ns));
- }
-
-}
|
34805565ec1a5002515aa1ae544956ad5b8182fa
|
drools
|
[DROOLS-389] Improve support for @Traitable POJOs- and @Trait interfaces--
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/compiler/factmodel/traits/TraitTest.java b/drools-compiler/src/test/java/org/drools/compiler/factmodel/traits/TraitTest.java
index 0225efce84f..658bbfc1481 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/factmodel/traits/TraitTest.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/factmodel/traits/TraitTest.java
@@ -26,6 +26,7 @@
import org.drools.core.factmodel.traits.LogicalTypeInconsistencyException;
import org.drools.core.factmodel.traits.MapWrapper;
import org.drools.core.factmodel.traits.Thing;
+import org.drools.core.factmodel.traits.Trait;
import org.drools.core.factmodel.traits.TraitFactory;
import org.drools.core.factmodel.traits.TraitProxy;
import org.drools.core.factmodel.traits.TraitRegistry;
@@ -4909,4 +4910,72 @@ public void testTraitImplicitInsertionExceptionOnNonTraitable() throws Interrupt
}
+
+ @Trait
+ public static interface SomeTrait<K> extends Thing<K> {
+ public String getFoo();
+ public void setFoo( String foo );
+ }
+
+ @Test
+ public void testTraitLegacyTraitableWithLegacyTrait() {
+ final String s1 = "package org.drools.compiler.factmodel.traits;\n" +
+ "import " + TraitTest.class.getName() + ".SomeTrait; \n" +
+ "import org.drools.core.factmodel.traits.*; \n" +
+ "global java.util.List list;\n" +
+ "" +
+ "rule \"Don ItemStyle\"\n" +
+ " when\n" +
+ " then\n" +
+ " don( new StudentImpl(), SomeTrait.class );\n" +
+ "end\n";
+
+ final KnowledgeBase kbase = getKieBaseFromString(s1);
+ TraitFactory.setMode( mode, kbase );
+ ArrayList list = new ArrayList();
+
+ StatefulKnowledgeSession knowledgeSession = kbase.newStatefulKnowledgeSession();
+ knowledgeSession.setGlobal( "list", list );
+
+ knowledgeSession.fireAllRules();
+
+ assertEquals( 2, knowledgeSession.getObjects().size() );
+ }
+
+ @Test
+ public void testIsALegacyTrait() {
+ final String s1 = "package org.drools.compiler.factmodel.traits;\n" +
+ "import " + TraitTest.class.getName() + ".SomeTrait; \n" +
+ "import org.drools.core.factmodel.traits.*; \n" +
+ "global java.util.List list;\n" +
+ "" +
+ "declare trait IStudent end \n" +
+ "" +
+ "rule \"Don ItemStyle\"\n" +
+ " when\n" +
+ " then\n" +
+ " insert( new StudentImpl() );\n" +
+ " don( new Entity(), IStudent.class );\n" +
+ "end\n" +
+ "" +
+ "rule Check " +
+ " when " +
+ " $s : StudentImpl() " +
+ " $e : Entity( this isA $s ) " +
+ " then " +
+ " list.add( 1 ); " +
+ " end ";
+
+ final KnowledgeBase kbase = getKieBaseFromString(s1);
+ TraitFactory.setMode( mode, kbase );
+ ArrayList list = new ArrayList();
+
+ StatefulKnowledgeSession knowledgeSession = kbase.newStatefulKnowledgeSession();
+ knowledgeSession.setGlobal( "list", list );
+
+ knowledgeSession.fireAllRules();
+
+ assertEquals( Arrays.asList( 1 ), list );
+ }
+
}
diff --git a/drools-core/src/main/java/org/drools/core/base/evaluators/IsAEvaluatorDefinition.java b/drools-core/src/main/java/org/drools/core/base/evaluators/IsAEvaluatorDefinition.java
index afbd9839541..15b0123aec9 100644
--- a/drools-core/src/main/java/org/drools/core/base/evaluators/IsAEvaluatorDefinition.java
+++ b/drools-core/src/main/java/org/drools/core/base/evaluators/IsAEvaluatorDefinition.java
@@ -334,6 +334,10 @@ private boolean compare( Object source, Object target, InternalWorkingMemory wor
targetTraits = x.getCode( target );
} else if ( target instanceof Thing ) {
targetTraits = ((TraitableBean) ((Thing) target).getCore()).getCurrentTypeCode();
+ if ( targetTraits == null && target instanceof TraitType ) {
+ CodedHierarchy x = ((ReteooRuleBase) workingMemory.getRuleBase()).getConfiguration().getComponentFactory().getTraitRegistry().getHierarchy();
+ targetTraits = x.getCode( ((TraitType)target).getTraitName() );
+ }
} else if ( target instanceof TraitableBean ) {
targetTraits = ((TraitableBean) target).getCurrentTypeCode();
} else {
diff --git a/drools-core/src/main/java/org/drools/core/factmodel/traits/TraitFactory.java b/drools-core/src/main/java/org/drools/core/factmodel/traits/TraitFactory.java
index ad9cb783a35..5edbd2b7d52 100644
--- a/drools-core/src/main/java/org/drools/core/factmodel/traits/TraitFactory.java
+++ b/drools-core/src/main/java/org/drools/core/factmodel/traits/TraitFactory.java
@@ -226,10 +226,32 @@ private Class<T> buildProxyClass( String key, K core, Class<?> trait ) {
ClassDefinition cdef = ruleBase.getTraitRegistry().getTraitable( coreKlass.getName() );
if ( tdef == null ) {
- throw new RuntimeDroolsException( "Unable to find Trait definition for class " + trait.getName() + ". It should have been DECLARED as a trait" );
- }
+ if ( trait.getAnnotation( Trait.class ) != null ) {
+ try {
+ if ( Thing.class.isAssignableFrom( trait ) ) {
+ tdef = buildClassDefinition( trait, null );
+ } else {
+ throw new RuntimeDroolsException( "Unable to create definition for class " + trait +
+ " : trait interfaces should extend " + Thing.class.getName() + " or be DECLARED as traits explicitly" );
+ }
+ } catch ( IOException e ) {
+ throw new RuntimeDroolsException( "Unable to create definition for class " + trait + " : " + e.getMessage() );
+ }
+ ruleBase.getTraitRegistry().addTrait( tdef );
+ } else {
+ throw new RuntimeDroolsException( "Unable to find Trait definition for class " + trait.getName() + ". It should have been DECLARED as a trait" );
+ } }
if ( cdef == null ) {
- throw new RuntimeDroolsException( "Unable to find Core class definition for class " + coreKlass.getName() + ". It should have been DECLARED as a trait" );
+ if ( core.getClass().getAnnotation( Traitable.class ) != null ) {
+ try {
+ cdef = buildClassDefinition( core.getClass(), core.getClass() );
+ } catch ( IOException e ) {
+ throw new RuntimeDroolsException( "Unable to create definition for class " + coreKlass.getName() + " : " + e.getMessage() );
+ }
+ ruleBase.getTraitRegistry().addTraitable( cdef );
+ } else {
+ throw new RuntimeDroolsException( "Unable to find Core class definition for class " + coreKlass.getName() + ". It should have been DECLARED as a trait" );
+ }
}
String proxyName = getProxyName( tdef, cdef );
@@ -319,7 +341,7 @@ public synchronized CoreWrapper<K> getCoreWrapper( Class<K> coreKlazz , ClassDef
}
try {
- ruleBase.getTraitRegistry().addTraitable( buildWrapperClassDefinition( coreKlazz, wrapperClass ) );
+ ruleBase.getTraitRegistry().addTraitable( buildClassDefinition( coreKlazz, wrapperClass ) );
return wrapperClass != null ? wrapperClass.newInstance() : null;
} catch (InstantiationException e) {
return null;
@@ -331,8 +353,8 @@ public synchronized CoreWrapper<K> getCoreWrapper( Class<K> coreKlazz , ClassDef
}
- private ClassDefinition buildWrapperClassDefinition(Class<K> coreKlazz, Class<? extends CoreWrapper<K>> wrapperClass) throws IOException {
- ClassFieldInspector inspector = new ClassFieldInspector( coreKlazz );
+ private ClassDefinition buildClassDefinition(Class<?> klazz, Class<?> wrapperClass) throws IOException {
+ ClassFieldInspector inspector = new ClassFieldInspector( klazz );
Package traitPackage = ruleBase.getPackagesMap().get( pack );
if ( traitPackage == null ) {
@@ -342,14 +364,26 @@ private ClassDefinition buildWrapperClassDefinition(Class<K> coreKlazz, Class<?
}
ClassFieldAccessorStore store = traitPackage.getClassFieldAccessorStore();
- String className = coreKlazz.getName() + "Wrapper";
- String superClass = coreKlazz.getName();
- String[] interfaces = new String[] {CoreWrapper.class.getName()};
- ClassDefinition def = new ClassDefinition( className, superClass, interfaces );
- Traitable tbl = wrapperClass.getAnnotation( Traitable.class );
- def.setTraitable( true, tbl != null && tbl.logical() );
- def.setDefinedClass( wrapperClass );
+ ClassDefinition def;
+ if ( ! klazz.isInterface() ) {
+ String className = wrapperClass.getName();
+ String superClass = wrapperClass != klazz ? klazz.getName() : klazz.getSuperclass().getName();
+ String[] interfaces = new String[] {CoreWrapper.class.getName()};
+ def = new ClassDefinition( className, superClass, interfaces );
+ def.setDefinedClass( wrapperClass );
+ Traitable tbl = wrapperClass.getAnnotation( Traitable.class );
+ def.setTraitable( true, tbl != null && tbl.logical() );
+ } else {
+ String className = klazz.getName();
+ String superClass = Object.class.getName();
+ String[] interfaces = new String[ klazz.getInterfaces().length ];
+ for ( int j = 0; j < klazz.getInterfaces().length; j++ ) {
+ interfaces[ j ] = klazz.getInterfaces()[ j ].getName();
+ }
+ def = new ClassDefinition( className, superClass, interfaces );
+ def.setDefinedClass( klazz );
+ }
Map<String, Field> fields = inspector.getFieldTypesField();
for ( Field f : fields.values() ) {
if ( f != null ) {
|
8dbd55da75fb5a06077011cdec31749fe27f03dd
|
duracloud$duracloud
|
DURACLOUD-303 - Added server configuration mode of standard/advanced to the bulk services. Advanced allows for the previous functionality of choosing the number and type of server instances. Standard allows the choice of "Optimize for Cost" and "Optimize for Speed"
git-svn-id: https://svn.duraspace.org/duracloud/trunk@304 1005ed41-97cd-4a8f-848c-be5b5fe45bcb
|
p
|
https://github.com/duracloud/duracloud
|
diff --git a/duraservice/src/main/java/org/duracloud/duraservice/config/AmazonFixityServiceInfo.java b/duraservice/src/main/java/org/duracloud/duraservice/config/AmazonFixityServiceInfo.java
index 6a149b550..769006959 100644
--- a/duraservice/src/main/java/org/duracloud/duraservice/config/AmazonFixityServiceInfo.java
+++ b/duraservice/src/main/java/org/duracloud/duraservice/config/AmazonFixityServiceInfo.java
@@ -12,6 +12,7 @@
import org.duracloud.serviceconfig.user.UserConfig;
import org.duracloud.serviceconfig.user.UserConfigMode;
import org.duracloud.serviceconfig.user.UserConfigModeSet;
+import org.duracloud.storage.domain.HadoopTypes;
import org.duracloud.storage.domain.HadoopTypes.INSTANCES;
/**
@@ -20,33 +21,6 @@
*/
public class AmazonFixityServiceInfo extends AbstractServiceInfo {
- protected enum ModeType {
- SERVICE_PROVIDES_BOTH_LISTS("all-in-one-for-list",
- "Verify integrity of a Space"),
- USER_PROVIDES_ONE_OF_LISTS("compare",
- "Verify integrity from an item list");
-
- private String key;
- private String desc;
-
- private ModeType(String key, String desc) {
- this.key = key;
- this.desc = desc;
- }
-
- public String toString() {
- return getKey();
- }
-
- protected String getKey() {
- return key;
- }
-
- protected String getDesc() {
- return desc;
- }
- }
-
@Override
public ServiceInfo getServiceXml(int index, String version) {
@@ -73,13 +47,13 @@ public ServiceInfo getServiceXml(int index, String version) {
private List<UserConfigModeSet> getModeSets() {
List<UserConfigMode> modes = new ArrayList<UserConfigMode>();
- modes.add(getMode(ModeType.SERVICE_PROVIDES_BOTH_LISTS));
- modes.add(getMode(ModeType.USER_PROVIDES_ONE_OF_LISTS));
+ modes.add(getMode(ModeType.OPTIMIZE_STANDARD));
+ modes.add(getMode(ModeType.OPTIMIZE_ADVANCED));
UserConfigModeSet modeSet = new UserConfigModeSet();
modeSet.setModes(modes);
- modeSet.setDisplayName("Service Mode");
- modeSet.setName("mode");
+ modeSet.setDisplayName("Configuration");
+ modeSet.setName("optimizeMode");
List<UserConfigModeSet> modeSets = new ArrayList<UserConfigModeSet>();
modeSets.add(modeSet);
@@ -87,64 +61,156 @@ private List<UserConfigModeSet> getModeSets() {
}
private UserConfigMode getMode(ModeType modeType) {
- List<UserConfig> userConfigs = new ArrayList<UserConfig>();
- userConfigs.add(getTargetSpace());
-
+ List<UserConfig> userConfigs = getDefaultUserConfigs();
switch (modeType) {
- case SERVICE_PROVIDES_BOTH_LISTS:
+ case OPTIMIZE_ADVANCED:
+ userConfigs.add(getNumberOfInstancesSelection());
+ userConfigs.add(getTypeOfInstanceListingSelection());
break;
- case USER_PROVIDES_ONE_OF_LISTS:
- userConfigs.add(getSpaceOfProvidedListingSelection());
- userConfigs.add(getContentIdOfProvidedListingConfig());
+ case OPTIMIZE_STANDARD:
+ userConfigs.add(getOptimizationSelection());
break;
default:
throw new RuntimeException("Unexpected ModeType: " + modeType);
}
- userConfigs.addAll(getHadoopConfigs());
-
UserConfigMode mode = new UserConfigMode();
mode.setDisplayName(modeType.getDesc());
mode.setName(modeType.getKey());
mode.setUserConfigs(userConfigs);
- mode.setUserConfigModeSets(new ArrayList<UserConfigModeSet>());
+ mode.setUserConfigModeSets(getListModeSets());
return mode;
}
- private List<UserConfig> getHadoopConfigs() {
- List<UserConfig> userConfigs = new ArrayList<UserConfig>();
+ private List<UserConfig> getDefaultUserConfigs()
+ {
+ // User Configs
+ List<UserConfig> userConfig = new ArrayList<UserConfig>();
+
+ // Include all user configs
+ userConfig.add(getTargetSpace());
+
+ return userConfig;
+ }
+ private SingleSelectUserConfig getNumberOfInstancesSelection() {
// Number of instances
List<Option> numInstancesOptions = new ArrayList<Option>();
for (int i = 1; i < 20; i++) {
Option op = new Option(String.valueOf(i), String.valueOf(i), false);
numInstancesOptions.add(op);
}
- SingleSelectUserConfig numInstances = new SingleSelectUserConfig(
+
+ return new SingleSelectUserConfig(
"numInstances",
"Number of Server Instances",
numInstancesOptions);
+ }
+ private SingleSelectUserConfig getOptimizationSelection() {
+ List<Option> options = new ArrayList<Option>();
+ options.add(new Option("Optimize for cost",
+ "optimize_for_cost",
+ true));
+ options.add(new Option("Optimize for speed",
+ "optimize_for_speed",
+ false));
+
+ return new SingleSelectUserConfig(
+ "optimizeType",
+ "Optimize",
+ options);
+ }
+
+ private SingleSelectUserConfig getTypeOfInstanceListingSelection() {
// Instance type
List<Option> instanceTypeOptions = new ArrayList<Option>();
- instanceTypeOptions.add(new Option(INSTANCES.SMALL.getDescription(),
- INSTANCES.SMALL.getId(),
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .SMALL.getDescription(),
+ HadoopTypes.INSTANCES.SMALL.getId(),
true));
- instanceTypeOptions.add(new Option(INSTANCES.LARGE.getDescription(),
- INSTANCES.LARGE.getId(),
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .LARGE.getDescription(),
+ HadoopTypes.INSTANCES.LARGE.getId(),
false));
- instanceTypeOptions.add(new Option(INSTANCES.XLARGE.getDescription(),
- INSTANCES.XLARGE.getId(),
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .XLARGE.getDescription(),
+ HadoopTypes.INSTANCES.XLARGE.getId(),
false));
- SingleSelectUserConfig instanceType = new SingleSelectUserConfig(
+ return new SingleSelectUserConfig(
"instanceType",
"Type of Server Instance",
instanceTypeOptions);
+ }
- userConfigs.add(numInstances);
- userConfigs.add(instanceType);
- return userConfigs;
+ protected enum ModeType {
+ OPTIMIZE_ADVANCED("advanced",
+ "Advanced"),
+ OPTIMIZE_STANDARD("standard",
+ "Standard"),
+ SERVICE_PROVIDES_BOTH_LISTS("all-in-one-for-list",
+ "Verify integrity of a Space"),
+ USER_PROVIDES_ONE_OF_LISTS("compare",
+ "Verify integrity from an item list");
+
+ private String key;
+ private String desc;
+
+ private ModeType(String key, String desc) {
+ this.key = key;
+ this.desc = desc;
+ }
+
+ public String toString() {
+ return getKey();
+ }
+
+ protected String getKey() {
+ return key;
+ }
+
+ protected String getDesc() {
+ return desc;
+ }
+ }
+
+ private List<UserConfigModeSet> getListModeSets() {
+ List<UserConfigMode> modes = new ArrayList<UserConfigMode>();
+
+ modes.add(getListMode(ModeType.SERVICE_PROVIDES_BOTH_LISTS));
+ modes.add(getListMode(ModeType.USER_PROVIDES_ONE_OF_LISTS));
+
+ UserConfigModeSet modeSet = new UserConfigModeSet();
+ modeSet.setModes(modes);
+ modeSet.setDisplayName("Service Mode");
+ modeSet.setName("mode");
+
+ List<UserConfigModeSet> modeSets = new ArrayList<UserConfigModeSet>();
+ modeSets.add(modeSet);
+ return modeSets;
+ }
+
+ private UserConfigMode getListMode(ModeType modeType) {
+ List<UserConfig> userConfigs = new ArrayList<UserConfig>();
+
+ switch (modeType) {
+ case SERVICE_PROVIDES_BOTH_LISTS:
+ break;
+ case USER_PROVIDES_ONE_OF_LISTS:
+ userConfigs.add(getSpaceOfProvidedListingSelection());
+ userConfigs.add(getContentIdOfProvidedListingConfig());
+ break;
+ default:
+ throw new RuntimeException("Unexpected ModeType: " + modeType);
+ }
+
+ UserConfigMode mode = new UserConfigMode();
+ mode.setDisplayName(modeType.getDesc());
+ mode.setName(modeType.getKey());
+ mode.setUserConfigs(userConfigs);
+ mode.setUserConfigModeSets(new ArrayList<UserConfigModeSet>());
+ return mode;
}
private TextUserConfig getContentIdOfProvidedListingConfig() {
diff --git a/duraservice/src/main/java/org/duracloud/duraservice/config/BulkImageConversionServiceInfo.java b/duraservice/src/main/java/org/duracloud/duraservice/config/BulkImageConversionServiceInfo.java
index 208e20160..fe546c7e4 100644
--- a/duraservice/src/main/java/org/duracloud/duraservice/config/BulkImageConversionServiceInfo.java
+++ b/duraservice/src/main/java/org/duracloud/duraservice/config/BulkImageConversionServiceInfo.java
@@ -7,6 +7,9 @@
import org.duracloud.serviceconfig.user.SingleSelectUserConfig;
import org.duracloud.serviceconfig.user.TextUserConfig;
import org.duracloud.serviceconfig.user.UserConfig;
+import org.duracloud.serviceconfig.user.UserConfigMode;
+import org.duracloud.serviceconfig.user.UserConfigModeSet;
+import org.duracloud.storage.domain.HadoopTypes;
import java.util.ArrayList;
import java.util.List;
@@ -37,6 +40,85 @@ public ServiceInfo getServiceXml(int index, String version) {
icService.setServiceVersion(version);
icService.setMaxDeploymentsAllowed(1);
+
+ icService.setUserConfigModeSets(getModeSets());
+
+ // System Configs
+ List<SystemConfig> systemConfig = new ArrayList<SystemConfig>();
+
+ SystemConfig host = new SystemConfig("duraStoreHost",
+ ServiceConfigUtil.STORE_HOST_VAR,
+ "localhost");
+ SystemConfig port = new SystemConfig("duraStorePort",
+ ServiceConfigUtil.STORE_PORT_VAR,
+ "8080");
+ SystemConfig context = new SystemConfig("duraStoreContext",
+ ServiceConfigUtil.STORE_CONTEXT_VAR,
+ "durastore");
+ SystemConfig username = new SystemConfig("username",
+ ServiceConfigUtil.STORE_USER_VAR,
+ "no-username");
+ SystemConfig password = new SystemConfig("password",
+ ServiceConfigUtil.STORE_PWORD_VAR,
+ "no-password");
+ SystemConfig mappersPerInstance = new SystemConfig("mappersPerInstance",
+ "1",
+ "1");
+
+ systemConfig.add(host);
+ systemConfig.add(port);
+ systemConfig.add(context);
+ systemConfig.add(username);
+ systemConfig.add(password);
+ systemConfig.add(mappersPerInstance);
+
+ icService.setSystemConfigs(systemConfig);
+
+ icService.setDeploymentOptions(getSimpleDeploymentOptions());
+
+ return icService;
+ }
+
+ private List<UserConfigModeSet> getModeSets() {
+ List<UserConfigMode> modes = new ArrayList<UserConfigMode>();
+
+ modes.add(getMode(ModeType.OPTIMIZE_STANDARD));
+ modes.add(getMode(ModeType.OPTIMIZE_ADVANCED));
+
+ UserConfigModeSet modeSet = new UserConfigModeSet();
+ modeSet.setModes(modes);
+ modeSet.setDisplayName("Configuration");
+ modeSet.setName("optimizeMode");
+
+ List<UserConfigModeSet> modeSets = new ArrayList<UserConfigModeSet>();
+ modeSets.add(modeSet);
+ return modeSets;
+ }
+
+ private UserConfigMode getMode(ModeType modeType) {
+ List<UserConfig> userConfigs = getDefaultUserConfigs();
+ switch (modeType) {
+ case OPTIMIZE_ADVANCED:
+ userConfigs.add(getNumberOfInstancesSelection());
+ userConfigs.add(getTypeOfInstanceListingSelection());
+ break;
+ case OPTIMIZE_STANDARD:
+ userConfigs.add(getOptimizationSelection());
+ break;
+ default:
+ throw new RuntimeException("Unexpected ModeType: " + modeType);
+ }
+
+ UserConfigMode mode = new UserConfigMode();
+ mode.setDisplayName(modeType.getDesc());
+ mode.setName(modeType.getKey());
+ mode.setUserConfigs(userConfigs);
+ mode.setUserConfigModeSets(null);
+ return mode;
+ }
+
+ private List<UserConfig> getDefaultUserConfigs()
+ {
// User Configs
List<UserConfig> icServiceUserConfig = new ArrayList<UserConfig>();
@@ -106,73 +188,92 @@ public ServiceInfo getServiceXml(int index, String version) {
"with this value will be converted.",
"");
+ // Include all user configs
+ icServiceUserConfig.add(sourceSpace);
+ icServiceUserConfig.add(destSpace);
+ icServiceUserConfig.add(toFormat);
+ icServiceUserConfig.add(colorSpace);
+ icServiceUserConfig.add(namePrefix);
+ icServiceUserConfig.add(nameSuffix);
+
+ return icServiceUserConfig;
+ }
+
+ private SingleSelectUserConfig getNumberOfInstancesSelection() {
// Number of instances
List<Option> numInstancesOptions = new ArrayList<Option>();
- for(int i = 1; i<20; i++) {
+ for (int i = 1; i < 20; i++) {
Option op = new Option(String.valueOf(i), String.valueOf(i), false);
numInstancesOptions.add(op);
}
- SingleSelectUserConfig numInstances =
- new SingleSelectUserConfig("numInstances",
- "Number of Server Instances",
- numInstancesOptions);
+ return new SingleSelectUserConfig(
+ "numInstances",
+ "Number of Server Instances",
+ numInstancesOptions);
+ }
+
+ private SingleSelectUserConfig getOptimizationSelection() {
+ List<Option> options = new ArrayList<Option>();
+ options.add(new Option("Optimize for cost",
+ "optimize_for_cost",
+ true));
+ options.add(new Option("Optimize for speed",
+ "optimize_for_speed",
+ false));
+
+ return new SingleSelectUserConfig(
+ "optimizeType",
+ "Optimize",
+ options);
+ }
+
+ private SingleSelectUserConfig getTypeOfInstanceListingSelection() {
// Instance type
List<Option> instanceTypeOptions = new ArrayList<Option>();
- instanceTypeOptions.add(new Option("Small Instance", "m1.small", true));
- instanceTypeOptions.add(new Option("Large Instance", "m1.large", false));
- instanceTypeOptions.add(
- new Option("Extra Large Instance", "m1.xlarge", false));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .SMALL.getDescription(),
+ HadoopTypes.INSTANCES.SMALL.getId(),
+ true));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .LARGE.getDescription(),
+ HadoopTypes.INSTANCES.LARGE.getId(),
+ false));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .XLARGE.getDescription(),
+ HadoopTypes.INSTANCES.XLARGE.getId(),
+ false));
- SingleSelectUserConfig instanceType =
- new SingleSelectUserConfig("instanceType",
- "Type of Server Instance",
- instanceTypeOptions);
-
- // Include all user configs
- icServiceUserConfig.add(sourceSpace);
- icServiceUserConfig.add(destSpace);
- icServiceUserConfig.add(toFormat);
- icServiceUserConfig.add(colorSpace);
- icServiceUserConfig.add(namePrefix);
- icServiceUserConfig.add(nameSuffix);
- icServiceUserConfig.add(numInstances);
- icServiceUserConfig.add(instanceType);
- icService.setUserConfigModeSets(createDefaultModeSet(icServiceUserConfig));
+ return new SingleSelectUserConfig(
+ "instanceType",
+ "Type of Server Instance",
+ instanceTypeOptions);
+ }
- // System Configs
- List<SystemConfig> systemConfig = new ArrayList<SystemConfig>();
+ protected enum ModeType {
+ OPTIMIZE_ADVANCED("advanced",
+ "Advanced"),
+ OPTIMIZE_STANDARD("standard",
+ "Standard");
- SystemConfig host = new SystemConfig("duraStoreHost",
- ServiceConfigUtil.STORE_HOST_VAR,
- "localhost");
- SystemConfig port = new SystemConfig("duraStorePort",
- ServiceConfigUtil.STORE_PORT_VAR,
- "8080");
- SystemConfig context = new SystemConfig("duraStoreContext",
- ServiceConfigUtil.STORE_CONTEXT_VAR,
- "durastore");
- SystemConfig username = new SystemConfig("username",
- ServiceConfigUtil.STORE_USER_VAR,
- "no-username");
- SystemConfig password = new SystemConfig("password",
- ServiceConfigUtil.STORE_PWORD_VAR,
- "no-password");
- SystemConfig mappersPerInstance = new SystemConfig("mappersPerInstance",
- "1",
- "1");
+ private String key;
+ private String desc;
- systemConfig.add(host);
- systemConfig.add(port);
- systemConfig.add(context);
- systemConfig.add(username);
- systemConfig.add(password);
- systemConfig.add(mappersPerInstance);
+ private ModeType(String key, String desc) {
+ this.key = key;
+ this.desc = desc;
+ }
- icService.setSystemConfigs(systemConfig);
+ public String toString() {
+ return getKey();
+ }
- icService.setDeploymentOptions(getSimpleDeploymentOptions());
+ protected String getKey() {
+ return key;
+ }
- return icService;
+ protected String getDesc() {
+ return desc;
+ }
}
}
diff --git a/duraservice/src/main/java/org/duracloud/duraservice/config/ReplicationOnDemandServiceInfo.java b/duraservice/src/main/java/org/duracloud/duraservice/config/ReplicationOnDemandServiceInfo.java
index 90c863c16..064a7d8ff 100644
--- a/duraservice/src/main/java/org/duracloud/duraservice/config/ReplicationOnDemandServiceInfo.java
+++ b/duraservice/src/main/java/org/duracloud/duraservice/config/ReplicationOnDemandServiceInfo.java
@@ -7,6 +7,9 @@
import org.duracloud.serviceconfig.user.SingleSelectUserConfig;
import org.duracloud.serviceconfig.user.TextUserConfig;
import org.duracloud.serviceconfig.user.UserConfig;
+import org.duracloud.serviceconfig.user.UserConfigMode;
+import org.duracloud.serviceconfig.user.UserConfigModeSet;
+import org.duracloud.storage.domain.HadoopTypes;
import java.util.ArrayList;
import java.util.List;
@@ -38,7 +41,83 @@ public ServiceInfo getServiceXml(int index, String version) {
repService.setUserConfigVersion("1.0");
repService.setServiceVersion(version);
repService.setMaxDeploymentsAllowed(1);
+ repService.setUserConfigModeSets(getModeSets());
+ // System Configs
+ List<SystemConfig> systemConfig = new ArrayList<SystemConfig>();
+
+ SystemConfig host = new SystemConfig("duraStoreHost",
+ ServiceConfigUtil.STORE_HOST_VAR,
+ "localhost");
+ SystemConfig port = new SystemConfig("duraStorePort",
+ ServiceConfigUtil.STORE_PORT_VAR,
+ "8080");
+ SystemConfig context = new SystemConfig("duraStoreContext",
+ ServiceConfigUtil.STORE_CONTEXT_VAR,
+ "durastore");
+ SystemConfig username = new SystemConfig("username",
+ ServiceConfigUtil.STORE_USER_VAR,
+ "no-username");
+ SystemConfig password = new SystemConfig("password",
+ ServiceConfigUtil.STORE_PWORD_VAR,
+ "no-password");
+ SystemConfig mappersPerInstance = new SystemConfig("mappersPerInstance",
+ "1",
+ "1");
+
+ systemConfig.add(host);
+ systemConfig.add(port);
+ systemConfig.add(context);
+ systemConfig.add(username);
+ systemConfig.add(password);
+ systemConfig.add(mappersPerInstance);
+
+ repService.setSystemConfigs(systemConfig);
+ repService.setDeploymentOptions(getSimpleDeploymentOptions());
+
+ return repService;
+ }
+
+ private List<UserConfigModeSet> getModeSets() {
+ List<UserConfigMode> modes = new ArrayList<UserConfigMode>();
+
+ modes.add(getMode(ModeType.OPTIMIZE_STANDARD));
+ modes.add(getMode(ModeType.OPTIMIZE_ADVANCED));
+
+ UserConfigModeSet modeSet = new UserConfigModeSet();
+ modeSet.setModes(modes);
+ modeSet.setDisplayName("Configuration");
+ modeSet.setName("optimizeMode");
+
+ List<UserConfigModeSet> modeSets = new ArrayList<UserConfigModeSet>();
+ modeSets.add(modeSet);
+ return modeSets;
+ }
+
+ private UserConfigMode getMode(ModeType modeType) {
+ List<UserConfig> userConfigs = getDefaultUserConfigs();
+ switch (modeType) {
+ case OPTIMIZE_ADVANCED:
+ userConfigs.add(getNumberOfInstancesSelection());
+ userConfigs.add(getTypeOfInstanceListingSelection());
+ break;
+ case OPTIMIZE_STANDARD:
+ userConfigs.add(getOptimizationSelection());
+ break;
+ default:
+ throw new RuntimeException("Unexpected ModeType: " + modeType);
+ }
+
+ UserConfigMode mode = new UserConfigMode();
+ mode.setDisplayName(modeType.getDesc());
+ mode.setName(modeType.getKey());
+ mode.setUserConfigs(userConfigs);
+ mode.setUserConfigModeSets(null);
+ return mode;
+ }
+
+ private List<UserConfig> getDefaultUserConfigs()
+ {
// User Configs
List<UserConfig> repServiceUserConfig = new ArrayList<UserConfig>();
@@ -55,7 +134,7 @@ public ServiceInfo getServiceXml(int index, String version) {
new Option("Stores", ServiceConfigUtil.STORES_VAR, false);
storeOptions.add(stores);
- SingleSelectUserConfig sourceSpace =
+ SingleSelectUserConfig sourceSpace =
new SingleSelectUserConfig("sourceSpaceId",
"Source Space",
spaceOptions);
@@ -68,71 +147,89 @@ public ServiceInfo getServiceXml(int index, String version) {
TextUserConfig repSpace =
new TextUserConfig("repSpaceId", "Copy to this space");
+ // Include all user configs
+ repServiceUserConfig.add(sourceSpace);
+ repServiceUserConfig.add(repStore);
+ repServiceUserConfig.add(repSpace);
+
+ return repServiceUserConfig;
+ }
+
+ private SingleSelectUserConfig getNumberOfInstancesSelection() {
// Number of instances
List<Option> numInstancesOptions = new ArrayList<Option>();
- for(int i = 1; i<20; i++) {
+ for (int i = 1; i < 20; i++) {
Option op = new Option(String.valueOf(i), String.valueOf(i), false);
numInstancesOptions.add(op);
}
- SingleSelectUserConfig numInstances =
- new SingleSelectUserConfig("numInstances",
- "Number of Server Instances",
- numInstancesOptions);
-
- // Instance type
- List<Option> instanceTypeOptions = new ArrayList<Option>();
- instanceTypeOptions.add(new Option("Small Instance", "m1.small", true));
- instanceTypeOptions.add(new Option("Large Instance", "m1.large", false));
- instanceTypeOptions.add(
- new Option("Extra Large Instance", "m1.xlarge", false));
- SingleSelectUserConfig instanceType =
- new SingleSelectUserConfig("instanceType",
- "Type of Server Instance",
- instanceTypeOptions);
+ return new SingleSelectUserConfig(
+ "numInstances",
+ "Number of Server Instances",
+ numInstancesOptions);
+ }
- // Include all user configs
- repServiceUserConfig.add(sourceSpace);
- repServiceUserConfig.add(repStore);
- repServiceUserConfig.add(repSpace);
- repServiceUserConfig.add(numInstances);
- repServiceUserConfig.add(instanceType);
+ private SingleSelectUserConfig getOptimizationSelection() {
+ List<Option> options = new ArrayList<Option>();
+ options.add(new Option("Optimize for cost",
+ "optimize_for_cost",
+ true));
+ options.add(new Option("Optimize for speed",
+ "optimize_for_speed",
+ false));
+
+ return new SingleSelectUserConfig(
+ "optimizeType",
+ "Optimize",
+ options);
+ }
- repService.setUserConfigModeSets(createDefaultModeSet(repServiceUserConfig));
+ private SingleSelectUserConfig getTypeOfInstanceListingSelection() {
+ // Instance type
+ List<Option> instanceTypeOptions = new ArrayList<Option>();
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .SMALL.getDescription(),
+ HadoopTypes.INSTANCES.SMALL.getId(),
+ true));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .LARGE.getDescription(),
+ HadoopTypes.INSTANCES.LARGE.getId(),
+ false));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .XLARGE.getDescription(),
+ HadoopTypes.INSTANCES.XLARGE.getId(),
+ false));
+
+ return new SingleSelectUserConfig(
+ "instanceType",
+ "Type of Server Instance",
+ instanceTypeOptions);
+ }
- // System Configs
- List<SystemConfig> systemConfig = new ArrayList<SystemConfig>();
+ protected enum ModeType {
+ OPTIMIZE_ADVANCED("advanced",
+ "Advanced"),
+ OPTIMIZE_STANDARD("standard",
+ "Standard");
- SystemConfig host = new SystemConfig("duraStoreHost",
- ServiceConfigUtil.STORE_HOST_VAR,
- "localhost");
- SystemConfig port = new SystemConfig("duraStorePort",
- ServiceConfigUtil.STORE_PORT_VAR,
- "8080");
- SystemConfig context = new SystemConfig("duraStoreContext",
- ServiceConfigUtil.STORE_CONTEXT_VAR,
- "durastore");
- SystemConfig username = new SystemConfig("username",
- ServiceConfigUtil.STORE_USER_VAR,
- "no-username");
- SystemConfig password = new SystemConfig("password",
- ServiceConfigUtil.STORE_PWORD_VAR,
- "no-password");
- SystemConfig mappersPerInstance = new SystemConfig("mappersPerInstance",
- "1",
- "1");
+ private String key;
+ private String desc;
- systemConfig.add(host);
- systemConfig.add(port);
- systemConfig.add(context);
- systemConfig.add(username);
- systemConfig.add(password);
- systemConfig.add(mappersPerInstance);
+ private ModeType(String key, String desc) {
+ this.key = key;
+ this.desc = desc;
+ }
- repService.setSystemConfigs(systemConfig);
+ public String toString() {
+ return getKey();
+ }
- repService.setDeploymentOptions(getSimpleDeploymentOptions());
+ protected String getKey() {
+ return key;
+ }
- return repService;
+ protected String getDesc() {
+ return desc;
+ }
}
}
diff --git a/duraservice/src/test/java/org/duracloud/duraservice/config/ServiceXmlGeneratorTest.java b/duraservice/src/test/java/org/duracloud/duraservice/config/ServiceXmlGeneratorTest.java
index 0d4b75853..a70eb8a52 100644
--- a/duraservice/src/test/java/org/duracloud/duraservice/config/ServiceXmlGeneratorTest.java
+++ b/duraservice/src/test/java/org/duracloud/duraservice/config/ServiceXmlGeneratorTest.java
@@ -203,9 +203,13 @@ private void verifyFixityTools(ServiceInfo serviceInfo) {
}
private void verifyBulkImageconversion(ServiceInfo serviceInfo) {
- int numUserConfigs = 8;
+ int numUserConfigs = 0;
int numSystemConfigs = 6;
verifyServiceInfo(numUserConfigs, numSystemConfigs, serviceInfo);
+
+ List<List<Integer>> setsModesConfigs = new ArrayList<List<Integer>>();
+ setsModesConfigs.add(Arrays.asList(7,8));
+ verifyServiceModes(setsModesConfigs, serviceInfo);
}
private void verifyAmazonFixity(ServiceInfo serviceInfo) {
@@ -214,14 +218,18 @@ private void verifyAmazonFixity(ServiceInfo serviceInfo) {
verifyServiceInfo(numUserConfigs, numSystemConfigs, serviceInfo);
List<List<Integer>> setsModesConfigs = new ArrayList<List<Integer>>();
- setsModesConfigs.add(Arrays.asList(3, 5));
+ setsModesConfigs.add(Arrays.asList(2, 3));
verifyServiceModes(setsModesConfigs, serviceInfo);
}
private void verifyRepOnDemand(ServiceInfo serviceInfo) {
- int numUserConfigs = 5;
+ int numUserConfigs = 0;
int numSystemConfigs = 6;
verifyServiceInfo(numUserConfigs, numSystemConfigs, serviceInfo);
+
+ List<List<Integer>> setsModesConfigs = new ArrayList<List<Integer>>();
+ setsModesConfigs.add(Arrays.asList(4,5));
+ verifyServiceModes(setsModesConfigs, serviceInfo);
}
private void verifyServiceInfo(int numUserConfigs,
diff --git a/services/amazonfixityservice/src/main/java/org/duracloud/services/amazonfixity/AmazonFixityService.java b/services/amazonfixityservice/src/main/java/org/duracloud/services/amazonfixity/AmazonFixityService.java
index 7f8e0a592..47234d373 100644
--- a/services/amazonfixityservice/src/main/java/org/duracloud/services/amazonfixity/AmazonFixityService.java
+++ b/services/amazonfixityservice/src/main/java/org/duracloud/services/amazonfixity/AmazonFixityService.java
@@ -37,6 +37,14 @@ public class AmazonFixityService extends BaseAmazonMapReduceService implements M
private String providedListingSpaceIdB;
private String providedListingContentIdB;
private String mode;
+ private String optimizeMode;
+ private String optimizeType;
+ private String numInstances;
+ private String instanceType;
+ private String costNumInstances;
+ private String costInstanceType;
+ private String speedNumInstances;
+ private String speedInstanceType;
@Override
protected AmazonMapReduceJobWorker getJobWorker() {
@@ -131,6 +139,38 @@ protected String getNumMappers(String instanceType) {
return mappers;
}
+ @Override
+ protected String getInstancesType() {
+ String instanceType = getInstanceType();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ instanceType = getCostInstanceType();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ instanceType = getSpeedInstanceType();
+ }
+ }
+
+ return instanceType;
+ }
+
+ @Override
+ protected String getNumOfInstances() {
+ String numOfInstances = getNumInstances();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ numOfInstances = getCostNumInstances();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ numOfInstances = getSpeedNumInstances();
+ }
+ }
+
+ return numOfInstances;
+ }
+
public String getProvidedListingSpaceIdB() {
return providedListingSpaceIdB;
}
@@ -154,4 +194,92 @@ public String getMode() {
public void setMode(String mode) {
this.mode = mode;
}
+
+ public String getOptimizeMode() {
+ return optimizeMode;
+ }
+
+ public void setOptimizeMode(String optimizeMode) {
+ this.optimizeMode = optimizeMode;
+ }
+
+ public String getNumInstances() {
+ return numInstances;
+ }
+
+ public void setNumInstances(String numInstances) {
+ if (numInstances != null && !numInstances.equals("")) {
+ try {
+ Integer.valueOf(numInstances);
+ this.numInstances = numInstances;
+ } catch (NumberFormatException e) {
+ log.warn(
+ "Attempt made to set numInstances to a non-numerical " +
+ "value, which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ } else {
+ log.warn("Attempt made to set numInstances to to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ }
+
+ public String getInstanceType() {
+ return instanceType;
+ }
+
+ public void setInstanceType(String instanceType) {
+
+ if (instanceType != null && !instanceType.equals("")) {
+ this.instanceType = instanceType;
+ } else {
+ log.warn("Attempt made to set typeOfInstance to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_INSTANCE_TYPE);
+ this.instanceType = DEFAULT_INSTANCE_TYPE;
+ }
+ }
+
+ public String getOptimizeType() {
+ return optimizeType;
+ }
+
+ public void setOptimizeType(String optimizeType) {
+ this.optimizeType = optimizeType;
+ }
+
+ public String getCostNumInstances() {
+ return costNumInstances;
+ }
+
+ public void setCostNumInstances(String costNumInstances) {
+ this.costNumInstances = costNumInstances;
+ }
+
+ public String getCostInstanceType() {
+ return costInstanceType;
+ }
+
+ public void setCostInstanceType(String costInstanceType) {
+ this.costInstanceType = costInstanceType;
+ }
+
+ public String getSpeedNumInstances() {
+ return speedNumInstances;
+ }
+
+ public void setSpeedNumInstances(String speedNumInstances) {
+ this.speedNumInstances = speedNumInstances;
+ }
+
+ public String getSpeedInstanceType() {
+ return speedInstanceType;
+ }
+
+ public void setSpeedInstanceType(String speedInstanceType) {
+ this.speedInstanceType = speedInstanceType;
+ }
}
diff --git a/services/amazonfixityservice/src/main/resources/META-INF/spring/bundle-context.xml b/services/amazonfixityservice/src/main/resources/META-INF/spring/bundle-context.xml
index abd17d931..ffb37c98a 100644
--- a/services/amazonfixityservice/src/main/resources/META-INF/spring/bundle-context.xml
+++ b/services/amazonfixityservice/src/main/resources/META-INF/spring/bundle-context.xml
@@ -15,6 +15,10 @@
<property name="serviceId" value="amazonfixityservice-${project.version}" />
<property name="destSpaceId" value="${service.output.spaceid}"/>
<property name="workSpaceId" value="${service.work.spaceid}"/>
+ <property name="costNumInstances" value="3"/>
+ <property name="costInstanceType" value="m1.small"/>
+ <property name="speedNumInstances" value="10"/>
+ <property name="speedInstanceType" value="m1.xlarge"/>
</bean>
</beans>
diff --git a/services/amazonfixityservice/src/test/java/org/duracloud/services/amazonfixity/AmazonFixityServiceTest.java b/services/amazonfixityservice/src/test/java/org/duracloud/services/amazonfixity/AmazonFixityServiceTest.java
index caab9516e..eb558f54f 100644
--- a/services/amazonfixityservice/src/test/java/org/duracloud/services/amazonfixity/AmazonFixityServiceTest.java
+++ b/services/amazonfixityservice/src/test/java/org/duracloud/services/amazonfixity/AmazonFixityServiceTest.java
@@ -25,6 +25,7 @@
import java.util.HashMap;
import java.util.Map;
+import static junit.framework.Assert.assertEquals;
import static org.duracloud.storage.domain.HadoopTypes.RUN_HADOOP_TASK_NAME;
import static org.duracloud.storage.domain.HadoopTypes.TASK_OUTPUTS;
import static org.duracloud.storage.domain.HadoopTypes.JOB_TYPES;
@@ -69,6 +70,30 @@ private void verifyNumMappers(String num, String expected) {
Assert.assertEquals(expected, num);
}
+ @Test
+ public void testOptmizationConfig() {
+ String instanceType = "m1.xlarge";
+ String numOfInstances = "10";
+
+ AmazonFixityService service = new AmazonFixityService();
+ service.setOptimizeMode("standard");
+ service.setOptimizeType("optimize_for_speed");
+ service.setSpeedInstanceType(instanceType);
+ service.setSpeedNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+
+ instanceType = "m1.large";
+ numOfInstances = "3";
+ service.setOptimizeType("optimize_for_cost");
+ service.setSpeedInstanceType(null);
+ service.setSpeedNumInstances(null);
+ service.setCostInstanceType(instanceType);
+ service.setCostNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+ }
+
@Test
public void testStart() throws Exception {
setUpStart();
@@ -93,6 +118,8 @@ private void sleep(long millis) {
private void setUpStart() throws Exception {
service.setWorkSpaceId("work-space-id");
+ service.setOptimizeMode("standard");
+ service.setOptimizeType("optimize_for_cost");
contentStore = createMockContentStore();
service.setContentStore(contentStore);
diff --git a/services/amazonmapreduce-servicescommon/src/main/java/org/duracloud/services/amazonmapreduce/BaseAmazonMapReduceService.java b/services/amazonmapreduce-servicescommon/src/main/java/org/duracloud/services/amazonmapreduce/BaseAmazonMapReduceService.java
index 00205b3bb..8bababa78 100644
--- a/services/amazonmapreduce-servicescommon/src/main/java/org/duracloud/services/amazonmapreduce/BaseAmazonMapReduceService.java
+++ b/services/amazonmapreduce-servicescommon/src/main/java/org/duracloud/services/amazonmapreduce/BaseAmazonMapReduceService.java
@@ -47,10 +47,14 @@ public abstract class BaseAmazonMapReduceService extends BaseService implements
private static final String DEFAULT_DURASTORE_PORT = "8080";
private static final String DEFAULT_DURASTORE_CONTEXT = "durastore";
private static final String DEFAULT_SOURCE_SPACE_ID = "service-source";
- private static final String DEFAULT_NUM_INSTANCES = "1";
- private static final String DEFAULT_INSTANCE_TYPE = SMALL.getId();
+ protected static final String DEFAULT_NUM_INSTANCES = "1";
+ protected static final String DEFAULT_INSTANCE_TYPE = SMALL.getId();
protected static final String DEFAULT_NUM_MAPPERS = "1";
+ protected static final String OPTIMIZE_MODE_STANDARD = "standard";
+ protected static final String OPTIMIZE_COST = "optimize_for_cost";
+ protected static final String OPTIMIZE_SPEED = "optimize_for_speed";
+
private String duraStoreHost;
private String duraStorePort;
private String duraStoreContext;
@@ -59,8 +63,6 @@ public abstract class BaseAmazonMapReduceService extends BaseService implements
private String sourceSpaceId;
private String destSpaceId;
private String workSpaceId;
- private String numInstances;
- private String instanceType;
private String mappersPerInstance;
private ContentStore contentStore;
@@ -73,6 +75,10 @@ public abstract class BaseAmazonMapReduceService extends BaseService implements
protected abstract String getNumMappers(String instanceType);
+ protected abstract String getInstancesType();
+
+ protected abstract String getNumOfInstances();
+
@Override
public void start() throws Exception {
log.info("Starting " + getServiceId() + " as " + username);
@@ -98,11 +104,11 @@ protected Map<String, String> collectTaskParams() {
taskParams.put(TASK_PARAMS.WORKSPACE_ID.name(), workSpaceId);
taskParams.put(TASK_PARAMS.SOURCE_SPACE_ID.name(), sourceSpaceId);
taskParams.put(TASK_PARAMS.DEST_SPACE_ID.name(), destSpaceId);
- taskParams.put(TASK_PARAMS.INSTANCE_TYPE.name(), instanceType);
- taskParams.put(TASK_PARAMS.NUM_INSTANCES.name(), numInstances);
+ taskParams.put(TASK_PARAMS.INSTANCE_TYPE.name(), getInstancesType());
+ taskParams.put(TASK_PARAMS.NUM_INSTANCES.name(), getNumOfInstances());
taskParams.put(TASK_PARAMS.MAPPERS_PER_INSTANCE.name(), getNumMappers(
- instanceType));
+ getInstancesType()));
taskParams.put(TASK_PARAMS.DC_HOST.name(), getDuraStoreHost());
taskParams.put(TASK_PARAMS.DC_PORT.name(), getDuraStorePort());
@@ -284,45 +290,6 @@ public void setWorkSpaceId(String workSpaceId) {
this.workSpaceId = workSpaceId;
}
- public String getNumInstances() {
- return numInstances;
- }
-
- public void setNumInstances(String numInstances) {
- if (numInstances != null && !numInstances.equals("")) {
- try {
- Integer.valueOf(numInstances);
- this.numInstances = numInstances;
- } catch (NumberFormatException e) {
- log("Attempt made to set numInstances to a non-numerical " +
- "value, which is not valid. Setting value to default: " +
- DEFAULT_NUM_INSTANCES);
- this.numInstances = DEFAULT_NUM_INSTANCES;
- }
- } else {
- log("Attempt made to set numInstances to to null or empty, " +
- ", which is not valid. Setting value to default: " +
- DEFAULT_NUM_INSTANCES);
- this.numInstances = DEFAULT_NUM_INSTANCES;
- }
- }
-
- public String getInstanceType() {
- return instanceType;
- }
-
- public void setInstanceType(String instanceType) {
-
- if (instanceType != null && !instanceType.equals("")) {
- this.instanceType = instanceType;
- } else {
- log("Attempt made to set typeOfInstance to null or empty, " +
- ", which is not valid. Setting value to default: " +
- DEFAULT_INSTANCE_TYPE);
- this.instanceType = DEFAULT_INSTANCE_TYPE;
- }
- }
-
public String getMappersPerInstance() {
return mappersPerInstance;
}
diff --git a/services/bulkimageconversionservice/src/main/java/org/duracloud/services/bulkimageconversion/BulkImageConversionService.java b/services/bulkimageconversionservice/src/main/java/org/duracloud/services/bulkimageconversion/BulkImageConversionService.java
index 26e7ce684..c35698d16 100644
--- a/services/bulkimageconversionservice/src/main/java/org/duracloud/services/bulkimageconversion/BulkImageConversionService.java
+++ b/services/bulkimageconversionservice/src/main/java/org/duracloud/services/bulkimageconversion/BulkImageConversionService.java
@@ -42,6 +42,14 @@ public class BulkImageConversionService extends BaseAmazonMapReduceService imple
private String colorSpace;
private String namePrefix;
private String nameSuffix;
+ private String optimizeMode;
+ private String optimizeType;
+ private String numInstances;
+ private String instanceType;
+ private String costNumInstances;
+ private String costInstanceType;
+ private String speedNumInstances;
+ private String speedInstanceType;
private AmazonMapReduceJobWorker worker;
private AmazonMapReduceJobWorker postWorker;
@@ -84,6 +92,38 @@ protected String getNumMappers(String instanceType) {
return mappers;
}
+ @Override
+ protected String getInstancesType() {
+ String instanceType = getInstanceType();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ instanceType = getCostInstanceType();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ instanceType = getSpeedInstanceType();
+ }
+ }
+
+ return instanceType;
+ }
+
+ @Override
+ protected String getNumOfInstances() {
+ String numOfInstances = getNumInstances();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ numOfInstances = getCostNumInstances();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ numOfInstances = getSpeedNumInstances();
+ }
+ }
+
+ return numOfInstances;
+ }
+
@Override
protected Map<String, String> collectTaskParams() {
Map<String, String> taskParams = super.collectTaskParams();
@@ -168,6 +208,94 @@ public void setNameSuffix(String nameSuffix) {
}
}
+ public String getOptimizeMode() {
+ return optimizeMode;
+ }
+
+ public void setOptimizeMode(String optimizeMode) {
+ this.optimizeMode = optimizeMode;
+ }
+
+ public String getNumInstances() {
+ return numInstances;
+ }
+
+ public void setNumInstances(String numInstances) {
+ if (numInstances != null && !numInstances.equals("")) {
+ try {
+ Integer.valueOf(numInstances);
+ this.numInstances = numInstances;
+ } catch (NumberFormatException e) {
+ log.warn(
+ "Attempt made to set numInstances to a non-numerical " +
+ "value, which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ } else {
+ log.warn("Attempt made to set numInstances to to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ }
+
+ public String getInstanceType() {
+ return instanceType;
+ }
+
+ public void setInstanceType(String instanceType) {
+
+ if (instanceType != null && !instanceType.equals("")) {
+ this.instanceType = instanceType;
+ } else {
+ log.warn("Attempt made to set typeOfInstance to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_INSTANCE_TYPE);
+ this.instanceType = DEFAULT_INSTANCE_TYPE;
+ }
+ }
+
+ public String getOptimizeType() {
+ return optimizeType;
+ }
+
+ public void setOptimizeType(String optimizeType) {
+ this.optimizeType = optimizeType;
+ }
+
+ public String getCostNumInstances() {
+ return costNumInstances;
+ }
+
+ public void setCostNumInstances(String costNumInstances) {
+ this.costNumInstances = costNumInstances;
+ }
+
+ public String getCostInstanceType() {
+ return costInstanceType;
+ }
+
+ public void setCostInstanceType(String costInstanceType) {
+ this.costInstanceType = costInstanceType;
+ }
+
+ public String getSpeedNumInstances() {
+ return speedNumInstances;
+ }
+
+ public void setSpeedNumInstances(String speedNumInstances) {
+ this.speedNumInstances = speedNumInstances;
+ }
+
+ public String getSpeedInstanceType() {
+ return speedInstanceType;
+ }
+
+ public void setSpeedInstanceType(String speedInstanceType) {
+ this.speedInstanceType = speedInstanceType;
+ }
+
private void log(String logMsg) {
log.warn(logMsg);
}
diff --git a/services/bulkimageconversionservice/src/main/resources/META-INF/spring/bundle-context.xml b/services/bulkimageconversionservice/src/main/resources/META-INF/spring/bundle-context.xml
index 02f08aa9b..496cbb2eb 100644
--- a/services/bulkimageconversionservice/src/main/resources/META-INF/spring/bundle-context.xml
+++ b/services/bulkimageconversionservice/src/main/resources/META-INF/spring/bundle-context.xml
@@ -23,8 +23,10 @@
<property name="workSpaceId" value="${service.work.spaceid}"/>
<property name="namePrefix" value=""/>
<property name="nameSuffix" value=""/>
- <property name="numInstances" value="1"/>
- <property name="instanceType" value="m1.small"/>
+ <property name="costNumInstances" value="3"/>
+ <property name="costInstanceType" value="m1.large"/>
+ <property name="speedNumInstances" value="10"/>
+ <property name="speedInstanceType" value="m1.xlarge"/>
<property name="mappersPerInstance" value="1"/>
</bean>
diff --git a/services/bulkimageconversionservice/src/test/java/org/duracloud/services/bulkimageconversion/BulkImageConversionServiceTest.java b/services/bulkimageconversionservice/src/test/java/org/duracloud/services/bulkimageconversion/BulkImageConversionServiceTest.java
index b0124f5dd..03a542e3e 100644
--- a/services/bulkimageconversionservice/src/test/java/org/duracloud/services/bulkimageconversion/BulkImageConversionServiceTest.java
+++ b/services/bulkimageconversionservice/src/test/java/org/duracloud/services/bulkimageconversion/BulkImageConversionServiceTest.java
@@ -33,6 +33,7 @@ public void testCollectTaskParams() {
service.setNamePrefix("test-");
service.setNameSuffix("-test");
service.setColorSpace("sRGB");
+ service.setOptimizeMode("advanced");
service.setInstanceType("c1.xlarge");
service.setNumInstances("8");
@@ -130,6 +131,30 @@ public void testBulkImageConversionParameters() {
assertEquals("8", service.getMappersPerInstance());
}
+ @Test
+ public void testOptmizationConfig() {
+ String instanceType = "m1.xlarge";
+ String numOfInstances = "10";
+
+ BulkImageConversionService service = new BulkImageConversionService();
+ service.setOptimizeMode("standard");
+ service.setOptimizeType("optimize_for_speed");
+ service.setSpeedInstanceType(instanceType);
+ service.setSpeedNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+
+ instanceType = "m1.large";
+ numOfInstances = "3";
+ service.setOptimizeType("optimize_for_cost");
+ service.setSpeedInstanceType(null);
+ service.setSpeedNumInstances(null);
+ service.setCostInstanceType(instanceType);
+ service.setCostNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+ }
+
@Test
public void testGetNumMappers() {
BulkImageConversionService service = new BulkImageConversionService();
diff --git a/services/replication-on-demand-service/src/main/java/org/duracloud/services/replicationod/ReplicationOnDemandService.java b/services/replication-on-demand-service/src/main/java/org/duracloud/services/replicationod/ReplicationOnDemandService.java
index 04611342f..134d059be 100644
--- a/services/replication-on-demand-service/src/main/java/org/duracloud/services/replicationod/ReplicationOnDemandService.java
+++ b/services/replication-on-demand-service/src/main/java/org/duracloud/services/replicationod/ReplicationOnDemandService.java
@@ -36,6 +36,14 @@ public class ReplicationOnDemandService extends BaseAmazonMapReduceService imple
private String repStoreId;
private String repSpaceId;
+ private String optimizeMode;
+ private String optimizeType;
+ private String numInstances;
+ private String instanceType;
+ private String costNumInstances;
+ private String costInstanceType;
+ private String speedNumInstances;
+ private String speedInstanceType;
private ReplicationOnDemandJobWorker worker;
@@ -85,6 +93,38 @@ protected String getNumMappers(String instanceType) {
return mappers;
}
+ @Override
+ protected String getInstancesType() {
+ String instanceType = getInstanceType();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ instanceType = getCostInstanceType();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ instanceType = getSpeedInstanceType();
+ }
+ }
+
+ return instanceType;
+ }
+
+ @Override
+ protected String getNumOfInstances() {
+ String numOfInstances = getNumInstances();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ numOfInstances = getCostNumInstances();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ numOfInstances = getSpeedNumInstances();
+ }
+ }
+
+ return numOfInstances;
+ }
+
@Override
protected Map<String, String> collectTaskParams() {
Map<String, String> taskParams = super.collectTaskParams();
@@ -130,6 +170,94 @@ public void setRepSpaceId(String repSpaceId) {
}
}
+ public String getOptimizeMode() {
+ return optimizeMode;
+ }
+
+ public void setOptimizeMode(String optimizeMode) {
+ this.optimizeMode = optimizeMode;
+ }
+
+ public String getNumInstances() {
+ return numInstances;
+ }
+
+ public void setNumInstances(String numInstances) {
+ if (numInstances != null && !numInstances.equals("")) {
+ try {
+ Integer.valueOf(numInstances);
+ this.numInstances = numInstances;
+ } catch (NumberFormatException e) {
+ log.warn(
+ "Attempt made to set numInstances to a non-numerical " +
+ "value, which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ } else {
+ log.warn("Attempt made to set numInstances to to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ }
+
+ public String getInstanceType() {
+ return instanceType;
+ }
+
+ public void setInstanceType(String instanceType) {
+
+ if (instanceType != null && !instanceType.equals("")) {
+ this.instanceType = instanceType;
+ } else {
+ log.warn("Attempt made to set typeOfInstance to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_INSTANCE_TYPE);
+ this.instanceType = DEFAULT_INSTANCE_TYPE;
+ }
+ }
+
+ public String getOptimizeType() {
+ return optimizeType;
+ }
+
+ public void setOptimizeType(String optimizeType) {
+ this.optimizeType = optimizeType;
+ }
+
+ public String getCostNumInstances() {
+ return costNumInstances;
+ }
+
+ public void setCostNumInstances(String costNumInstances) {
+ this.costNumInstances = costNumInstances;
+ }
+
+ public String getCostInstanceType() {
+ return costInstanceType;
+ }
+
+ public void setCostInstanceType(String costInstanceType) {
+ this.costInstanceType = costInstanceType;
+ }
+
+ public String getSpeedNumInstances() {
+ return speedNumInstances;
+ }
+
+ public void setSpeedNumInstances(String speedNumInstances) {
+ this.speedNumInstances = speedNumInstances;
+ }
+
+ public String getSpeedInstanceType() {
+ return speedInstanceType;
+ }
+
+ public void setSpeedInstanceType(String speedInstanceType) {
+ this.speedInstanceType = speedInstanceType;
+ }
+
private void log(String logMsg) {
log.warn(logMsg);
}
diff --git a/services/replication-on-demand-service/src/main/resources/META-INF/spring/bundle-context.xml b/services/replication-on-demand-service/src/main/resources/META-INF/spring/bundle-context.xml
index 86fdcef1d..c1c37ab13 100644
--- a/services/replication-on-demand-service/src/main/resources/META-INF/spring/bundle-context.xml
+++ b/services/replication-on-demand-service/src/main/resources/META-INF/spring/bundle-context.xml
@@ -23,8 +23,10 @@
<property name="repSpaceId" value="replication-space"/>
<property name="destSpaceId" value="${service.output.spaceid}"/>
<property name="workSpaceId" value="${service.work.spaceid}"/>
- <property name="numInstances" value="1"/>
- <property name="instanceType" value="m1.small"/>
+ <property name="costNumInstances" value="3"/>
+ <property name="costInstanceType" value="m1.small"/>
+ <property name="speedNumInstances" value="5"/>
+ <property name="speedInstanceType" value="m1.large"/>
<property name="mappersPerInstance" value="1"/>
</bean>
diff --git a/services/replication-on-demand-service/src/test/java/org/duracloud/services/replicationod/ReplicationOnDemandServiceTest.java b/services/replication-on-demand-service/src/test/java/org/duracloud/services/replicationod/ReplicationOnDemandServiceTest.java
index 06bc11e85..f99193f70 100644
--- a/services/replication-on-demand-service/src/test/java/org/duracloud/services/replicationod/ReplicationOnDemandServiceTest.java
+++ b/services/replication-on-demand-service/src/test/java/org/duracloud/services/replicationod/ReplicationOnDemandServiceTest.java
@@ -30,6 +30,7 @@ public void testCollectTaskParams() {
String repStoreId = "0";
String repSpaceId = "rep-space";
String destSpaceId = "test-dest";
+ String optimizeMode = "advanced";
String instanceType = "c1.xlarge";
String numInstances = "8";
String dcHost = "dchost";
@@ -44,6 +45,7 @@ public void testCollectTaskParams() {
service.setRepStoreId(repStoreId);
service.setRepSpaceId(repSpaceId);
service.setDestSpaceId(destSpaceId);
+ service.setOptimizeMode(optimizeMode);
service.setInstanceType(instanceType);
service.setNumInstances(numInstances);
service.setDuraStoreHost(dcHost);
@@ -138,6 +140,30 @@ public void testReplicationOnDemandParameters() {
assertEquals("8", service.getMappersPerInstance());
}
+ @Test
+ public void testOptmizationConfig() {
+ String instanceType = "m1.xlarge";
+ String numOfInstances = "10";
+
+ ReplicationOnDemandService service = new ReplicationOnDemandService();
+ service.setOptimizeMode("standard");
+ service.setOptimizeType("optimize_for_speed");
+ service.setSpeedInstanceType(instanceType);
+ service.setSpeedNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+
+ instanceType = "m1.large";
+ numOfInstances = "3";
+ service.setOptimizeType("optimize_for_cost");
+ service.setSpeedInstanceType(null);
+ service.setSpeedNumInstances(null);
+ service.setCostInstanceType(instanceType);
+ service.setCostNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+ }
+
@Test
public void testGetNumMappers() {
ReplicationOnDemandService service = new ReplicationOnDemandService();
|
8b9ffeb5f2883e3d5187ad2f4a3a35540ff70326
|
drools
|
JBRULES-527: fixing compilation problems--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@6992 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/reteoo/BetaMemory.java b/drools-core/src/main/java/org/drools/reteoo/BetaMemory.java
index 3242224b102..90471a806f0 100644
--- a/drools-core/src/main/java/org/drools/reteoo/BetaMemory.java
+++ b/drools-core/src/main/java/org/drools/reteoo/BetaMemory.java
@@ -1,10 +1,14 @@
package org.drools.reteoo;
+import java.util.HashMap;
+import java.util.Map;
+
import org.drools.util.TupleHashTable;
public class BetaMemory {
private TupleHashTable tupleMemory;
private ObjectHashTable objectMemory;
+ private Map createdHandles;
public BetaMemory(final TupleHashTable tupleMemory,
final ObjectHashTable objectMemory) {
@@ -19,4 +23,11 @@ public ObjectHashTable getObjectMemory() {
public TupleHashTable getTupleMemory() {
return this.tupleMemory;
}
+
+ public Map getCreatedHandles() {
+ if(createdHandles == null) {
+ createdHandles = new HashMap();
+ }
+ return createdHandles;
+ }
}
diff --git a/drools-core/src/main/java/org/drools/reteoo/BetaNode.java b/drools-core/src/main/java/org/drools/reteoo/BetaNode.java
index 20525acf049..fd03f8f6dc0 100644
--- a/drools-core/src/main/java/org/drools/reteoo/BetaNode.java
+++ b/drools-core/src/main/java/org/drools/reteoo/BetaNode.java
@@ -227,42 +227,6 @@ public boolean equals(final Object object) {
*/
public Object createMemory(final RuleBaseConfiguration config) {
return this.constraints.createBetaMemory();
- // // iterate over all the constraints untill we find one that is indexeable. When we find it we remove it from the list and create the
- // // BetaMemory for it. If we don't find one, we create a normal beta memory. We don't need the constraint as we can assume that
- // // anything returned by the memory already passes that test.
- // LinkedList constraints = this.constraints.getConstraints();
- // BetaMemory memory = null;
- //
- // if ( constraints != null ) {
- // for ( LinkedListEntry entry = (LinkedListEntry) constraints.getFirst(); entry != null; entry = (LinkedListEntry) entry.getNext() ) {
- // BetaNodeFieldConstraint constraint = (BetaNodeFieldConstraint) entry.getObject();
- // if ( constraint.getClass() == VariableConstraint.class ) {
- // VariableConstraint variableConstraint = (VariableConstraint) constraint;
- // FieldExtractor extractor = variableConstraint.getFieldExtractor();
- // Evaluator evaluator = variableConstraint.getEvaluator();
- // if ( evaluator.getOperator() == Operator.EQUAL ) {
- // // make suret the indexed constraint is first
- // if ( constraints.getFirst() != entry ) {
- // constraints.remove( entry );
- // constraints.insertAfter( null,
- // entry );
- // }
- // memory = new BetaMemory( new TupleHashTable(),
- // new FieldIndexHashTable( extractor,
- // variableConstraint.getRequiredDeclarations()[0] ) );
- // break;
- //
- // }
- // }
- // }
- // }
- //
- // if ( memory == null ) {
- // memory = new BetaMemory( new TupleHashTable(),
- // new FactHashTable() );
- // }
- //
- // return memory;
}
/**
diff --git a/drools-core/src/main/java/org/drools/reteoo/CollectNode.java b/drools-core/src/main/java/org/drools/reteoo/CollectNode.java
index bfc0ff76abb..088e43a74fa 100755
--- a/drools-core/src/main/java/org/drools/reteoo/CollectNode.java
+++ b/drools-core/src/main/java/org/drools/reteoo/CollectNode.java
@@ -125,8 +125,9 @@ public void assertTuple(final ReteTuple leftTuple,
final Collection result = this.collect.instantiateResultObject();
final Iterator it = memory.getObjectMemory().iterator( leftTuple );
- this.constraints.updateFromTuple( workingMemory, leftTuple );
-
+ this.constraints.updateFromTuple( workingMemory,
+ leftTuple );
+
for ( FactEntry entry = (FactEntry) it.next(); entry != null; entry = (FactEntry) it.next() ) {
final InternalFactHandle handle = entry.getFactHandle();
if ( this.constraints.isAllowedCachedLeft( handle.getObject() ) ) {
@@ -144,13 +145,15 @@ public void assertTuple(final ReteTuple leftTuple,
}
}
if ( isAllowed ) {
- final InternalFactHandle handle = workingMemory.getFactHandleFactory().newFactHandle( result );
-
if ( this.resultsBinder.isAllowedCachedLeft( result ) ) {
- this.sink.propagateAssertTuple( leftTuple,
- handle,
- context,
- workingMemory );
+ final InternalFactHandle handle = workingMemory.getFactHandleFactory().newFactHandle( result );
+ memory.getCreatedHandles().put( leftTuple,
+ handle );
+
+ sink.propagateAssertTuple( leftTuple,
+ handle,
+ context,
+ workingMemory );
}
}
}
@@ -161,31 +164,22 @@ public void assertTuple(final ReteTuple leftTuple,
public void retractTuple(final ReteTuple leftTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
- // FIXME
-// final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this );
-// memory.getTupleMemory().remove( leftTuple );
-//
-// final Map matches = leftTuple.getTupleMatches();
-//
-// if ( !matches.isEmpty() ) {
-// for ( final Iterator it = matches.values().iterator(); it.hasNext(); ) {
-// final CompositeTupleMatch compositeTupleMatch = (CompositeTupleMatch) it.next();
-// compositeTupleMatch.getObjectMatches().remove( compositeTupleMatch );
-// it.remove();
-// }
-// }
-//
-// // if tuple was propagated
-// if ( (leftTuple.getChildEntries() != null) && (leftTuple.getChildEntries().size() > 0) ) {
-// // Need to store the collection result object for later disposal
-// final InternalFactHandle lastHandle = ((ReteTuple) ((LinkedListEntry) leftTuple.getChildEntries().getFirst()).getObject()).getLastHandle();
-//
-// leftTuple.retractChildEntries( context,
-// workingMemory );
-//
-// // Destroying the acumulate result object
-// workingMemory.getFactHandleFactory().destroyFactHandle( lastHandle );
-// }
+
+ final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this );
+ memory.getTupleMemory().remove( leftTuple );
+ final InternalFactHandle handle = (InternalFactHandle) memory.getCreatedHandles().remove( leftTuple );
+
+ // if tuple was propagated
+ if ( handle != null ) {
+
+ this.sink.propagateRetractTuple( leftTuple,
+ handle,
+ context,
+ workingMemory );
+
+ // Destroying the acumulate result object
+ workingMemory.getFactHandleFactory().destroyFactHandle( handle );
+ }
}
/**
@@ -205,11 +199,16 @@ public void assertObject(final InternalFactHandle handle,
memory.getObjectMemory().add( handle );
final Iterator it = memory.getTupleMemory().iterator();
- this.constraints.updateFromFactHandle( workingMemory, handle );
+ this.constraints.updateFromFactHandle( workingMemory,
+ handle );
for ( ReteTuple tuple = (ReteTuple) it.next(); tuple != null; tuple = (ReteTuple) it.next() ) {
if ( this.constraints.isAllowedCachedRight( tuple ) ) {
- this.retractTuple( tuple, context, workingMemory );
- this.assertTuple( tuple, context, workingMemory );
+ this.retractTuple( tuple,
+ context,
+ workingMemory );
+ this.assertTuple( tuple,
+ context,
+ workingMemory );
}
}
}
@@ -223,9 +222,25 @@ public void assertObject(final InternalFactHandle handle,
public void retractObject(final InternalFactHandle handle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
+
final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this );
+ if ( !memory.getObjectMemory().remove( handle ) ) {
+ return;
+ }
- // FIXME
+ final Iterator it = memory.getTupleMemory().iterator();
+ this.constraints.updateFromFactHandle( workingMemory,
+ handle );
+ for ( ReteTuple tuple = (ReteTuple) it.next(); tuple != null; tuple = (ReteTuple) it.next() ) {
+ if ( this.constraints.isAllowedCachedRight( tuple ) ) {
+ this.retractTuple( tuple,
+ context,
+ workingMemory );
+ this.assertTuple( tuple,
+ context,
+ workingMemory );
+ }
+ }
}
public String toString() {
@@ -237,19 +252,12 @@ public void updateSink(TupleSink sink,
InternalWorkingMemory workingMemory) {
final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this );
- final Iterator tupleIter = memory.getTupleMemory().iterator();
- for ( ReteTuple tuple = (ReteTuple) tupleIter.next(); tuple != null; tuple = (ReteTuple) tupleIter.next() ) {
- final Iterator objectIter = memory.getObjectMemory().iterator( tuple );
- this.constraints.updateFromTuple( workingMemory, tuple );
- for ( FactEntry entry = (FactEntry) objectIter.next(); entry != null; entry = (FactEntry) objectIter.next() ) {
- final InternalFactHandle handle = entry.getFactHandle();
- if ( this.constraints.isAllowedCachedLeft( handle.getObject() ) ) {
- sink.assertTuple( new ReteTuple( tuple,
- handle ),
- context,
- workingMemory );
- }
- }
+ for ( java.util.Iterator it = memory.getCreatedHandles().entrySet().iterator(); it.hasNext(); ) {
+ Map.Entry entry = (Map.Entry) it.next();
+ sink.assertTuple( new ReteTuple( (ReteTuple)entry.getKey(),
+ (InternalFactHandle) entry.getValue()),
+ context,
+ workingMemory );
}
}
|
d9d3f68a390494af15e49060b7afd9924dbcbee1
|
kotlin
|
Drop JetClassObject element and its usages--as class objects are now represented by JetObjectDeclaration element-
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBodyCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBodyCodegen.java
index fcc1c54048206..1fd5dec89b76f 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBodyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBodyCodegen.java
@@ -99,9 +99,6 @@ else if (declaration instanceof JetClassOrObject) {
genClassOrObject((JetClassOrObject) declaration);
}
- else if (declaration instanceof JetClassObject) {
- genClassOrObject(((JetClassObject) declaration).getObjectDeclaration());
- }
}
private void generatePrimaryConstructorProperties(PropertyCodegen propertyCodegen, JetClassOrObject origin) {
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
index 6b89164c5665d..3a11a2f98a8bb 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
@@ -150,7 +150,7 @@ else if (jetClass.isEnum()) {
isStatic = !jetClass.isInner();
}
else {
- isStatic = myClass.getParent() instanceof JetClassObject;
+ isStatic = myClass instanceof JetObjectDeclaration && ((JetObjectDeclaration) myClass).isClassObject() ;
isFinal = true;
}
@@ -968,9 +968,9 @@ private void generateFieldForSingleton() {
fieldTypeDescriptor = descriptor;
}
else if (classObjectDescriptor != null) {
- JetClassObject classObject = ((JetClass) myClass).getClassObject();
+ JetObjectDeclaration classObject = ((JetClass) myClass).getClassObject();
assert classObject != null : "Class object not found: " + myClass.getText();
- original = classObject.getObjectDeclaration();
+ original = classObject;
fieldTypeDescriptor = classObjectDescriptor;
}
else {
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/binding/CodegenAnnotatingVisitor.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/binding/CodegenAnnotatingVisitor.java
index e6a744a51d702..4f0990a4c578c 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/binding/CodegenAnnotatingVisitor.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/binding/CodegenAnnotatingVisitor.java
@@ -207,46 +207,23 @@ public void visitEnumEntry(@NotNull JetEnumEntry enumEntry) {
}
@Override
- public void visitClassObject(@NotNull JetClassObject classObject) {
- ClassDescriptor classDescriptor = bindingContext.get(CLASS, classObject.getObjectDeclaration());
+ public void visitObjectDeclaration(@NotNull JetObjectDeclaration declaration) {
+ if (!filter.shouldProcessClass(declaration)) return;
- assert classDescriptor != null : String.format("No class found in binding context for: \n---\n%s\n---\n",
- JetPsiUtil.getElementTextWithContext(classObject));
+ ClassDescriptor classDescriptor = bindingContext.get(CLASS, declaration);
+ // working around a problem with shallow analysis
+ if (classDescriptor == null) return;
- //TODO_R: remove visitClassObject
String name = getName(classDescriptor);
recordClosure(classDescriptor, name);
classStack.push(classDescriptor);
nameStack.push(name);
- super.visitClassObject(classObject);
+ super.visitObjectDeclaration(declaration);
nameStack.pop();
classStack.pop();
}
- @Override
- public void visitObjectDeclaration(@NotNull JetObjectDeclaration declaration) {
- if (declaration.getParent() instanceof JetClassObject) {
- super.visitObjectDeclaration(declaration);
- }
- else {
- if (!filter.shouldProcessClass(declaration)) return;
-
- ClassDescriptor classDescriptor = bindingContext.get(CLASS, declaration);
- // working around a problem with shallow analysis
- if (classDescriptor == null) return;
-
- String name = getName(classDescriptor);
- recordClosure(classDescriptor, name);
-
- classStack.push(classDescriptor);
- nameStack.push(name);
- super.visitObjectDeclaration(declaration);
- nameStack.pop();
- classStack.pop();
- }
- }
-
@Override
public void visitClass(@NotNull JetClass klass) {
if (!filter.shouldProcessClass(klass)) return;
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/binding/PsiCodegenPredictor.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/binding/PsiCodegenPredictor.java
index e06ac2f4360b1..de0267dcbb49d 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/binding/PsiCodegenPredictor.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/binding/PsiCodegenPredictor.java
@@ -55,10 +55,6 @@ public static String getPredefinedJvmInternalName(@NotNull JetDeclaration declar
// TODO: Method won't give correct class name for traits implementations
JetDeclaration parentDeclaration = JetStubbedPsiUtil.getContainingDeclaration(declaration);
- if (parentDeclaration instanceof JetClassObject) {
- assert declaration instanceof JetObjectDeclaration : "Only object declarations can be children of JetClassObject: " + declaration;
- return getPredefinedJvmInternalName(parentDeclaration);
- }
String parentInternalName;
if (parentDeclaration != null) {
@@ -78,12 +74,6 @@ public static String getPredefinedJvmInternalName(@NotNull JetDeclaration declar
parentInternalName = AsmUtil.internalNameByFqNameWithoutInnerClasses(containingFile.getPackageFqName());
}
- if (declaration instanceof JetClassObject) {
- // Get parent and assign Class object prefix
- //TODO_R: getName() nullable
- return parentInternalName + "$" + ((JetClassObject) declaration).getObjectDeclaration().getName();
- }
-
if (!PsiTreeUtil.instanceOf(declaration, JetClass.class, JetObjectDeclaration.class, JetNamedFunction.class, JetProperty.class) ||
declaration instanceof JetEnumEntry) {
// Other subclasses are not valid for class name prediction.
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/JetNodeTypes.java b/compiler/frontend/src/org/jetbrains/kotlin/JetNodeTypes.java
index 7f730d0288ff0..3dc47f9843b55 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/JetNodeTypes.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/JetNodeTypes.java
@@ -35,7 +35,6 @@ public interface JetNodeTypes {
IElementType OBJECT_DECLARATION = JetStubElementTypes.OBJECT_DECLARATION;
JetNodeType OBJECT_DECLARATION_NAME = new JetNodeType("OBJECT_DECLARATION_NAME", JetObjectDeclarationName.class);
- IElementType CLASS_OBJECT = JetStubElementTypes.CLASS_OBJECT;
IElementType ENUM_ENTRY = JetStubElementTypes.ENUM_ENTRY;
IElementType ANONYMOUS_INITIALIZER = JetStubElementTypes.ANONYMOUS_INITIALIZER;
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
index 5ddce51d76c5c..b709ac255dd57 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
@@ -187,8 +187,8 @@ public interface Errors {
// Class objects
- DiagnosticFactory0<JetClassObject> MANY_CLASS_OBJECTS = DiagnosticFactory0.create(ERROR);
- DiagnosticFactory0<JetClassObject> CLASS_OBJECT_NOT_ALLOWED = DiagnosticFactory0.create(ERROR);
+ DiagnosticFactory0<JetObjectDeclaration> MANY_CLASS_OBJECTS = DiagnosticFactory0.create(ERROR);
+ DiagnosticFactory0<JetObjectDeclaration> CLASS_OBJECT_NOT_ALLOWED = DiagnosticFactory0.create(ERROR);
// Objects
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/PositioningStrategies.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/PositioningStrategies.kt
index 9d5ed884af233..6e7aedb33e7a6 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/PositioningStrategies.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/PositioningStrategies.kt
@@ -51,10 +51,11 @@ public object PositioningStrategies {
}
return markRange(objectKeyword, delegationSpecifierList)
}
- is JetClassObject -> {
- val classKeyword = element.getClassKeyword()
- val objectKeyword = element.getObjectDeclaration().getObjectKeyword()
- return markRange(classKeyword, objectKeyword)
+ is JetObjectDeclaration -> {
+ return markRange(
+ element.getClassKeyword() ?: element.getObjectKeyword(),
+ element.getNameIdentifier() ?: element.getObjectKeyword()
+ )
}
else -> {
return super.mark(element)
@@ -99,17 +100,7 @@ public object PositioningStrategies {
}
return markElement(nameIdentifier)
}
- if (element is JetObjectDeclaration) {
- val objectKeyword = element.getObjectKeyword()
- val parent = element.getParent()
- if (parent is JetClassObject) {
- val classKeyword = parent.getClassKeyword()
- val start = classKeyword ?: objectKeyword
- return markRange(start, objectKeyword)
- }
- return markElement(objectKeyword)
- }
- return super.mark(element)
+ return DEFAULT.mark(element)
}
}
@@ -240,7 +231,6 @@ public object PositioningStrategies {
is JetObjectDeclaration -> element.getObjectKeyword()
is JetPropertyAccessor -> element.getNamePlaceholder()
is JetClassInitializer -> element
- is JetClassObject -> element.getObjectDeclaration().getObjectKeyword()
else -> throw IllegalArgumentException(
"Can't find text range for element '${element.javaClass.getCanonicalName()}' with the text '${element.getText()}'")
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt
index 7048fec93d6f1..41d76c6ac573f 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt
@@ -188,11 +188,6 @@ private object DebugTextBuildingVisitor : JetVisitor<String, Unit>() {
return "initializer in " + (containingDeclaration?.getDebugText() ?: "...")
}
- override fun visitClassObject(classObject: JetClassObject, data: Unit?): String? {
- val containingDeclaration = JetStubbedPsiUtil.getContainingDeclaration(classObject)
- return "class object in " + (containingDeclaration?.getDebugText() ?: "...")
- }
-
override fun visitClassBody(classBody: JetClassBody, data: Unit?): String? {
val containingDeclaration = JetStubbedPsiUtil.getContainingDeclaration(classBody)
return "class body for " + (containingDeclaration?.getDebugText() ?: "...")
@@ -242,6 +237,9 @@ private object DebugTextBuildingVisitor : JetVisitor<String, Unit>() {
return buildText {
append("STUB: ")
appendInn(declaration.getModifierList(), suffix = " ")
+ if (declaration.isClassObject()) {
+ append("class ")
+ }
append("object ")
appendInn(declaration.getNameAsName())
appendInn(declaration.getDelegationSpecifierList(), prefix = " : ")
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClass.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClass.java
index b20663c7f4a78..f39b07909eb9c 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClass.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClass.java
@@ -142,7 +142,7 @@ public JetClassBody getBody() {
}
@Nullable
- public JetClassObject getClassObject() {
+ public JetObjectDeclaration getClassObject() {
JetClassBody body = getBody();
if (body == null) return null;
return body.getClassObject();
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClassBody.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClassBody.java
index 759a165ce24b8..07f8a0767c695 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClassBody.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClassBody.java
@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.psi;
+import com.google.common.collect.Lists;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
@@ -31,6 +32,7 @@
import java.util.Arrays;
import java.util.List;
+import static kotlin.KotlinPackage.firstOrNull;
import static org.jetbrains.kotlin.psi.stubs.elements.JetStubElementTypes.*;
public class JetClassBody extends JetElementImplStub<KotlinPlaceHolderStub<JetClassBody>> implements JetDeclarationContainer {
@@ -65,13 +67,19 @@ public List<JetProperty> getProperties() {
}
@Nullable
- public JetClassObject getClassObject() {
- return getStubOrPsiChild(CLASS_OBJECT);
+ public JetObjectDeclaration getClassObject() {
+ return firstOrNull(getAllClassObjects());
}
@NotNull
- public List<JetClassObject> getAllClassObjects() {
- return getStubOrPsiChildrenAsList(JetStubElementTypes.CLASS_OBJECT);
+ public List<JetObjectDeclaration> getAllClassObjects() {
+ List<JetObjectDeclaration> result = Lists.newArrayList();
+ for (JetObjectDeclaration declaration : getStubOrPsiChildrenAsList(JetStubElementTypes.OBJECT_DECLARATION)) {
+ if (declaration.isClassObject()) {
+ result.add(declaration);
+ }
+ }
+ return result;
}
@Nullable
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClassObject.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClassObject.java
deleted file mode 100644
index 3156e5f8c703a..0000000000000
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetClassObject.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2010-2015 JetBrains s.r.o.
- *
- * 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.jetbrains.kotlin.psi;
-
-import com.intellij.lang.ASTNode;
-import com.intellij.psi.PsiElement;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.kotlin.lexer.JetTokens;
-import org.jetbrains.kotlin.psi.stubs.KotlinPlaceHolderStub;
-import org.jetbrains.kotlin.psi.stubs.elements.JetStubElementTypes;
-
-public class JetClassObject extends JetDeclarationStub<KotlinPlaceHolderStub<JetClassObject>> implements JetStatementExpression {
- public JetClassObject(@NotNull ASTNode node) {
- super(node);
- }
-
- public JetClassObject(@NotNull KotlinPlaceHolderStub<JetClassObject> stub) {
- super(stub, JetStubElementTypes.CLASS_OBJECT);
- }
-
- @Override
- public <R, D> R accept(@NotNull JetVisitor<R, D> visitor, D data) {
- return visitor.visitClassObject(this, data);
- }
-
- @NotNull
- public JetObjectDeclaration getObjectDeclaration() {
- return getRequiredStubOrPsiChild(JetStubElementTypes.OBJECT_DECLARATION);
- }
-
- @NotNull
- public PsiElement getClassKeyword() {
- return findChildByType(JetTokens.CLASS_KEYWORD);
- }
-}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetNamedDeclarationUtil.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetNamedDeclarationUtil.java
index cdc4e726f062e..afa4d338a2f13 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetNamedDeclarationUtil.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetNamedDeclarationUtil.java
@@ -51,9 +51,6 @@ public static FqNameUnsafe getUnsafeFQName(@NotNull JetNamedDeclaration namedDec
@Nullable
public static FqName getParentFqName(@NotNull JetNamedDeclaration namedDeclaration) {
PsiElement parent = namedDeclaration.getParent();
- if (parent instanceof JetClassObject) {
- parent = parent.getParent();
- }
if (parent instanceof JetClassBody) {
// One nesting to JetClassBody doesn't affect to qualified name
parent = parent.getParent();
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetPsiFactory.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetPsiFactory.kt
index 618d439861e64..2747248114292 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetPsiFactory.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetPsiFactory.kt
@@ -645,10 +645,6 @@ public class JetPsiFactory(private val project: Project) {
return createFunction("fun foo() {\n" + bodyText + "\n}").getBodyExpression() as JetBlockExpression
}
- public fun createEmptyClassObject(): JetClassObject {
- return createClass("class foo { class object { } }").getClassObject()!!
- }
-
public fun createComment(text: String): PsiComment {
val file = createFile(text)
val comments = file.getChildren().filterIsInstance<PsiComment>()
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetPsiUtil.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetPsiUtil.java
index 24af2ab33c7cb..85deec9989271 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetPsiUtil.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetPsiUtil.java
@@ -431,11 +431,6 @@ public static JetClassOrObject getOutermostClassOrObject(@NotNull JetClassOrObje
if (parent instanceof PsiFile) {
return current;
}
- if (parent instanceof JetClassObject) {
- // current class IS the class object declaration
- parent = parent.getParent();
- assert parent instanceof JetClassBody : "Parent of class object is not a class body: " + parent;
- }
if (!(parent instanceof JetClassBody)) {
// It is a local class, no legitimate outer
return current;
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java
index 9d387a55a3651..79cf79de17d28 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java
@@ -33,10 +33,6 @@ public R visitClass(@NotNull JetClass klass, D data) {
return visitNamedDeclaration(klass, data);
}
- public R visitClassObject(@NotNull JetClassObject classObject, D data) {
- return visitDeclaration(classObject, data);
- }
-
public R visitNamedFunction(@NotNull JetNamedFunction function, D data) {
return visitNamedDeclaration(function, data);
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java
index 5a31d91f91c91..289cfd2370d24 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java
@@ -33,10 +33,6 @@ public void visitClass(@NotNull JetClass klass) {
super.visitClass(klass, null);
}
- public void visitClassObject(@NotNull JetClassObject classObject) {
- super.visitClassObject(classObject, null);
- }
-
public void visitNamedFunction(@NotNull JetNamedFunction function) {
super.visitNamedFunction(function, null);
}
@@ -436,12 +432,6 @@ public final Void visitClass(@NotNull JetClass klass, Void data) {
return null;
}
- @Override
- public final Void visitClassObject(@NotNull JetClassObject classObject, Void data) {
- visitClassObject(classObject);
- return null;
- }
-
@Override
public final Void visitNamedFunction(@NotNull JetNamedFunction function, Void data) {
visitNamedFunction(function);
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoidWithParameter.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoidWithParameter.java
index 4011f0a8fdcf3..bc086241de6a4 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoidWithParameter.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoidWithParameter.java
@@ -34,10 +34,6 @@ public void visitClassVoid(@NotNull JetClass klass, P data) {
super.visitClass(klass, data);
}
- public void visitClassObjectVoid(@NotNull JetClassObject classObject, P data) {
- super.visitClassObject(classObject, data);
- }
-
public void visitNamedFunctionVoid(@NotNull JetNamedFunction function, P data) {
super.visitNamedFunction(function, data);
}
@@ -433,12 +429,6 @@ public final Void visitClass(@NotNull JetClass klass, P data) {
return null;
}
- @Override
- public final Void visitClassObject(@NotNull JetClassObject classObject, P data) {
- visitClassObjectVoid(classObject, data);
- return null;
- }
-
@Override
public final Void visitNamedFunction(@NotNull JetNamedFunction function, P data) {
visitNamedFunctionVoid(function, data);
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/JetObjectElementType.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/JetObjectElementType.java
index 144f5499baa9c..82cd27d33a46a 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/JetObjectElementType.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/JetObjectElementType.java
@@ -24,7 +24,6 @@
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.name.FqName;
-import org.jetbrains.kotlin.psi.JetClassObject;
import org.jetbrains.kotlin.psi.JetObjectDeclaration;
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilPackage;
import org.jetbrains.kotlin.psi.stubs.KotlinObjectStub;
@@ -46,7 +45,7 @@ public KotlinObjectStub createStub(@NotNull JetObjectDeclaration psi, StubElemen
FqName fqName = ResolveSessionUtils.safeFqNameForLazyResolve(psi);
List<String> superNames = PsiUtilPackage.getSuperNames(psi);
return new KotlinObjectStubImpl(parentStub, StringRef.fromString(name), fqName, Utils.INSTANCE$.wrapStrings(superNames),
- psi.isTopLevel(), isClassObject(psi), psi.isLocal(), psi.isObjectLiteral());
+ psi.isTopLevel(), psi.isClassObject(), psi.isLocal(), psi.isObjectLiteral());
}
@Override
@@ -93,8 +92,4 @@ public KotlinObjectStub deserialize(@NotNull StubInputStream dataStream, StubEle
public void indexStub(@NotNull KotlinObjectStub stub, @NotNull IndexSink sink) {
StubIndexServiceFactory.getInstance().indexObject(stub, sink);
}
-
- private static boolean isClassObject(@NotNull JetObjectDeclaration objectDeclaration) {
- return objectDeclaration.getParent() instanceof JetClassObject;
- }
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/JetStubElementTypes.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/JetStubElementTypes.java
index 8bed79d669d33..eba0047c572a7 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/JetStubElementTypes.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/JetStubElementTypes.java
@@ -31,8 +31,6 @@ public interface JetStubElementTypes {
JetClassElementType ENUM_ENTRY = new JetClassElementType("ENUM_ENTRY");
JetObjectElementType OBJECT_DECLARATION = new JetObjectElementType("OBJECT_DECLARATION");
- JetPlaceHolderStubElementType<JetClassObject> CLASS_OBJECT =
- new JetPlaceHolderStubElementType<JetClassObject>("CLASS_OBJECT", JetClassObject.class);
JetPlaceHolderStubElementType<JetClassInitializer> ANONYMOUS_INITIALIZER =
new JetPlaceHolderStubElementType<JetClassInitializer>("ANONYMOUS_INITIALIZER", JetClassInitializer.class);
@@ -115,7 +113,7 @@ public interface JetStubElementTypes {
new JetPlaceHolderStubElementType<JetConstructorCalleeExpression>("CONSTRUCTOR_CALLEE", JetConstructorCalleeExpression.class);
TokenSet DECLARATION_TYPES =
- TokenSet.create(CLASS, OBJECT_DECLARATION, CLASS_OBJECT, FUNCTION, PROPERTY, ANONYMOUS_INITIALIZER, ENUM_ENTRY);
+ TokenSet.create(CLASS, OBJECT_DECLARATION, FUNCTION, PROPERTY, ANONYMOUS_INITIALIZER, ENUM_ENTRY);
TokenSet DELEGATION_SPECIFIER_TYPES = TokenSet.create(DELEGATOR_BY, DELEGATOR_SUPER_CALL, DELEGATOR_SUPER_CLASS, THIS_CALL);
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.java
index 174de2faaa9a8..693f292281975 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.java
@@ -199,9 +199,9 @@ private void checkManyClassObjects(JetClassOrObject classOrObject) {
for (JetDeclaration jetDeclaration : classOrObject.getDeclarations()) {
jetDeclaration.accept(this);
- if (jetDeclaration instanceof JetClassObject) {
+ if (jetDeclaration instanceof JetObjectDeclaration && ((JetObjectDeclaration) jetDeclaration).isClassObject()) {
if (classObjectAlreadyFound) {
- trace.report(MANY_CLASS_OBJECTS.on((JetClassObject) jetDeclaration));
+ trace.report(MANY_CLASS_OBJECTS.on((JetObjectDeclaration) jetDeclaration));
}
classObjectAlreadyFound = true;
}
@@ -226,11 +226,6 @@ private void registerPrimaryConstructorParameters(@NotNull JetClass klass) {
}
}
- @Override
- public void visitClassObject(@NotNull JetClassObject classObject) {
- visitClassOrObject(classObject.getObjectDeclaration());
- }
-
@Override
public void visitEnumEntry(@NotNull JetEnumEntry enumEntry) {
visitClassOrObject(enumEntry);
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ModifiersChecker.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ModifiersChecker.java
index c696b2d377983..abc640b8fa1a6 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ModifiersChecker.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ModifiersChecker.java
@@ -171,7 +171,7 @@ private void checkModalityModifiers(@NotNull JetModifierListOwner modifierListOw
checkCompatibility(modifierList, Arrays.asList(ABSTRACT_KEYWORD, OPEN_KEYWORD, FINAL_KEYWORD),
Arrays.asList(ABSTRACT_KEYWORD, OPEN_KEYWORD));
- if (modifierListOwner.getParent() instanceof JetClassObject || modifierListOwner instanceof JetObjectDeclaration) {
+ if (modifierListOwner instanceof JetObjectDeclaration) {
checkIllegalModalityModifiers(modifierListOwner);
}
else if (modifierListOwner instanceof JetClassOrObject) {
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/DeclarationScopeProviderImpl.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/DeclarationScopeProviderImpl.java
index abe23c0359807..ae18ed7ded8e5 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/DeclarationScopeProviderImpl.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/DeclarationScopeProviderImpl.java
@@ -68,16 +68,6 @@ public JetScope getResolutionScopeForDeclaration(@NotNull PsiElement elementOfDe
return classDescriptor.getScopeForMemberDeclarationResolution();
}
- if (parentDeclaration instanceof JetClassObject) {
- assert jetDeclaration instanceof JetObjectDeclaration : "Should be situation for getting scope for object in class [object {...}]";
-
- JetClassObject classObject = (JetClassObject) parentDeclaration;
- LazyClassDescriptor classObjectDescriptor =
- (LazyClassDescriptor) lazyDeclarationResolver.getClassObjectDescriptor(classObject).getContainingDeclaration();
-
- return classObjectDescriptor.getScopeForMemberDeclarationResolution();
- }
-
throw new IllegalStateException("Don't call this method for local declarations: " + jetDeclaration + "\n" +
JetPsiUtil.getElementTextWithContext(jetDeclaration));
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyDeclarationResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyDeclarationResolver.java
index c35a346e0cfb1..ea126f9accc6d 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyDeclarationResolver.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyDeclarationResolver.java
@@ -27,7 +27,6 @@
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.BindingTrace;
-import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor;
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor;
import org.jetbrains.kotlin.resolve.scopes.JetScope;
import org.jetbrains.kotlin.storage.LockBasedLazyResolveStorageManager;
@@ -65,13 +64,6 @@ public LazyDeclarationResolver(
@NotNull
public ClassDescriptor getClassDescriptor(@NotNull JetClassOrObject classOrObject) {
- if (classOrObject instanceof JetObjectDeclaration) {
- JetObjectDeclaration objectDeclaration = (JetObjectDeclaration) classOrObject;
- JetClassObject classObjectElement = objectDeclaration.getClassObjectElement();
- if (classObjectElement != null) {
- return getClassObjectDescriptor(classObjectElement);
- }
- }
JetScope resolutionScope = resolutionScopeToResolveDeclaration(classOrObject);
// Why not use the result here. Because it may be that there is a redeclaration:
@@ -93,31 +85,6 @@ public ClassDescriptor getClassDescriptor(@NotNull JetClassOrObject classOrObjec
return (ClassDescriptor) descriptor;
}
- @NotNull
- /*package*/ LazyClassDescriptor getClassObjectDescriptor(@NotNull JetClassObject classObject) {
- JetClass aClass = JetStubbedPsiUtil.getContainingDeclaration(classObject, JetClass.class);
-
- LazyClassDescriptor parentClassDescriptor;
-
- if (aClass != null) {
- parentClassDescriptor = (LazyClassDescriptor) getClassDescriptor(aClass);
- }
- else {
- // Class object in object is an error but we want to find descriptors even for this case
- JetObjectDeclaration objectDeclaration = PsiTreeUtil.getParentOfType(classObject, JetObjectDeclaration.class);
- assert objectDeclaration != null : String.format("Class object %s can be in class or object in file %s", classObject, classObject.getContainingFile().getText());
- parentClassDescriptor = (LazyClassDescriptor) getClassDescriptor(objectDeclaration);
- }
-
- // Activate resolution and writing to trace
- parentClassDescriptor.getClassObjectDescriptor();
- parentClassDescriptor.getDescriptorsForExtraClassObjects();
- DeclarationDescriptor classObjectDescriptor = getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, classObject.getObjectDeclaration());
- assert classObjectDescriptor != null : "No descriptor found for " + JetPsiUtil.getElementTextWithContext(classObject);
-
- return (LazyClassDescriptor) classObjectDescriptor;
- }
-
@NotNull
private BindingContext getBindingContext() {
return trace.getBindingContext();
@@ -133,19 +100,9 @@ public DeclarationDescriptor visitClass(@NotNull JetClass klass, Void data) {
@Override
public DeclarationDescriptor visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, Void data) {
- PsiElement parent = declaration.getParent();
- if (parent instanceof JetClassObject) {
- JetClassObject jetClassObject = (JetClassObject) parent;
- return resolveToDescriptor(jetClassObject);
- }
return getClassDescriptor(declaration);
}
- @Override
- public DeclarationDescriptor visitClassObject(@NotNull JetClassObject classObject, Void data) {
- return getClassObjectDescriptor(classObject);
- }
-
@Override
public DeclarationDescriptor visitTypeParameter(@NotNull JetTypeParameter parameter, Void data) {
JetTypeParameterListOwner ownerElement = PsiTreeUtil.getParentOfType(parameter, JetTypeParameterListOwner.class);
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassInfo.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassInfo.java
index bbbc86c5d656e..a4028be51417f 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassInfo.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassInfo.java
@@ -46,7 +46,7 @@ else if (element.isEnum()) {
}
@Override
- public JetClassObject getClassObject() {
+ public JetObjectDeclaration getClassObject() {
return element.getClassObject();
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassLikeInfo.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassLikeInfo.java
index 71cc9d4d068c4..9c10c34b58df5 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassLikeInfo.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassLikeInfo.java
@@ -21,8 +21,8 @@
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.ReadOnly;
import org.jetbrains.kotlin.descriptors.ClassKind;
-import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.name.FqName;
+import org.jetbrains.kotlin.psi.*;
import java.util.List;
@@ -34,11 +34,11 @@ public interface JetClassLikeInfo extends JetDeclarationContainer {
JetModifierList getModifierList();
@Nullable
- JetClassObject getClassObject();
+ JetObjectDeclaration getClassObject();
@NotNull
@ReadOnly
- List<JetClassObject> getClassObjects();
+ List<JetObjectDeclaration> getClassObjects();
// This element is used to identify resolution scope for the class
@NotNull
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassOrObjectInfo.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassOrObjectInfo.java
index 2001283c1c79a..93e12041d6b0b 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassOrObjectInfo.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetClassOrObjectInfo.java
@@ -58,7 +58,7 @@ public List<JetDeclaration> getDeclarations() {
@NotNull
@Override
- public List<JetClassObject> getClassObjects() {
+ public List<JetObjectDeclaration> getClassObjects() {
JetClassBody body = element.getBody();
if (body == null) {
return Collections.emptyList();
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetObjectInfo.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetObjectInfo.java
index d68b8f57abefd..60266d5046e5b 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetObjectInfo.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetObjectInfo.java
@@ -19,7 +19,6 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.ClassKind;
-import org.jetbrains.kotlin.psi.JetClassObject;
import org.jetbrains.kotlin.psi.JetObjectDeclaration;
import org.jetbrains.kotlin.psi.JetParameter;
import org.jetbrains.kotlin.psi.JetTypeParameterList;
@@ -39,7 +38,7 @@ protected JetObjectInfo(@NotNull JetObjectDeclaration element) {
}
@Override
- public JetClassObject getClassObject() {
+ public JetObjectDeclaration getClassObject() {
return null;
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetScriptInfo.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetScriptInfo.kt
index 96fa7ecad50df..9e023b4165590 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetScriptInfo.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/JetScriptInfo.kt
@@ -28,7 +28,7 @@ public class JetScriptInfo(
override fun getContainingPackageFqName() = fqName.parent()
override fun getModifierList() = null
override fun getClassObject() = null
- override fun getClassObjects() = listOf<JetClassObject>()
+ override fun getClassObjects() = listOf<JetObjectDeclaration>()
override fun getScopeAnchor() = script
override fun getCorrespondingClassOrObject() = null
override fun getTypeParameterList() = null
@@ -44,5 +44,5 @@ public fun shouldBeScriptClassMember(declaration: JetDeclaration): Boolean {
// we only add those vals, vars and funs that have explicitly specified return types
// (or implicit Unit for function with block body)
return declaration is JetCallableDeclaration && declaration.getTypeReference() != null
- || declaration is JetNamedFunction && declaration.hasBlockBody()
+ || declaration is JetNamedFunction && declaration.hasBlockBody()
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/PsiBasedClassMemberDeclarationProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/PsiBasedClassMemberDeclarationProvider.kt
index e8caeb8367240..ad22909fc45f7 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/PsiBasedClassMemberDeclarationProvider.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/PsiBasedClassMemberDeclarationProvider.kt
@@ -29,12 +29,7 @@ public class PsiBasedClassMemberDeclarationProvider(
override fun doCreateIndex(index: AbstractPsiBasedDeclarationProvider.Index) {
for (declaration in classInfo.getDeclarations()) {
- if (declaration !is JetClassObject) {
- index.putToIndex(declaration)
- }
- else {
- index.putToIndex(declaration.getObjectDeclaration())
- }
+ index.putToIndex(declaration)
}
for (parameter in classInfo.getPrimaryConstructorParameters()) {
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java
index 6bb0ad2355c88..81d02caf9367e 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java
@@ -83,7 +83,7 @@ public boolean apply(JetType type) {
private final Annotations annotations;
private final Annotations danglingAnnotations;
private final NullableLazyValue<LazyClassDescriptor> classObjectDescriptor;
- private final MemoizedFunctionToNotNull<JetClassObject, ClassDescriptor> extraClassObjectDescriptors;
+ private final MemoizedFunctionToNotNull<JetObjectDeclaration, ClassDescriptor> extraClassObjectDescriptors;
private final LazyClassMemberScope unsubstitutedMemberScope;
private final JetScope staticScope = new StaticScopeForKotlinClass(this);
@@ -186,9 +186,9 @@ public LazyClassDescriptor invoke() {
return computeClassObjectDescriptor(getClassObjectIfAllowed());
}
});
- this.extraClassObjectDescriptors = storageManager.createMemoizedFunction(new Function1<JetClassObject, ClassDescriptor>() {
+ this.extraClassObjectDescriptors = storageManager.createMemoizedFunction(new Function1<JetObjectDeclaration, ClassDescriptor>() {
@Override
- public ClassDescriptor invoke(JetClassObject classObject) {
+ public ClassDescriptor invoke(JetObjectDeclaration classObject) {
return computeClassObjectDescriptor(classObject);
}
});
@@ -357,21 +357,21 @@ public LazyClassDescriptor getClassObjectDescriptor() {
@NotNull
@ReadOnly
public List<ClassDescriptor> getDescriptorsForExtraClassObjects() {
- final JetClassObject allowedClassObject = getClassObjectIfAllowed();
+ final JetObjectDeclaration allowedClassObject = getClassObjectIfAllowed();
return KotlinPackage.map(
KotlinPackage.filter(
declarationProvider.getOwnerInfo().getClassObjects(),
- new Function1<JetClassObject, Boolean>() {
+ new Function1<JetObjectDeclaration, Boolean>() {
@Override
- public Boolean invoke(JetClassObject classObject) {
+ public Boolean invoke(JetObjectDeclaration classObject) {
return classObject != allowedClassObject;
}
}
),
- new Function1<JetClassObject, ClassDescriptor>() {
+ new Function1<JetObjectDeclaration, ClassDescriptor>() {
@Override
- public ClassDescriptor invoke(JetClassObject classObject) {
+ public ClassDescriptor invoke(JetObjectDeclaration classObject) {
return extraClassObjectDescriptors.invoke(classObject);
}
}
@@ -379,7 +379,7 @@ public ClassDescriptor invoke(JetClassObject classObject) {
}
@Nullable
- private LazyClassDescriptor computeClassObjectDescriptor(@Nullable JetClassObject classObject) {
+ private LazyClassDescriptor computeClassObjectDescriptor(@Nullable JetObjectDeclaration classObject) {
JetClassLikeInfo classObjectInfo = getClassObjectInfo(classObject);
if (classObjectInfo instanceof JetClassOrObjectInfo) {
Name name = ((JetClassOrObjectInfo) classObjectInfo).getName();
@@ -404,21 +404,21 @@ private LazyClassDescriptor computeClassObjectDescriptor(@Nullable JetClassObjec
}
@Nullable
- private JetClassLikeInfo getClassObjectInfo(@Nullable JetClassObject classObject) {
+ private JetClassLikeInfo getClassObjectInfo(@Nullable JetObjectDeclaration classObject) {
if (classObject != null) {
if (!isClassObjectAllowed()) {
c.getTrace().report(CLASS_OBJECT_NOT_ALLOWED.on(classObject));
}
- return JetClassInfoUtil.createClassLikeInfo(classObject.getObjectDeclaration());
+ return JetClassInfoUtil.createClassLikeInfo(classObject);
}
return null;
}
@Nullable
- private JetClassObject getClassObjectIfAllowed() {
- JetClassObject classObject = declarationProvider.getOwnerInfo().getClassObject();
+ private JetObjectDeclaration getClassObjectIfAllowed() {
+ JetObjectDeclaration classObject = declarationProvider.getOwnerInfo().getClassObject();
return (classObject != null && isClassObjectAllowed()) ? classObject : null;
}
diff --git a/compiler/tests/org/jetbrains/kotlin/renderer/AbstractDescriptorRendererTest.kt b/compiler/tests/org/jetbrains/kotlin/renderer/AbstractDescriptorRendererTest.kt
index 1d7ec94365c3c..c72a8efff2aac 100644
--- a/compiler/tests/org/jetbrains/kotlin/renderer/AbstractDescriptorRendererTest.kt
+++ b/compiler/tests/org/jetbrains/kotlin/renderer/AbstractDescriptorRendererTest.kt
@@ -71,10 +71,6 @@ public abstract class AbstractDescriptorRendererTest : KotlinTestWithEnvironment
file.acceptChildren(this)
}
- override fun visitClassObject(classObject: JetClassObject) {
- classObject.acceptChildren(this)
- }
-
override fun visitParameter(parameter: JetParameter) {
val declaringElement = parameter.getParent().getParent()
when (declaringElement) {
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetIconProvider.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetIconProvider.java
index 34449055df625..fbc6287820714 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetIconProvider.java
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetIconProvider.java
@@ -155,7 +155,7 @@ public static Icon getBaseIcon(PsiElement psiElement) {
}
return icon;
}
- if (psiElement instanceof JetObjectDeclaration || psiElement instanceof JetClassObject) {
+ if (psiElement instanceof JetObjectDeclaration) {
return JetIcons.OBJECT;
}
if (psiElement instanceof JetParameter) {
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/JetSourceNavigationHelper.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/JetSourceNavigationHelper.java
index 954583cd8f142..9d085903b89ec 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/JetSourceNavigationHelper.java
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/JetSourceNavigationHelper.java
@@ -29,7 +29,6 @@
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.stubs.StringStubIndexExtension;
-import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import kotlin.KotlinPackage;
@@ -80,30 +79,9 @@ private JetSourceNavigationHelper() {
@Nullable
public static JetClassOrObject getSourceClassOrObject(@NotNull JetClassOrObject decompiledClassOrObject) {
- if (decompiledClassOrObject instanceof JetObjectDeclaration && decompiledClassOrObject.getParent() instanceof JetClassObject) {
- return getSourceClassObject((JetClassObject) decompiledClassOrObject.getParent());
- }
return getSourceForNamedClassOrObject(decompiledClassOrObject);
}
- private static JetClassOrObject getSourceClassObject(JetClassObject decompiledClassObject) {
- JetClass decompiledClass = PsiTreeUtil.getParentOfType(decompiledClassObject, JetClass.class);
- assert decompiledClass != null;
-
- JetClass sourceClass = (JetClass) getSourceForNamedClassOrObject(decompiledClass);
- if (sourceClass == null) {
- return null;
- }
-
- if (sourceClass.hasModifier(JetTokens.ENUM_KEYWORD)) {
- return sourceClass;
- }
-
- JetClassObject classObject = sourceClass.getClassObject();
- assert classObject != null;
- return classObject.getObjectDeclaration();
- }
-
@NotNull
private static GlobalSearchScope createLibrarySourcesScope(@NotNull JetNamedDeclaration decompiledDeclaration) {
JetFile containingFile = decompiledDeclaration.getContainingJetFile();
@@ -458,11 +436,6 @@ public JetDeclaration visitObjectDeclaration(@NotNull JetObjectDeclaration decla
return getSourceClassOrObject(declaration);
}
- @Override
- public JetDeclaration visitClassObject(@NotNull JetClassObject classObject, Void data) {
- return getSourceClassObject(classObject);
- }
-
@Override
public JetDeclaration visitClass(@NotNull JetClass klass, Void data) {
return getSourceClassOrObject(klass);
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClassClsStubBuilder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClassClsStubBuilder.kt
index 06cd4df8e9ace..b60db677e847c 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClassClsStubBuilder.kt
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClassClsStubBuilder.kt
@@ -31,7 +31,6 @@ import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.psi.JetDelegationSpecifierList
import org.jetbrains.kotlin.psi.JetDelegatorToSuperClass
import org.jetbrains.kotlin.lexer.JetTokens
-import org.jetbrains.kotlin.psi.JetClassObject
import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer
import org.jetbrains.kotlin.psi.stubs.impl.KotlinModifierListStubImpl
import org.jetbrains.kotlin.lexer.JetModifierKeywordToken
@@ -80,20 +79,10 @@ private class ClassClsStubBuilder(
}
private fun createClassOrObjectStubAndModifierListStub(): StubElement<out PsiElement> {
- val isClassObject = classKind == ProtoBuf.Class.Kind.CLASS_OBJECT
- if (isClassObject) {
- val classObjectStub = KotlinPlaceHolderStubImpl<JetClassObject>(parentStub, JetStubElementTypes.CLASS_OBJECT)
- val modifierList = createModifierListForClass(classObjectStub)
- val objectDeclarationStub = doCreateClassOrObjectStub(classObjectStub)
- createAnnotationStubs(c.components.annotationLoader.loadClassAnnotations(classProto, c.nameResolver), modifierList)
- return objectDeclarationStub
- }
- else {
- val classOrObjectStub = doCreateClassOrObjectStub(parentStub)
- val modifierList = createModifierListForClass(classOrObjectStub)
- createAnnotationStubs(c.components.annotationLoader.loadClassAnnotations(classProto, c.nameResolver), modifierList)
- return classOrObjectStub
- }
+ val classOrObjectStub = doCreateClassOrObjectStub()
+ val modifierList = createModifierListForClass(classOrObjectStub)
+ createAnnotationStubs(c.components.annotationLoader.loadClassAnnotations(classProto, c.nameResolver), modifierList)
+ return classOrObjectStub
}
private fun createModifierListForClass(parent: StubElement<out PsiElement>): KotlinModifierListStubImpl {
@@ -110,7 +99,7 @@ private class ClassClsStubBuilder(
return createModifierListStubForDeclaration(parent, classProto.getFlags(), relevantFlags, additionalModifiers)
}
- private fun doCreateClassOrObjectStub(parent: StubElement<out PsiElement>): StubElement<out PsiElement> {
+ private fun doCreateClassOrObjectStub(): StubElement<out PsiElement> {
val isClassObject = classKind == ProtoBuf.Class.Kind.CLASS_OBJECT
val fqName = outerContext.memberFqNameProvider.getMemberFqName(classId.getRelativeClassName().shortName())
val shortName = fqName.shortName()?.ref()
@@ -121,7 +110,7 @@ private class ClassClsStubBuilder(
return when (classKind) {
ProtoBuf.Class.Kind.OBJECT, ProtoBuf.Class.Kind.CLASS_OBJECT -> {
KotlinObjectStubImpl(
- parent, shortName, fqName, superTypeRefs,
+ parentStub, shortName, fqName, superTypeRefs,
isTopLevel = classId.isTopLevelClass(),
isClassObject = isClassObject,
isLocal = false,
@@ -131,7 +120,7 @@ private class ClassClsStubBuilder(
else -> {
KotlinClassStubImpl(
JetClassElementType.getStubType(classKind == ProtoBuf.Class.Kind.ENUM_ENTRY),
- parent,
+ parentStub,
fqName.ref(),
shortName,
superTypeRefs,
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt
index 80c79f25a62fb..e0e6ea1cb9a38 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt
@@ -85,9 +85,6 @@ private object DeclarationKindDetector : JetVisitor<AnnotationHostKind?, Unit?>(
override fun visitClass(d: JetClass, _: Unit?) = detect(d, if (d.isTrait()) "trait" else "class")
- override fun visitClassObject(d: JetClassObject, _: Unit?) = detect(d, "class object",
- name = "of " + d.getStrictParentOfType<JetClass>()?.getName())
-
override fun visitNamedFunction(d: JetNamedFunction, _: Unit?) = detect(d, "fun")
override fun visitProperty(d: JetProperty, _: Unit?) = detect(d, d.getValOrVarNode().getText()!!)
@@ -102,7 +99,7 @@ private object DeclarationKindDetector : JetVisitor<AnnotationHostKind?, Unit?>(
override fun visitParameter(d: JetParameter, _: Unit?) = detect(d, "parameter", newLineNeeded = false)
override fun visitObjectDeclaration(d: JetObjectDeclaration, _: Unit?): AnnotationHostKind? {
- if (d.getParent() is JetClassObject) return null
+ if (d.isClassObject()) return detect(d, "class object", name = "${d.getName()} of ${d.getStrictParentOfType<JetClass>()?.getName()}")
if (d.getParent() is JetObjectLiteralExpression) return null
return detect(d, "object")
}
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/structureView/JetStructureViewElement.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/structureView/JetStructureViewElement.java
index 414faec45f59c..7e9b74b066e6f 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/structureView/JetStructureViewElement.java
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/structureView/JetStructureViewElement.java
@@ -166,10 +166,6 @@ else if (element instanceof JetClass) {
else if (element instanceof JetClassOrObject) {
return ((JetClassOrObject) element).getDeclarations();
}
- else if (element instanceof JetClassObject) {
- JetObjectDeclaration objectDeclaration = ((JetClassObject) element).getObjectDeclaration();
- return objectDeclaration.getDeclarations();
- }
return Collections.emptyList();
}
diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInsight/upDownMover/JetDeclarationMover.java b/idea/src/org/jetbrains/kotlin/idea/codeInsight/upDownMover/JetDeclarationMover.java
index 67eaaba358378..085902e24fcad 100644
--- a/idea/src/org/jetbrains/kotlin/idea/codeInsight/upDownMover/JetDeclarationMover.java
+++ b/idea/src/org/jetbrains/kotlin/idea/codeInsight/upDownMover/JetDeclarationMover.java
@@ -60,8 +60,10 @@ public void visitAnonymousInitializer(@NotNull JetClassInitializer initializer)
}
@Override
- public void visitClassObject(@NotNull JetClassObject classObject) {
- memberSuspects.add(classObject.getClassKeyword());
+ public void visitObjectDeclaration(@NotNull JetObjectDeclaration declaration) {
+ if (declaration.isClassObject()) {
+ memberSuspects.add(declaration.getClassKeyword());
+ }
}
@Override
diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/extractFunctionForDebuggerUtil.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/extractFunctionForDebuggerUtil.kt
index 8cfa6e61d15a7..be9de56bb587a 100644
--- a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/extractFunctionForDebuggerUtil.kt
+++ b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/extractFunctionForDebuggerUtil.kt
@@ -193,9 +193,6 @@ private fun addDebugExpressionBeforeContextElement(codeFragment: JetCodeFragment
contextElement is JetClassOrObject -> {
insertNewInitializer(contextElement.getBody())
}
- contextElement is JetClassObject -> {
- insertNewInitializer(contextElement.getObjectDeclaration().getBody())
- }
contextElement is JetFunctionLiteral -> {
val block = contextElement.getBodyExpression()!!
block.getStatements().firstOrNull() ?: block.getLastChild()
diff --git a/idea/src/org/jetbrains/kotlin/idea/projectView/JetClassObjectTreeNode.java b/idea/src/org/jetbrains/kotlin/idea/projectView/JetClassObjectTreeNode.java
deleted file mode 100644
index 3ac3c7db97dcd..0000000000000
--- a/idea/src/org/jetbrains/kotlin/idea/projectView/JetClassObjectTreeNode.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright 2010-2015 JetBrains s.r.o.
- *
- * 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.jetbrains.kotlin.idea.projectView;
-
-import com.intellij.ide.projectView.PresentationData;
-import com.intellij.ide.projectView.ViewSettings;
-import com.intellij.ide.projectView.impl.nodes.AbstractPsiBasedNode;
-import com.intellij.ide.util.treeView.AbstractTreeNode;
-import com.intellij.openapi.project.Project;
-import com.intellij.psi.PsiElement;
-import org.jetbrains.kotlin.psi.JetClassObject;
-import org.jetbrains.kotlin.psi.JetPsiUtil;
-
-import java.util.Collection;
-
-import static org.jetbrains.kotlin.idea.projectView.JetProjectViewUtil.canRepresentPsiElement;
-import static org.jetbrains.kotlin.idea.projectView.JetProjectViewUtil.getClassOrObjectChildren;
-
-public class JetClassObjectTreeNode extends AbstractPsiBasedNode<JetClassObject> {
- protected JetClassObjectTreeNode(Project project, JetClassObject classObject, ViewSettings viewSettings) {
- super(project, classObject, viewSettings);
- }
-
- @Override
- protected PsiElement extractPsiFromValue() {
- return getValue();
- }
-
- @Override
- protected Collection<AbstractTreeNode> getChildrenImpl() {
- return getClassOrObjectChildren(getValue().getObjectDeclaration(), getProject(), getSettings());
- }
-
- @Override
- protected void updateImpl(PresentationData data) {
- data.setPresentableText("<class object>");
- }
-
- @Override
- public boolean canRepresent(Object element) {
- if (!isValid()) {
- return false;
- }
-
- return super.canRepresent(element) || canRepresentPsiElement(getValue(), element, getSettings());
- }
-
- @Override
- protected boolean isDeprecated() {
- return JetPsiUtil.isDeprecated(getValue());
- }
-}
diff --git a/idea/src/org/jetbrains/kotlin/idea/projectView/JetProjectViewUtil.java b/idea/src/org/jetbrains/kotlin/idea/projectView/JetProjectViewUtil.java
index 38a44fd4ea42d..e833fb608649a 100644
--- a/idea/src/org/jetbrains/kotlin/idea/projectView/JetProjectViewUtil.java
+++ b/idea/src/org/jetbrains/kotlin/idea/projectView/JetProjectViewUtil.java
@@ -21,7 +21,6 @@
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
-import org.jetbrains.kotlin.psi.JetClassObject;
import org.jetbrains.kotlin.psi.JetClassOrObject;
import org.jetbrains.kotlin.psi.JetDeclaration;
@@ -44,9 +43,6 @@ public static Collection<AbstractTreeNode> getClassOrObjectChildren(JetClassOrOb
if (declaration instanceof JetClassOrObject) {
result.add(new JetClassOrObjectTreeNode(project, (JetClassOrObject) declaration, settings));
}
- else if (declaration instanceof JetClassObject) {
- result.add(new JetClassObjectTreeNode(project, (JetClassObject) declaration, settings));
- }
else {
result.add(new JetDeclarationTreeNode(project, declaration, settings));
}
diff --git a/idea/src/org/jetbrains/kotlin/idea/run/JetRunConfigurationProducer.java b/idea/src/org/jetbrains/kotlin/idea/run/JetRunConfigurationProducer.java
index 42a86aac9a32d..ab151d894ca85 100644
--- a/idea/src/org/jetbrains/kotlin/idea/run/JetRunConfigurationProducer.java
+++ b/idea/src/org/jetbrains/kotlin/idea/run/JetRunConfigurationProducer.java
@@ -117,8 +117,7 @@ public FunctionDescriptor fun(JetNamedFunction function) {
currentElement = PsiTreeUtil.getParentOfType((PsiElement) currentElement, JetClassOrObject.class, JetFile.class)) {
JetDeclarationContainer entryPointContainer = currentElement;
if (entryPointContainer instanceof JetClass) {
- JetClassObject classObject = ((JetClass) currentElement).getClassObject();
- entryPointContainer = classObject != null ? classObject.getObjectDeclaration() : null;
+ entryPointContainer = ((JetClass) currentElement).getClassObject();
}
if (entryPointContainer != null && mainFunctionDetector.hasMain(entryPointContainer.getDeclarations())) return entryPointContainer;
}
diff --git a/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/JetPsiUnifier.kt b/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/JetPsiUnifier.kt
index 887662fa90819..84e982162d3f3 100644
--- a/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/JetPsiUnifier.kt
+++ b/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/JetPsiUnifier.kt
@@ -72,7 +72,6 @@ import org.jetbrains.kotlin.psi.JetParameter
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.psi.JetClassOrObject
import org.jetbrains.kotlin.psi.JetCallableDeclaration
-import org.jetbrains.kotlin.psi.JetClassObject
import org.jetbrains.kotlin.psi.JetTypeParameter
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.renderer.DescriptorRenderer
@@ -695,9 +694,6 @@ public class JetPsiUnifier(
e1 is JetMultiDeclaration && e2 is JetMultiDeclaration ->
if (matchMultiDeclarations(e1, e2)) null else UNMATCHED
- e1 is JetClassObject && e2 is JetClassObject ->
- e1.getObjectDeclaration().matchDeclarations(e2.getObjectDeclaration())
-
e1 is JetClassInitializer && e2 is JetClassInitializer ->
null
diff --git a/idea/testData/quickfix/suppress/declarationKinds/afterClassObject.kt b/idea/testData/quickfix/suppress/declarationKinds/afterClassObject.kt
index d6f897ae27ff9..593b6872e267c 100644
--- a/idea/testData/quickfix/suppress/declarationKinds/afterClassObject.kt
+++ b/idea/testData/quickfix/suppress/declarationKinds/afterClassObject.kt
@@ -1,4 +1,4 @@
-// "Suppress 'REDUNDANT_NULLABLE' for class object of C" "true"
+// "Suppress 'REDUNDANT_NULLABLE' for class object Default of C" "true"
class C {
[suppress("REDUNDANT_NULLABLE")]
diff --git a/idea/testData/quickfix/suppress/declarationKinds/beforeClassObject.kt b/idea/testData/quickfix/suppress/declarationKinds/beforeClassObject.kt
index 92865aee6a81f..c6b058626b934 100644
--- a/idea/testData/quickfix/suppress/declarationKinds/beforeClassObject.kt
+++ b/idea/testData/quickfix/suppress/declarationKinds/beforeClassObject.kt
@@ -1,4 +1,4 @@
-// "Suppress 'REDUNDANT_NULLABLE' for class object of C" "true"
+// "Suppress 'REDUNDANT_NULLABLE' for class object Default of C" "true"
class C {
class object {
diff --git a/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt b/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt
index 7fa69e4117f86..7afc5a3bf98ca 100644
--- a/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt
+++ b/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt
@@ -37,7 +37,6 @@ import org.jetbrains.kotlin.psi.stubs.KotlinPropertyStub
import kotlin.test.assertEquals
import org.jetbrains.kotlin.psi.JetClassBody
import org.jetbrains.kotlin.psi.JetClassInitializer
-import org.jetbrains.kotlin.psi.JetClassObject
import org.jetbrains.kotlin.psi.debugText.getDebugText
public class DebugTextByStubTest : LightCodeInsightFixtureTestCase() {
@@ -201,10 +200,10 @@ public class DebugTextByStubTest : LightCodeInsightFixtureTestCase() {
}
fun testClassObject() {
- val tree = createStubTree("class A { class object {} }")
+ val tree = createStubTree("class A { class object Def {} }")
val classObject = tree.findChildStubByType(JetStubElementTypes.CLASS)!!.findChildStubByType(JetStubElementTypes.CLASS_BODY)!!
- .findChildStubByType(JetStubElementTypes.CLASS_OBJECT)
- assertEquals("class object in STUB: class A", JetClassObject(classObject as KotlinPlaceHolderStub).getDebugText())
+ .findChildStubByType(JetStubElementTypes.OBJECT_DECLARATION)
+ assertEquals("STUB: class object Def", JetObjectDeclaration(classObject as KotlinObjectStub).getDebugText())
}
fun testPropertyAccessors() {
diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/DeclarationBodyVisitor.java b/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/DeclarationBodyVisitor.java
index f4dfd6a04e6ac..0ebad4b0d21a7 100644
--- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/DeclarationBodyVisitor.java
+++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/DeclarationBodyVisitor.java
@@ -84,8 +84,11 @@ public Void visitEnumEntry(@NotNull JetEnumEntry enumEntry, TranslationContext d
}
@Override
- public Void visitClassObject(@NotNull JetClassObject classObject, TranslationContext context) {
- JetObjectDeclaration declaration = classObject.getObjectDeclaration();
+ public Void visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, TranslationContext context) {
+ if (!declaration.isClassObject()) {
+ // parsed it in initializer visitor => no additional actions are needed
+ return null;
+ }
JsExpression value = ClassTranslator.generateClassCreation(declaration, context);
ClassDescriptor descriptor = getClassDescriptor(context.bindingContext(), declaration);
@@ -94,12 +97,6 @@ public Void visitClassObject(@NotNull JetClassObject classObject, TranslationCon
return null;
}
- @Override
- public Void visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, TranslationContext context) {
- // parsed it in initializer visitor => no additional actions are needed
- return null;
- }
-
@Override
public Void visitNamedFunction(@NotNull JetNamedFunction expression, TranslationContext context) {
FunctionDescriptor descriptor = getFunctionDescriptor(context.bindingContext(), expression);
diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/initializer/InitializerVisitor.java b/js/js.translator/src/org/jetbrains/kotlin/js/translate/initializer/InitializerVisitor.java
index 7ac2439807bcb..292ac2c0e995d 100644
--- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/initializer/InitializerVisitor.java
+++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/initializer/InitializerVisitor.java
@@ -65,7 +65,9 @@ public Void visitDeclaration(@NotNull JetDeclaration expression, @NotNull Transl
@Override
public Void visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, @NotNull TranslationContext context) {
- InitializerUtils.generateObjectInitializer(declaration, result, context);
+ if (!declaration.isClassObject()) {
+ InitializerUtils.generateObjectInitializer(declaration, result, context);
+ }
return null;
}
}
|
30661b0551940cf7e40b3db2dd3263b3d8b23c2a
|
Delta Spike
|
DELTASPIKE-289 add postback handling for windowId
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties
index c20b420f7..b935ffcb8 100644
--- a/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties
+++ b/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties
@@ -1,19 +1,19 @@
-#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
+# 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.
+# 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.
testProperty03=test_value_03
org.apache.deltaspike.core.spi.activation.ClassDeactivator=org.apache.deltaspike.test.core.impl.activation.TestClassDeactivator
diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindow.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindow.java
new file mode 100644
index 000000000..d272f3353
--- /dev/null
+++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindow.java
@@ -0,0 +1,51 @@
+/*
+ * 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.deltaspike.jsf.spi.scope.window;
+
+import javax.faces.context.FacesContext;
+
+/**
+ * <p>API to interact with the window/browser tab handling.
+ * This originally got implemented in Apache MyFaces CODI
+ * which was the basis for the respective feature in JSF-2.2.
+ * We now orientate us a bit on the JSF-2.2 API for making it
+ * easier to provide this feature for JSF-2.0, JSF-2.1 and also
+ * JSF-2.2 JSF implementations.</p>
+ *
+ * <p>Please not that in JSF-2.2 a <code>javax.faces.lifecycle.ClientWindow</code>
+ * instance gets created for each and every request, but in DeltaSpike our
+ * ClientWindow instances are most likely @ApplicationScoped.
+ * </p>
+ */
+public interface ClientWindow
+{
+
+ /**
+ * Extract the windowId for the current request.
+ * This method is intended to get executed at the start of the JSF lifecycle.
+ * We also need to take care about JSF-2.2 ClientWindow in the future.
+ * Depending on the {@link ClientWindowConfig.ClientWindowRenderMode} and
+ * after consulting {@link ClientWindowConfig} we will first send an
+ * intermediate page if the request is an initial GET request.
+ *
+ * @param facesContext for the request
+ * @return the extracted WindowId of the Request, or <code>null</code> if there is no window assigned.
+ */
+ String getWindowId(FacesContext facesContext);
+}
diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindowConfig.java
similarity index 92%
rename from deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java
rename to deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindowConfig.java
index 94690ec2a..dd3c5db0e 100644
--- a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java
+++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindowConfig.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.deltaspike.jsf.spi.window;
+package org.apache.deltaspike.jsf.spi.scope.window;
import javax.faces.context.FacesContext;
@@ -46,7 +46,12 @@ public enum ClientWindowRenderMode
* Render each GET request with the windowId you get during the request
* and perform a lazy check on the client side via JavaScript or similar.
*/
- LAZY
+ LAZY,
+
+ /**
+ * If you set this mode, you also need to provide an own {@link ClientWindow} implementation.
+ */
+ CUSTOM
}
diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/DefaultClientWindowConfig.java
similarity index 95%
rename from deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java
rename to deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/DefaultClientWindowConfig.java
index dbec59177..a3bcf22a5 100644
--- a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java
+++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/DefaultClientWindowConfig.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.deltaspike.jsf.spi.window;
+package org.apache.deltaspike.jsf.spi.scope.window;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
@@ -32,8 +32,11 @@
import org.apache.deltaspike.core.util.ExceptionUtils;
/**
- * Default implementation of {@link ClientWindowConfig}.
- * It will use the internal <code>windowhandler.html</code>
+ * <p>Default implementation of {@link ClientWindowConfig}.
+ * By default it will use the internal <code>windowhandler.html</code></p>
+ *
+ * <p>You can @Specializes this class to tweak the configuration or
+ * provide a completely new implementation as @Alternative.</p>
*/
@SessionScoped
public class DefaultClientWindowConfig implements ClientWindowConfig, Serializable
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
index 28ad66dd4..9d4808d85 100644
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
@@ -56,7 +56,10 @@ public void execute(FacesContext facesContext)
//TODO broadcastApplicationStartupBroadcaster();
broadcastBeforeFacesRequestEvent(facesContext);
+ //X TODO add ClientWindow handling
this.wrapped.execute(facesContext);
+
+
}
@Override
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
new file mode 100644
index 000000000..4ab6d37f8
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
@@ -0,0 +1,96 @@
+/*
+ * 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.deltaspike.jsf.impl.scope.window;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.faces.component.UIViewRoot;
+import javax.faces.context.FacesContext;
+import javax.inject.Inject;
+
+import java.util.logging.Logger;
+
+import org.apache.deltaspike.core.spi.scope.window.WindowContext;
+import org.apache.deltaspike.jsf.spi.scope.window.ClientWindow;
+import org.apache.deltaspike.jsf.spi.scope.window.ClientWindowConfig;
+
+import static org.apache.deltaspike.jsf.spi.scope.window.ClientWindowConfig.ClientWindowRenderMode;
+
+/**
+ * This is the default implementation of the window/browser tab
+ * detection handling for JSF applications.
+ * This is to big degrees a port of Apache MyFaces CODI
+ * ClientSideWindowHandler.
+ *
+ * It will act according to the configured {@link ClientWindowRenderMode}.
+ *
+ *
+ */
+@ApplicationScoped
+public class DefaultClientWindow implements ClientWindow
+{
+ private static final Logger logger = Logger.getLogger(DefaultClientWindow.class.getName());
+
+
+ @Inject
+ private ClientWindowConfig clientWindowConfig;
+
+ @Inject
+ private WindowContext windowContext;
+
+
+ @Override
+ public String getWindowId(FacesContext facesContext)
+ {
+ if (ClientWindowRenderMode.NONE.equals(clientWindowConfig.getClientWindowRenderMode(facesContext)))
+ {
+ return null;
+ }
+
+ String windowId = null;
+
+ if (facesContext.isPostback())
+ {
+ return getPostBackWindowId(facesContext);
+ }
+
+ return windowId;
+ }
+
+ /**
+ * Extract the windowId for http POST
+ */
+ private String getPostBackWindowId(FacesContext facesContext)
+ {
+ UIViewRoot uiViewRoot = facesContext.getViewRoot();
+
+ if (uiViewRoot != null)
+ {
+ WindowIdHolderComponent existingWindowIdHolder
+ = WindowIdHolderComponent.getWindowIdHolderComponent(uiViewRoot);
+ if (existingWindowIdHolder != null)
+ {
+ return existingWindowIdHolder.getWindowId();
+ }
+ }
+
+ return null;
+ }
+
+
+}
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java
new file mode 100644
index 000000000..e4f73268b
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java
@@ -0,0 +1,154 @@
+/*
+ * 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.deltaspike.jsf.impl.scope.window;
+
+import javax.faces.component.UIComponent;
+import javax.faces.component.UIOutput;
+import javax.faces.component.UIViewRoot;
+import javax.faces.context.FacesContext;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+/**
+ * UI Component holder for the windowId in case of post-backs.
+ * We store this component as direct child in the ViewRoot
+ * and evaluate it's value on postbacks.
+ */
+public class WindowIdHolderComponent extends UIOutput
+{
+ private static final Logger logger = Logger.getLogger(WindowIdHolderComponent.class.getName());
+
+ private String windowId;
+
+ /**
+ * Default constructor might be invoked by the jsf implementation
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public WindowIdHolderComponent()
+ {
+ }
+
+ /**
+ * Constructor which creates the holder for the given window-id
+ * @param windowId current window-id
+ */
+ public WindowIdHolderComponent(String windowId)
+ {
+ this.windowId = windowId;
+ }
+
+ /**
+ * Needed for server-side window-handler and client-side window handler for supporting postbacks
+ */
+ public static void addWindowIdHolderComponent(FacesContext facesContext, String windowId)
+ {
+ if (windowId == null || windowId.length() == 0)
+ {
+ return;
+ }
+
+ UIViewRoot uiViewRoot = facesContext.getViewRoot();
+
+ if (uiViewRoot == null)
+ {
+ return;
+ }
+
+ WindowIdHolderComponent existingWindowIdHolder = getWindowIdHolderComponent(uiViewRoot);
+ if (existingWindowIdHolder != null)
+ {
+ if (!windowId.equals(existingWindowIdHolder.getWindowId()))
+ {
+ logger.log(Level.FINE, "updating WindowIdHolderComponent from %1 to %2",
+ new Object[]{existingWindowIdHolder.getId(), windowId});
+
+ existingWindowIdHolder.changeWindowId(windowId);
+ }
+ return;
+ }
+ else
+ {
+ // add as first child
+ uiViewRoot.getChildren().add(0, new WindowIdHolderComponent(windowId));
+ }
+ }
+
+ public static WindowIdHolderComponent getWindowIdHolderComponent(UIViewRoot uiViewRoot)
+ {
+ List<UIComponent> uiComponents = uiViewRoot.getChildren();
+
+ // performance improvement - don't change - see EXTCDI-256 :
+ for (int i = 0, size = uiComponents.size(); i < size; i++)
+ {
+ UIComponent uiComponent = uiComponents.get(i);
+ if (uiComponent instanceof WindowIdHolderComponent)
+ {
+ //in this case we have the same view-root
+ return (WindowIdHolderComponent) uiComponent;
+ }
+ }
+
+ return null;
+ }
+
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Object saveState(FacesContext facesContext)
+ {
+ Object[] values = new Object[2];
+ values[0] = super.saveState(facesContext);
+ values[1] = windowId;
+ return values;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void restoreState(FacesContext facesContext, Object state)
+ {
+ if (state == null)
+ {
+ return;
+ }
+
+ Object[] values = (Object[]) state;
+ super.restoreState(facesContext, values[0]);
+
+ windowId = (String) values[1];
+ }
+
+ /**
+ * @return the current windowId
+ */
+ public String getWindowId()
+ {
+ return windowId;
+ }
+
+ void changeWindowId(String windowId)
+ {
+ this.windowId = windowId;
+ }
+}
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java
new file mode 100644
index 000000000..883ddb022
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java
@@ -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.
+ */
+package org.apache.deltaspike.jsf.impl.scope.window;
+
+import javax.faces.context.FacesContext;
+import javax.faces.render.RenderKit;
+import javax.faces.render.RenderKitFactory;
+import java.util.Iterator;
+
+import org.apache.deltaspike.core.spi.activation.Deactivatable;
+import org.apache.deltaspike.core.util.ClassDeactivationUtils;
+
+
+/**
+ * Registers the @{link WindowIdRenderKit}
+ */
+public class WindowIdRenderKitFactory extends RenderKitFactory implements Deactivatable
+{
+ private final RenderKitFactory wrapped;
+
+ private final boolean deactivated;
+
+ /**
+ * Constructor for wrapping the given {@link javax.faces.render.RenderKitFactory}
+ * @param wrapped render-kit-factory which will be wrapped
+ */
+ public WindowIdRenderKitFactory(RenderKitFactory wrapped)
+ {
+ this.wrapped = wrapped;
+ this.deactivated = !isActivated();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void addRenderKit(String s, RenderKit renderKit)
+ {
+ wrapped.addRenderKit(s, renderKit);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public RenderKit getRenderKit(FacesContext facesContext, String s)
+ {
+ RenderKit renderKit = wrapped.getRenderKit(facesContext, s);
+
+ if (renderKit == null)
+ {
+ return null;
+ }
+
+ if (deactivated)
+ {
+ return renderKit;
+ }
+
+ return new WindowIdRenderKitWrapper(renderKit);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Iterator<String> getRenderKitIds()
+ {
+ return wrapped.getRenderKitIds();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public RenderKitFactory getWrapped()
+ {
+ return wrapped;
+ }
+
+ public boolean isActivated()
+ {
+ return ClassDeactivationUtils.isActivated(getClass());
+ }
+}
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java
new file mode 100644
index 000000000..bb939d516
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java
@@ -0,0 +1,92 @@
+/*
+ * 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.deltaspike.jsf.impl.scope.window;
+
+import javax.faces.context.FacesContext;
+import javax.faces.context.ResponseWriter;
+import javax.faces.render.RenderKit;
+import javax.faces.render.RenderKitWrapper;
+import java.io.Writer;
+
+import org.apache.deltaspike.core.api.provider.BeanProvider;
+import org.apache.deltaspike.core.spi.scope.window.WindowContext;
+
+/**
+ * Wraps the RenderKit and adds the
+ * {@link WindowIdHolderComponent} to the view tree
+ */
+public class WindowIdRenderKitWrapper extends RenderKitWrapper
+{
+ private final RenderKit wrapped;
+
+ /**
+ * This will get initialized lazily to prevent boot order issues
+ * with the JSF and CDI containers.
+ */
+ private volatile WindowContext windowContext;
+
+
+ //needed if the renderkit gets proxied - see EXTCDI-215
+ protected WindowIdRenderKitWrapper()
+ {
+ this.wrapped = null;
+ }
+
+ public WindowIdRenderKitWrapper(RenderKit wrapped)
+ {
+ this.wrapped = wrapped;
+ }
+
+ @Override
+ public RenderKit getWrapped()
+ {
+ return wrapped;
+ }
+
+ /**
+ * Adds a {@link WindowIdHolderComponent} with the
+ * current windowId to the component tree.
+ */
+ public ResponseWriter createResponseWriter(Writer writer, String s, String s1)
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ String windowId = getWindowContext().getCurrentWindowId();
+
+ WindowIdHolderComponent.addWindowIdHolderComponent(facesContext, windowId);
+
+ return wrapped.createResponseWriter(writer, s, s1);
+ }
+
+
+ private WindowContext getWindowContext()
+ {
+ if (windowContext == null)
+ {
+ synchronized (this)
+ {
+ if (windowContext == null)
+ {
+ windowContext = BeanProvider.getContextualReference(WindowContext.class);
+ }
+ }
+ }
+
+ return windowContext;
+ }
+}
diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
index 50ed16777..6d951da10 100644
--- a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
+++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
@@ -36,5 +36,6 @@
<factory>
<lifecycle-factory>org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeLifecycleFactoryWrapper</lifecycle-factory>
<faces-context-factory>org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeFacesContextFactory</faces-context-factory>
+ <render-kit-factory>org.apache.deltaspike.jsf.impl.scope.window.WindowIdRenderKitFactory</render-kit-factory>
</factory>
-</faces-config>
\ No newline at end of file
+</faces-config>
|
062042ba83651b8495bc0330023ae7c7c47a38d4
|
hbase
|
HBASE-1722 Add support for exporting HBase- metrics via JMX--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@813229 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 05466fa181fb..d81a17cbca78 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -34,6 +34,7 @@ Release 0.21.0 - Unreleased
HBASE-1800 Too many ZK connections
HBASE-1819 Update to 0.20.1 hadoop and zk 3.2.1
HBASE-1820 Update jruby from 1.2 to 1.3.1
+ HBASE-1722 Add support for exporting HBase metrics via JMX
OPTIMIZATIONS
HBASE-1765 Delay Result deserialization until asked for and permit
diff --git a/src/docs/src/documentation/content/xdocs/metrics.xml b/src/docs/src/documentation/content/xdocs/metrics.xml
index c8744f438de5..b01d7bd06cc7 100644
--- a/src/docs/src/documentation/content/xdocs/metrics.xml
+++ b/src/docs/src/documentation/content/xdocs/metrics.xml
@@ -63,5 +63,118 @@
in ganglia, the stats are aggregated rather than reported per instance.
</p>
</section>
+
+ <section>
+ <title> Using with JMX </title>
+ <p>
+ In addition to the standard output contexts supported by the Hadoop
+ metrics package, you can also export HBase metrics via Java Management
+ Extensions (JMX). This will allow viewing HBase stats in JConsole or
+ any other JMX client.
+ </p>
+ <section>
+ <title>Enable HBase stats collection</title>
+ <p>
+ To enable JMX support in HBase, first edit
+ <code>$HBASE_HOME/conf/hadoop-metrics.properties</code> to support
+ metrics refreshing. (If you've already configured
+ <code>hadoop-metrics.properties</code> for another output context,
+ you can skip this step).
+ </p>
+ <source>
+# Configuration of the "hbase" context for null
+hbase.class=org.apache.hadoop.metrics.spi.NullContextWithUpdateThread
+hbase.period=60
+
+# Configuration of the "jvm" context for null
+jvm.class=org.apache.hadoop.metrics.spi.NullContextWithUpdateThread
+jvm.period=60
+
+# Configuration of the "rpc" context for null
+rpc.class=org.apache.hadoop.metrics.spi.NullContextWithUpdateThread
+rpc.period=60
+ </source>
+ </section>
+ <section>
+ <title>Setup JMX remote access</title>
+ <p>
+ For remote access, you will need to configure JMX remote passwords
+ and access profiles. Create the files:
+ </p>
+ <dl>
+ <dt><code>$HBASE_HOME/conf/jmxremote.passwd</code> (set permissions
+ to 600)</dt>
+ <dd>
+ <source>
+monitorRole monitorpass
+controlRole controlpass
+ </source>
+ </dd>
+
+ <dt><code>$HBASE_HOME/conf/jmxremote.access</code></dt>
+ <dd>
+ <source>
+monitorRole readonly
+controlRole readwrite
+ </source>
+ </dd>
+ </dl>
+ </section>
+ <section>
+ <title>Configure JMX in HBase startup</title>
+ <p>
+ Finally, edit the <code>$HBASE_HOME/conf/hbase-env.sh</code> and
+ <code>$HBASE_HOME/bin/hbase</code> scripts for JMX support:
+ </p>
+ <dl>
+ <dt><code>$HBASE_HOME/conf/hbase-env.sh</code></dt>
+ <dd>
+ <p>Add the lines:</p>
+ <source>
+JMX_OPTS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.ssl=false"
+JMX_OPTS="$JMX_OPTS -Dcom.sun.management.jmxremote.password.file=$HBASE_HOME/conf/jmxremote.passwd"
+JMX_OPTS="$JMX_OPTS -Dcom.sun.management.jmxremote.access.file=$HBASE_HOME/conf/jmxremote.access"
+
+export HBASE_MASTER_OPTS="$JMX_OPTS -Dcom.sun.management.jmxremote.port=10101"
+export HBASE_REGIONSERVER_OPTS="$JMX_OPTS -Dcom.sun.management.jmxremote.port=10102"
+ </source>
+ </dd>
+ <dt><code>$HBASE_HOME/bin/hbase</code></dt>
+ <dd>
+ <p>Towards the end of the script, replace the lines:</p>
+ <source>
+ # figure out which class to run
+if [ "$COMMAND" = "shell" ] ; then
+ CLASS="org.jruby.Main ${HBASE_HOME}/bin/hirb.rb"
+elif [ "$COMMAND" = "master" ] ; then
+ CLASS='org.apache.hadoop.hbase.master.HMaster'
+elif [ "$COMMAND" = "regionserver" ] ; then
+ CLASS='org.apache.hadoop.hbase.regionserver.HRegionServer'
+ </source>
+ <p>
+ with the lines: (adding the "HBASE_OPTS=..." lines for "master" and
+ "regionserver" commands)
+ </p>
+ <source>
+ # figure out which class to run
+if [ "$COMMAND" = "shell" ] ; then
+ CLASS="org.jruby.Main ${HBASE_HOME}/bin/hirb.rb"
+elif [ "$COMMAND" = "master" ] ; then
+ CLASS='org.apache.hadoop.hbase.master.HMaster'
+ HBASE_OPTS="$HBASE_OPTS $HBASE_MASTER_OPTS"
+elif [ "$COMMAND" = "regionserver" ] ; then
+ CLASS='org.apache.hadoop.hbase.regionserver.HRegionServer'
+ HBASE_OPTS="$HBASE_OPTS $HBASE_REGIONSERVER_OPTS"
+ </source>
+ </dd>
+ </dl>
+ <p>
+ After restarting the processes you want to monitor, you should now be
+ able to run JConsole (included with the JDK since JDK 5.0) to view
+ the statistics via JMX. HBase MBeans are exported under the
+ <strong><code>hadoop</code></strong> domain in JMX.
+ </p>
+ </section>
+ </section>
</body>
</document>
diff --git a/src/java/org/apache/hadoop/hbase/ipc/HBaseRpcMetrics.java b/src/java/org/apache/hadoop/hbase/ipc/HBaseRpcMetrics.java
index fcfd13943815..950d02a43900 100644
--- a/src/java/org/apache/hadoop/hbase/ipc/HBaseRpcMetrics.java
+++ b/src/java/org/apache/hadoop/hbase/ipc/HBaseRpcMetrics.java
@@ -47,6 +47,7 @@
public class HBaseRpcMetrics implements Updater {
private MetricsRecord metricsRecord;
private static Log LOG = LogFactory.getLog(HBaseRpcMetrics.class);
+ private final HBaseRPCStatistics rpcStatistics;
public HBaseRpcMetrics(String hostName, String port) {
MetricsContext context = MetricsUtil.getContext("rpc");
@@ -58,6 +59,8 @@ public HBaseRpcMetrics(String hostName, String port) {
+ hostName + ", port=" + port);
context.registerUpdater(this);
+
+ rpcStatistics = new HBaseRPCStatistics(this.registry, hostName, port);
}
@@ -110,6 +113,7 @@ public void doUpdates(MetricsContext context) {
}
public void shutdown() {
- // Nothing to do
+ if (rpcStatistics != null)
+ rpcStatistics.shutdown();
}
}
\ No newline at end of file
diff --git a/src/java/org/apache/hadoop/hbase/master/metrics/MasterMetrics.java b/src/java/org/apache/hadoop/hbase/master/metrics/MasterMetrics.java
index 4d527b0a5b15..62d7cf3888c4 100644
--- a/src/java/org/apache/hadoop/hbase/master/metrics/MasterMetrics.java
+++ b/src/java/org/apache/hadoop/hbase/master/metrics/MasterMetrics.java
@@ -39,6 +39,7 @@ public class MasterMetrics implements Updater {
private final Log LOG = LogFactory.getLog(this.getClass());
private final MetricsRecord metricsRecord;
private final MetricsRegistry registry = new MetricsRegistry();
+ private final MasterStatistics masterStatistics;
/*
* Count of requests to the cluster since last call to metrics update
*/
@@ -52,11 +53,16 @@ public MasterMetrics() {
metricsRecord.setTag("Master", name);
context.registerUpdater(this);
JvmMetrics.init("Master", name);
+
+ // expose the MBean for metrics
+ masterStatistics = new MasterStatistics(this.registry);
+
LOG.info("Initialized");
}
public void shutdown() {
- // nought to do.
+ if (masterStatistics != null)
+ masterStatistics.shutdown();
}
/**
diff --git a/src/java/org/apache/hadoop/hbase/regionserver/metrics/RegionServerMetrics.java b/src/java/org/apache/hadoop/hbase/regionserver/metrics/RegionServerMetrics.java
index 52ab21ffffef..49e819724960 100644
--- a/src/java/org/apache/hadoop/hbase/regionserver/metrics/RegionServerMetrics.java
+++ b/src/java/org/apache/hadoop/hbase/regionserver/metrics/RegionServerMetrics.java
@@ -47,6 +47,7 @@ public class RegionServerMetrics implements Updater {
private long lastUpdate = System.currentTimeMillis();
private static final int MB = 1024*1024;
private MetricsRegistry registry = new MetricsRegistry();
+ private final RegionServerStatistics statistics;
public final MetricsTimeVaryingRate atomicIncrementTime =
new MetricsTimeVaryingRate("atomicIncrementTime", registry);
@@ -112,13 +113,18 @@ public RegionServerMetrics() {
context.registerUpdater(this);
// Add jvmmetrics.
JvmMetrics.init("RegionServer", name);
+
+ // export for JMX
+ statistics = new RegionServerStatistics(this.registry, name);
+
LOG.info("Initialized");
}
-
+
public void shutdown() {
- // nought to do.
+ if (statistics != null)
+ statistics.shutdown();
}
-
+
/**
* Since this object is a registered updater, this method will be called
* periodically, e.g. every 5 seconds.
@@ -141,7 +147,7 @@ public void doUpdates(MetricsContext unused) {
this.metricsRecord.update();
this.lastUpdate = System.currentTimeMillis();
}
-
+
public void resetAllMinMax() {
// Nothing to do
}
|
07d58c5537eb7c63194c49de7f75c79834a3f442
|
restlet-framework-java
|
Completed implementation of apispark extension.--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.apispark/.classpath b/modules/org.restlet.ext.apispark/.classpath
index 3474bbacbd..3d20c6d659 100644
--- a/modules/org.restlet.ext.apispark/.classpath
+++ b/modules/org.restlet.ext.apispark/.classpath
@@ -3,5 +3,7 @@
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="src" path="src"/>
<classpathentry combineaccessrules="false" exported="true" kind="src" path="/org.restlet"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/org.restlet.ext.jackson"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/com.fasterxml.jackson"/>
<classpathentry kind="output" path="bin"/>
</classpath>
diff --git a/modules/org.restlet.ext.apispark/module.xml b/modules/org.restlet.ext.apispark/module.xml
index ba038b1000..baaf978298 100644
--- a/modules/org.restlet.ext.apispark/module.xml
+++ b/modules/org.restlet.ext.apispark/module.xml
@@ -9,5 +9,6 @@
<dependencies>
<dependency type="module" id="core" />
+ <dependency type="module" id="jackson" />
</dependencies>
</module>
\ No newline at end of file
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Account.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Account.java
index ba445cdac4..5f4803a777 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Account.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Account.java
@@ -2,9 +2,8 @@
public class Account {
- public void createApi(Contract api){
-
- }
-
-
+ public void createApi(Contract api) {
+
+ }
+
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Body.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Body.java
index be8e207d46..d7db2bfb7f 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Body.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Body.java
@@ -3,27 +3,27 @@
public class Body {
/**
- * Reference of the representation in the body
- * of the message
- */
- private String type;
-
- /**
- * Indicates whether you should provide an array
- * of [type] or just one [type]
+ * Indicates whether you should provide an array of [type] or just one
+ * [type].
*/
private boolean array;
-
+
+ /** Reference of the representation in the body of the message. */
+ private String type;
+
public String getRepresentation() {
return type;
}
- public void setRepresentation(String representation) {
- this.type = representation;
- }
+
public boolean isArray() {
return array;
}
+
public void setArray(boolean array) {
this.array = array;
}
+
+ public void setRepresentation(String representation) {
+ this.type = representation;
+ }
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Contract.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Contract.java
index b9ad9209eb..eacc795a92 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Contract.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Contract.java
@@ -3,57 +3,50 @@
import java.util.List;
public class Contract {
-
- /**
- * Name of the API
- */
- private String name;
-
- /**
- * Textual description of the API
- */
+
+ /** Textual description of the API. */
private String description;
-
+
+ /** Name of the API. */
+ private String name;
+
/**
- * Representations available with this API
- * Note: their "name" is used as a reference further in
- * this description
+ * Representations available with this API Note: their "name" is used as a
+ * reference further in this description.
*/
private List<Representation> Representations;
-
- /**
- * Resources provided by the API
- */
+
+ /** Resources provided by the API. */
private List<Resource> resources;
+ public String getDescription() {
+ return description;
+ }
+
public String getName() {
return name;
}
- public void setName(String name) {
- this.name = name;
+ public List<Representation> getRepresentations() {
+ return Representations;
}
- public String getDescription() {
- return description;
+ public List<Resource> getResources() {
+ return resources;
}
public void setDescription(String description) {
this.description = description;
}
- public List<Representation> getRepresentations() {
- return Representations;
+ public void setName(String name) {
+ this.name = name;
}
public void setRepresentations(List<Representation> representations) {
Representations = representations;
}
- public List<Resource> getResources() {
- return resources;
- }
-
public void setResources(List<Resource> resources) {
this.resources = resources;
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Documentation.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Documentation.java
index 7ce075cafb..310e43c177 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Documentation.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Documentation.java
@@ -2,71 +2,62 @@
public class Documentation {
- /**
- * Current version of the API
- */
- private String version;
-
- /**
- * URL of the description of the license used by the API
- */
- private String license;
-
- /**
- * Base URL on which you can access the API
- * Note: will enable multiple endpoints and protocols in
- * the future (use class Endpoint in a list)
- */
- private String endpoint;
-
- /**
- * E-mail of the person to contact for further information
- * or user acces on the API
- */
+ /** Any useful information for a user that plans to access to the API. */
private String contact;
-
+
+ /** Contract of this API. */
+ private Contract contract;
+
/**
- * Contract of this API
+ * Base URL on which you can access the API<br>
+ * Note: will enable multiple endpoints and protocols in the future (use
+ * class Endpoint in a list).
*/
- private Contract contract;
+ private String endpoint;
- public String getVersion() {
- return version;
- }
+ /** URL of the description of the license used by the API. */
+ private String license;
- public void setVersion(String version) {
- this.version = version;
- }
+ /** Current version of the API. */
+ private String version;
- public String getLicense() {
- return license;
+ public String getContact() {
+ return contact;
}
- public void setLicense(String license) {
- this.license = license;
+ public Contract getContract() {
+ return contract;
}
public String getEndpoint() {
return endpoint;
}
- public void setEndpoint(String endpoint) {
- this.endpoint = endpoint;
+ public String getLicense() {
+ return license;
}
- public String getContact() {
- return contact;
+ public String getVersion() {
+ return version;
}
public void setContact(String contact) {
this.contact = contact;
}
- public Contract getContract() {
- return contract;
- }
-
public void setContract(Contract contract) {
this.contract = contract;
}
+
+ public void setEndpoint(String endpoint) {
+ this.endpoint = endpoint;
+ }
+
+ public void setLicense(String license) {
+ this.license = license;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Endpoint.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Endpoint.java
index 556b567ae6..b84d182c93 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Endpoint.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Endpoint.java
@@ -4,37 +4,36 @@
public class Endpoint {
- /**
- * Protocol used for this endpoint
- */
- private Protocol protocol;
-
- /**
- * Address of the host
- */
+ /** The host's name. */
private String host;
-
- /**
- * Port used for this endpoint
- */
- private Integer port;
-
- public Protocol getProtocol() {
- return protocol;
- }
- public void setProtocol(Protocol protocol) {
- this.protocol = protocol;
- }
+
+ /** The endpoint's port. */
+ private int port;
+
+ /** Protocol used for this endpoint. */
+ private Protocol protocol;
+
public String getHost() {
return host;
}
+
+ public int getPort() {
+ return port;
+ }
+
+ public Protocol getProtocol() {
+ return protocol;
+ }
+
public void setHost(String host) {
this.host = host;
}
- public Integer getPort() {
- return port;
- }
- public void setPort(Integer port) {
+
+ public void setPort(int port) {
this.port = port;
}
+
+ public void setProtocol(Protocol protocol) {
+ this.protocol = protocol;
+ }
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Method.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Method.java
index 27e9ad492a..431d26def3 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Method.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Method.java
@@ -1,5 +1,26 @@
package org.restlet.ext.apispark;
public class Method {
+ /** Textual description of this method. */
+ private String description;
+
+ /** Name of this method. */
+ private String name;
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Operation.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Operation.java
index 31863aa858..94ef0649dd 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Operation.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Operation.java
@@ -4,105 +4,107 @@
public class Operation {
- /**
- * HTTP method for this operation
- */
- private Method method;
-
- /**
- * Textual description of this operation
- */
+ /** Textual description of this operation. */
private String description;
-
+
+ /** Headers to use for this operation. */
+ private List<Parameter> headers;
+
+ /** Representation retrieved by this operation if any. */
+ private Body inRepresentation;
+
+ /** HTTP method for this operation. */
+ private Method method;
+
/**
- * Unique name for this operation
- * Note: will be used for client SDK generation in
- * the future
+ * Unique name for this operation<br>
+ * Note: will be used for client SDK generation in the future.
*/
private String name;
-
- /**
- * Representation retrieved by this operation if any
- */
- private Body inRepresentation;
-
+
/**
- * Representation to send in the body of your request
- * for this operation if any
+ * Representation to send in the body of your request for this operation if
+ * any.
*/
private Body outRepresentation;
-
- /**
- * Query parameters available for this operation
- */
- private List<Parameter> queryParameters;
-
- /**
- * Headers to use for this operation
- */
- private List<Parameter> headers;
-
- /**
- * Path variables you must provide for this operation
- */
+
+ /** ath variables you must provide for this operation. */
private List<PathVariable> pathVariables;
-
- /**
- * Possible response messages you could encounter
- */
+
+ /** Query parameters available for this operation. */
+ private List<Parameter> queryParameters;
+
+ /** Possible response messages you could encounter. */
private List<Response> responses;
-
- public Method getMethod() {
- return method;
- }
- public void setMethod(Method method) {
- this.method = method;
- }
+
public String getDescription() {
return description;
}
- public void setDescription(String description) {
- this.description = description;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
+
+ public List<Parameter> getHeaders() {
+ return headers;
}
+
public Body getInRepresentation() {
return inRepresentation;
}
- public void setInRepresentation(Body inRepresentation) {
- this.inRepresentation = inRepresentation;
+
+ public Method getMethod() {
+ return method;
}
+
+ public String getName() {
+ return name;
+ }
+
public Body getOutRepresentation() {
return outRepresentation;
}
- public void setOutRepresentation(Body outRepresentation) {
- this.outRepresentation = outRepresentation;
+
+ public List<PathVariable> getPathVariables() {
+ return pathVariables;
}
+
public List<Parameter> getQueryParameters() {
return queryParameters;
}
- public void setQueryParameters(List<Parameter> queryParameters) {
- this.queryParameters = queryParameters;
+
+ public List<Response> getResponses() {
+ return responses;
}
- public List<Parameter> getHeaders() {
- return headers;
+
+ public void setDescription(String description) {
+ this.description = description;
}
+
public void setHeaders(List<Parameter> headers) {
this.headers = headers;
}
- public List<PathVariable> getPathVariables() {
- return pathVariables;
+
+ public void setInRepresentation(Body inRepresentation) {
+ this.inRepresentation = inRepresentation;
}
+
+ public void setMethod(Method method) {
+ this.method = method;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setOutRepresentation(Body outRepresentation) {
+ this.outRepresentation = outRepresentation;
+ }
+
public void setPathVariables(List<PathVariable> pathVariables) {
this.pathVariables = pathVariables;
}
- public List<Response> getResponses() {
- return responses;
+
+ public void setQueryParameters(List<Parameter> queryParameters) {
+ this.queryParameters = queryParameters;
}
+
public void setResponses(List<Response> responses) {
this.responses = responses;
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Parameter.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Parameter.java
index 0c13d91ad4..5cffaadc06 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Parameter.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Parameter.java
@@ -5,71 +5,74 @@
public class Parameter {
/**
- * Name of the parameter
- */
- private String name;
-
- /**
- * Textual description of this parameter
- */
- private String description;
-
- /**
- * Default value of the parameter
+ * Indicates whether you can provide multiple values for this parameter or
+ * not.
*/
+ private boolean allowMultiple;
+
+ /** Default value of the parameter. */
private String defaultValue;
-
+
+ /** Textual description of this parameter. */
+ private String description;
+
+ /** Name of the parameter. */
+ private String name;
+
/**
- * List of possible values of the parameter if there
- * is a limited number of possible values for it
+ * List of possible values of the parameter if there is a limited number of
+ * possible values for it.
*/
private List<String> possibleValues;
-
- /**
- * Indicates whether the parameter is mandatory or not
- */
+
+ /** Indicates whether the parameter is mandatory or not. */
private boolean required;
-
- /**
- * Indicates whether you can provide multiple values
- * for this parameter or not
- */
- private boolean allowMultiple;
-
+
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
public String getName() {
return name;
}
- public void setName(String name) {
- this.name = name;
+
+ public List<String> getPossibleValues() {
+ return possibleValues;
}
- public String getDescription() {
- return description;
+
+ public boolean isAllowMultiple() {
+ return allowMultiple;
}
- public void setDescription(String description) {
- this.description = description;
+
+ public boolean isRequired() {
+ return required;
}
- public String getDefaultValue() {
- return defaultValue;
+
+ public void setAllowMultiple(boolean allowMultiple) {
+ this.allowMultiple = allowMultiple;
}
+
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
- public List<String> getPossibleValues() {
- return possibleValues;
+
+ public void setDescription(String description) {
+ this.description = description;
}
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
public void setPossibleValues(List<String> possibleValues) {
this.possibleValues = possibleValues;
}
- public boolean isRequired() {
- return required;
- }
+
public void setRequired(boolean required) {
this.required = required;
}
- public boolean isAllowMultiple() {
- return allowMultiple;
- }
- public void setAllowMultiple(boolean allowMultiple) {
- this.allowMultiple = allowMultiple;
- }
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/PathVariable.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/PathVariable.java
index c472f18486..12b38dc784 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/PathVariable.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/PathVariable.java
@@ -2,36 +2,21 @@
public class PathVariable {
- /**
- * Name of this variable
- */
- private String name;
-
- /**
- * Textual description of this variable
- */
- private String description;
-
- /**
- * Indicates whether you can provide a list of values
- * or just a single one
- */
+ /** Indicates whether you can provide a list of values or just a single one. */
private boolean array;
- public String getName() {
- return name;
- }
+ /** Textual description of this variable. */
+ private String description;
- public void setName(String name) {
- this.name = name;
- }
+ /** Name of this variable. */
+ private String name;
public String getDescription() {
return description;
}
- public void setDescription(String description) {
- this.description = description;
+ public String getName() {
+ return name;
}
public boolean isArray() {
@@ -41,4 +26,12 @@ public boolean isArray() {
public void setArray(boolean array) {
this.array = array;
}
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Property.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Property.java
index 888a64cd69..26da507f76 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Property.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Property.java
@@ -5,122 +5,135 @@
public class Property {
/**
- * Name ot this property
- */
- private String name;
-
- /**
- * Textual description of this property
- */
- private String description;
-
- /**
- * Type of this property, either a primitive type or
- * a reference to a representation
+ * Type of this property, either a primitive type or a reference to a
+ * representation.
*/
private String dataType;
-
+
+ // TODO review comment
/**
- * Default value if this property is of a primitive type
- * Note: need to check casts for non-String primitive
- * types
+ * Default value if this property is of a primitive type<br>
+ * Note: need to check casts for non-String primitive types
*/
private String defaultValue;
-
+
+ /** Textual description of this property. */
+ private String description;
+
+ // TODO review comment
/**
- * A list of possible values for this property if it has
- * a limited number of possible values
+ * Maximum value of this property if it is a number Note: check casts
*/
- private List<String> possibleValues;
-
+ private String max;
+
+ // TODO review comment
+ /** Maximum number of occurences of the items of this property. */
+ private Integer maxOccurs;
+
+ // TODO review comment
/**
- * Minimum value of this property if it is a number
- * Note: check casts
+ * Minimum value of this property if it is a number Note: check casts
*/
private String min;
-
+
+ // TODO review comment
+ /** Minimum number of occurences of the items of this property. */
+ private Integer minOccurs;
+
+ /** Name of this property. */
+ private String name;
+
+ // TODO review comment
/**
- * Maximum value of this property if it is a number
- * Note: check casts
+ * A list of possible values for this property if it has a limited number of
+ * possible values.
*/
- private String max;
-
+ private List<String> possibleValues;
+
+ // TODO review comment
/**
- * If maxOccurs > 1, indicates whether each item in
- * this property is supposed to be unique or not
+ * If maxOccurs > 1, indicates whether each item in this property is
+ * supposed to be unique or not
*/
private boolean uniqueItems;
-
- /**
- * Minimum number of occurences of the items of this
- * property
- */
- private Integer minOccurs;
-
- /**
- * Maximum number of occurences of the items of this
- * property
- */
- private Integer maxOccurs;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
+
+ public String getDefaultValue() {
+ return defaultValue;
}
+
public String getDescription() {
return description;
}
- public void setDescription(String description) {
- this.description = description;
+
+ public String getMax() {
+ return max;
}
- public String getType() {
- return dataType;
+
+ public Integer getMaxOccurs() {
+ return maxOccurs;
}
- public void setType(String type) {
- this.dataType = type;
+
+ public String getMin() {
+ return min;
}
- public String getDefaultValue() {
- return defaultValue;
+
+ public Integer getMinOccurs() {
+ return minOccurs;
}
- public void setDefaultValue(String defaultValue) {
- this.defaultValue = defaultValue;
+
+ public String getName() {
+ return name;
}
+
public List<String> getPossibleValues() {
return possibleValues;
}
- public void setPossibleValues(List<String> possibleValues) {
- this.possibleValues = possibleValues;
+
+ public String getType() {
+ return dataType;
}
- public String getMin() {
- return min;
+
+ public boolean isUniqueItems() {
+ return uniqueItems;
}
- public void setMin(String min) {
- this.min = min;
+
+ public void setDefaultValue(String defaultValue) {
+ this.defaultValue = defaultValue;
}
- public String getMax() {
- return max;
+
+ public void setDescription(String description) {
+ this.description = description;
}
+
public void setMax(String max) {
this.max = max;
}
- public boolean isUniqueItems() {
- return uniqueItems;
- }
- public void setUniqueItems(boolean uniqueItems) {
- this.uniqueItems = uniqueItems;
+
+ public void setMaxOccurs(Integer maxOccurs) {
+ this.maxOccurs = maxOccurs;
}
- public Integer getMinOccurs() {
- return minOccurs;
+
+ public void setMin(String min) {
+ this.min = min;
}
+
public void setMinOccurs(Integer minOccurs) {
this.minOccurs = minOccurs;
}
- public Integer getMaxOccurs() {
- return maxOccurs;
+
+ public void setName(String name) {
+ this.name = name;
}
- public void setMaxOccurs(Integer maxOccurs) {
- this.maxOccurs = maxOccurs;
+
+ public void setPossibleValues(List<String> possibleValues) {
+ this.possibleValues = possibleValues;
+ }
+
+ public void setType(String type) {
+ this.dataType = type;
+ }
+
+ public void setUniqueItems(boolean uniqueItems) {
+ this.uniqueItems = uniqueItems;
}
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Representation.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Representation.java
index 4524407036..a2d4d780cd 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Representation.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Representation.java
@@ -4,59 +4,58 @@
public class Representation {
- /**
- * Name of the representation
- */
- private String name;
-
- /**
- * Textual description of this representation
- */
+ /** Textual description of this representation. */
private String description;
-
- /**
- * Reference to its parent type if any
- */
+
+ /** Name of the representation. */
+ private String name;
+
+ /** Reference to its parent type if any. */
private String parentType;
-
- /**
- * List of variants available for this representation
- */
- private List<Variant> variants;
-
- /**
- * List of this representation's properties
- */
+
+ /** List of this representation's properties. */
private List<Property> properties;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
+
+ /** List of variants available for this representation. */
+ private List<Variant> variants;
+
public String getDescription() {
return description;
}
- public void setDescription(String description) {
- this.description = description;
+
+ public String getName() {
+ return name;
}
+
public String getParentType() {
return parentType;
}
- public void setParentType(String parentType) {
- this.parentType = parentType;
+
+ public List<Property> getProperties() {
+ return properties;
}
+
public List<Variant> getVariants() {
return variants;
}
- public void setVariants(List<Variant> variants) {
- this.variants = variants;
+
+ public void setDescription(String description) {
+ this.description = description;
}
- public List<Property> getProperties() {
- return properties;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setParentType(String parentType) {
+ this.parentType = parentType;
}
+
public void setProperties(List<Property> properties) {
this.properties = properties;
}
+
+ public void setVariants(List<Variant> variants) {
+ this.variants = variants;
+ }
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Resource.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Resource.java
index 36f64d2597..a65bc9354e 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Resource.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Resource.java
@@ -4,55 +4,47 @@
public class Resource {
- /**
- * Name of this resource
- */
+ /** Textual description of this resource */
+ private String description;
+
+ /** Name of this resource */
private String name;
-
- /**
- * Relative path from the endpoint to this resource
- */
- private String resourcePath;
-
- /**
- * List of the APIs this resource provides
- */
+
+ /** List of the APIs this resource provides */
private List<Operation> operations;
-
- /**
- * Textual description of this resource
- */
- private String description;
+
+ /** Relative path from the endpoint to this resource */
+ private String resourcePath;
+
+ public String getDescription() {
+ return description;
+ }
public String getName() {
return name;
}
- public void setName(String name) {
- this.name = name;
+ public List<Operation> getOperations() {
+ return operations;
}
public String getResourcePath() {
return resourcePath;
}
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
+ public void setDescription(String description) {
+ this.description = description;
}
- public List<Operation> getOperations() {
- return operations;
+ public void setName(String name) {
+ this.name = name;
}
public void setOperations(List<Operation> operations) {
this.operations = operations;
}
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
}
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Response.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Response.java
index 20d2a3ce97..e4b50812c2 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Response.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Response.java
@@ -1,71 +1,69 @@
package org.restlet.ext.apispark;
+import org.restlet.data.Status;
+
public class Response {
- /**
- * Name of this response
- */
- private String name;
-
- /**
- * Textual description of this response
- */
+ /** Custom content of the body if any. */
+ private Body body;
+
+ /** Status code of the response */
+ private int code;
+
+ /** Textual description of this response */
private String description;
-
- /**
- * HTTP code for the response
- * See: http://fr.wikipedia.org/wiki/Liste_des_codes_HTTP
- */
- private Integer code;
-
- /**
- * Textual message associated with code in RCF
- * See: http://fr.wikipedia.org/wiki/Liste_des_codes_HTTP
- */
+
+ /** Status message of the response. */
private String message;
-
+
+ /** Name of this response */
+ private String name;
+
/**
- * Custom content of the body if any
+ * Constructor. The default status code is {@link Status#SUCCESS_OK}.
*/
- private Body body;
+ public Response() {
+ setCode(Status.SUCCESS_OK.getCode());
+ setMessage(Status.SUCCESS_OK.getDescription());
+ }
- public String getName() {
- return name;
+ public Body getBody() {
+ return body;
}
- public void setName(String name) {
- this.name = name;
+ public int getCode() {
+ return code;
}
public String getDescription() {
return description;
}
- public void setDescription(String description) {
- this.description = description;
+ public String getMessage() {
+ return message;
}
- public Integer getCode() {
- return code;
+ public String getName() {
+ return name;
+ }
+
+ public void setBody(Body body) {
+ this.body = body;
}
- public void setCode(Integer code) {
+ public void setCode(int code) {
this.code = code;
}
- public String getMessage() {
- return message;
+ public void setDescription(String description) {
+ this.description = description;
}
public void setMessage(String message) {
this.message = message;
}
- public Body getBody() {
- return body;
- }
-
- public void setBody(Body body) {
- this.body = body;
+ public void setName(String name) {
+ this.name = name;
}
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Variant.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Variant.java
index 772478d232..a302c63414 100644
--- a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Variant.java
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/Variant.java
@@ -2,29 +2,25 @@
public class Variant {
- /**
- * Textual description of this variant
- */
- private String description;
-
- /**
- * Must be a MIME type
- */
+ /** Must be a MIME type. */
private String dataType;
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
+ /** Textual description of this variant. */
+ private String description;
public String getDataType() {
return dataType;
}
+ public String getDescription() {
+ return description;
+ }
+
public void setDataType(String dataType) {
this.dataType = dataType;
}
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkApplication.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkApplication.java
new file mode 100644
index 0000000000..6d6a1766f6
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkApplication.java
@@ -0,0 +1,855 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+
+import org.restlet.Application;
+import org.restlet.Component;
+import org.restlet.Context;
+import org.restlet.Request;
+import org.restlet.Response;
+import org.restlet.Restlet;
+import org.restlet.Server;
+import org.restlet.data.MediaType;
+import org.restlet.data.Method;
+import org.restlet.data.Protocol;
+import org.restlet.data.Reference;
+import org.restlet.data.Status;
+import org.restlet.engine.Engine;
+import org.restlet.representation.Representation;
+import org.restlet.representation.Variant;
+import org.restlet.resource.Directory;
+import org.restlet.resource.Finder;
+import org.restlet.resource.ServerResource;
+import org.restlet.routing.Filter;
+import org.restlet.routing.Route;
+import org.restlet.routing.Router;
+import org.restlet.routing.TemplateRoute;
+import org.restlet.routing.VirtualHost;
+
+/**
+ * APISpark enabled application. This {@link Application} subclass can describe
+ * itself in APISpark by introspecting its content. You can obtain this
+ * representation with an OPTIONS request addressed exactly to the application
+ * URI (e.g. "http://host:port/path/to/application"). By default, the returned
+ * representation gleans the list of all attached {@link ServerResource} classes
+ * and calls {@link #getName()} to get the title and {@link #getDescription()}
+ * the textual content of the APISpark document generated. This default behavior
+ * can be customized by overriding the
+ * {@link #getApplicationInfo(Request, Response)} method.<br>
+ * <br>
+ * In case you want to customize the XSLT stylesheet, you can override the
+ * {@link #createAPISparkRepresentation(ApplicationInfo)} method and return an
+ * instance of an {@link ApisparkRepresentation} subclass overriding the
+ * {@link ApisparkRepresentation#getHtmlRepresentation()} method.<br>
+ * <br>
+ * In addition, this class can create an instance and configure it with an
+ * user-provided APISpark/XML document. In this case, it creates a root
+ * {@link Router} and for each resource found in the APISpark document, it tries
+ * to attach a {@link ServerResource} class to the router using its APISpark
+ * path. For this, it looks up the qualified name of the {@link ServerResource}
+ * subclass using the APISpark's "id" attribute of the "resource" elements. This
+ * is the only Restlet specific convention on the original APISpark document.<br>
+ * <br>
+ * To attach an application configured in this way to an existing component, you
+ * can call the {@link #attachToComponent(Component)} or the
+ * {@link #attachToHost(VirtualHost)} methods. In this case, it uses the "base"
+ * attribute of the APISpark "resources" element as the URI attachment path to
+ * the virtual host.<br>
+ * <br>
+ * Concurrency note: instances of this class or its subclasses can be invoked by
+ * several threads at the same time and therefore must be thread-safe. You
+ * should be especially careful when storing state in member variables. <br>
+ *
+ * @author Jerome Louvel
+ */
+public class ApisparkApplication extends Application {
+
+ /**
+ * Indicates if the application should be automatically described via
+ * APISpark when an OPTIONS request handles a "*" target URI.
+ */
+ private volatile boolean autoDescribing;
+
+ /** The APISpark base reference. */
+ private volatile Reference baseRef;
+
+ /** The router to {@link ServerResource} classes. */
+ private volatile Router router;
+
+ /**
+ * Creates an application that can automatically introspect and expose
+ * itself as with a APISpark description upon reception of an OPTIONS
+ * request on the "*" target URI.
+ */
+ public ApisparkApplication() {
+ this((Context) null);
+ }
+
+ /**
+ * Creates an application that can automatically introspect and expose
+ * itself as with a APISpark description upon reception of an OPTIONS
+ * request on the "*" target URI.
+ *
+ * @param context
+ * The context to use based on parent component context. This
+ * context should be created using the
+ * {@link Context#createChildContext()} method to ensure a proper
+ * isolation with the other applications.
+ */
+ public ApisparkApplication(Context context) {
+ super(context);
+ this.autoDescribing = true;
+ }
+
+ /**
+ * Creates an application described using a APISpark document. Creates a
+ * router where Resource classes are attached and set it as the root
+ * Restlet.
+ *
+ * By default the application is not automatically described. If you want
+ * to, you can call {@link #setAutoDescribing(boolean)}.
+ *
+ * @param context
+ * The context to use based on parent component context. This
+ * context should be created using the
+ * {@link Context#createChildContext()} method to ensure a proper
+ * isolation with the other applications.
+ * @param apispark
+ * The APISpark description document.
+ */
+ public ApisparkApplication(Context context, Representation apispark) {
+ super(context);
+ this.autoDescribing = false;
+
+ try {
+ // Instantiates a APISparkRepresentation of the APISpark document
+ ApisparkRepresentation apisparkRep = null;
+
+ if (apispark instanceof ApisparkRepresentation) {
+ apisparkRep = (ApisparkRepresentation) apispark;
+ } else {
+ // TODO to be done
+ // apisparkRep = new APISparkRepresentation(apispark);
+ }
+
+ final Router root = new Router(getContext());
+ this.router = root;
+ setInboundRoot(root);
+
+ if (apisparkRep.getApplication() != null) {
+ if (apisparkRep.getApplication().getResources() != null) {
+ for (final ResourceInfo resource : apisparkRep
+ .getApplication().getResources().getResources()) {
+ attachResource(resource, null, this.router);
+ }
+
+ // Analyzes the APISpark resources base
+ setBaseRef(apisparkRep.getApplication().getResources()
+ .getBaseRef());
+ }
+
+ // Set the name of the application as the title of the first
+ // documentation tag.
+ if (!apisparkRep.getApplication().getDocumentations().isEmpty()) {
+ setName(apisparkRep.getApplication().getDocumentations()
+ .get(0).getTitle());
+ }
+ }
+ } catch (Exception e) {
+ getLogger().log(Level.WARNING,
+ "Error during the attachment of the APISpark application",
+ e);
+ }
+ }
+
+ /**
+ * Creates an application described using a APISpark document. Creates a
+ * router where Resource classes are attached and set it as the root
+ * Restlet.
+ *
+ * By default the application is not automatically described. If you want
+ * to, you can call {@link #setAutoDescribing(boolean)}.
+ *
+ * @param apispark
+ * The APISpark description document.
+ */
+ public ApisparkApplication(Representation apispark) {
+ this(null, apispark);
+ }
+
+ /**
+ * Adds the necessary server connectors to the component.
+ *
+ * @param component
+ * The parent component to update.
+ */
+ private void addConnectors(Component component) {
+ // Create the server connector
+ Protocol protocol = getBaseRef().getSchemeProtocol();
+ int port = getBaseRef().getHostPort();
+ boolean exists = false;
+
+ if (port == -1) {
+ for (Server server : component.getServers()) {
+ if (server.getProtocols().contains(protocol)
+ && (server.getPort() == protocol.getDefaultPort())) {
+ exists = true;
+ }
+ }
+
+ if (!exists) {
+ component.getServers().add(protocol);
+ }
+ } else {
+ for (Server server : component.getServers()) {
+ if (server.getProtocols().contains(protocol)
+ && (server.getPort() == port)) {
+ exists = true;
+ }
+ }
+
+ if (!exists) {
+ component.getServers().add(protocol, port);
+ }
+ }
+ }
+
+ /**
+ * Represents the resource as a APISpark description.
+ *
+ * @param request
+ * The current request.
+ * @param response
+ * The current response.
+ * @return The APISpark description.
+ */
+ protected Representation apisparkRepresent(Request request,
+ Response response) {
+ return apisparkRepresent(getPreferredAPISparkVariant(request), request,
+ response);
+ }
+
+ /**
+ * Represents the resource as a APISpark description for the given variant.
+ *
+ * @param variant
+ * The APISpark variant.
+ * @param request
+ * The current request.
+ * @param response
+ * The current response.
+ * @return The APISpark description.
+ */
+ protected Representation apisparkRepresent(Variant variant,
+ Request request, Response response) {
+ Representation result = null;
+
+ if (variant != null) {
+ ApplicationInfo applicationInfo = getApplicationInfo(request,
+ response);
+ DocumentationInfo doc = null;
+
+ if ((getName() != null) && !"".equals(getName())) {
+ if (applicationInfo.getDocumentations().isEmpty()) {
+ doc = new DocumentationInfo();
+ applicationInfo.getDocumentations().add(doc);
+ } else {
+ doc = applicationInfo.getDocumentations().get(0);
+ }
+
+ doc.setTitle(getName());
+ }
+
+ if ((doc != null) && (getDescription() != null)
+ && !"".equals(getDescription())) {
+ doc.setTextContent(getDescription());
+ }
+
+ if (MediaType.APPLICATION_JSON.equals(variant.getMediaType())) {
+ result = createAPISparkRepresentation(applicationInfo);
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Attaches a resource, as specified in a APISpark document, to a specified
+ * router, then recursively attaches its child resources.
+ *
+ * @param currentResource
+ * The resource to attach.
+ * @param parentResource
+ * The parent resource. Needed to correctly resolve the "path" of
+ * the resource. Should be null if the resource is root-level.
+ * @param router
+ * The router to which to attach the resource and its children.
+ * @throws ClassNotFoundException
+ * If the class name specified in the "id" attribute of the
+ * resource does not exist, this exception will be thrown.
+ */
+ private void attachResource(ResourceInfo currentResource,
+ ResourceInfo parentResource, Router router)
+ throws ClassNotFoundException {
+
+ String uriPattern = currentResource.getPath();
+
+ // If there is a parentResource, add its uriPattern to this one
+ if (parentResource != null) {
+ String parentUriPattern = parentResource.getPath();
+
+ if ((parentUriPattern.endsWith("/") == false)
+ && (uriPattern.startsWith("/") == false)) {
+ parentUriPattern += "/";
+ }
+
+ uriPattern = parentUriPattern + uriPattern;
+ currentResource.setPath(uriPattern);
+ } else if (!uriPattern.startsWith("/")) {
+ uriPattern = "/" + uriPattern;
+ currentResource.setPath(uriPattern);
+ }
+
+ Finder finder = createFinder(router, uriPattern, currentResource);
+
+ if (finder != null) {
+ // Attach the resource itself
+ router.attach(uriPattern, finder);
+ }
+
+ // Attach children of the resource
+ for (ResourceInfo childResource : currentResource.getChildResources()) {
+ attachResource(childResource, currentResource, router);
+ }
+ }
+
+ /**
+ * Attaches the application to the given component if the application has a
+ * APISpark base reference. The application will be attached to an existing
+ * virtual host if possible, otherwise a new one will be created.
+ *
+ * @param component
+ * The parent component to update.
+ * @return The parent virtual host.
+ */
+ public VirtualHost attachToComponent(Component component) {
+ VirtualHost result = null;
+
+ if (getBaseRef() != null) {
+ // Create the virtual host
+ result = getVirtualHost(component);
+
+ // Attach the application to the virtual host
+ attachToHost(result);
+
+ // Adds the necessary server connectors
+ addConnectors(component);
+ } else {
+ getLogger()
+ .warning(
+ "The APISpark application has no base reference defined. Unable to guess the virtual host.");
+ }
+
+ return result;
+ }
+
+ /**
+ * Attaches the application to the given host using the APISpark base
+ * reference.
+ *
+ * @param host
+ * The virtual host to attach to.
+ */
+ public void attachToHost(VirtualHost host) {
+ if (getBaseRef() != null) {
+ final String path = getBaseRef().getPath();
+ if (path == null) {
+ host.attach("", this);
+ } else {
+ host.attach(path, this);
+ }
+
+ } else {
+ getLogger()
+ .warning(
+ "The APISpark application has no base reference defined. Unable to guess the virtual host.");
+ }
+ }
+
+ /**
+ * Indicates if the application and all its resources can be described using
+ * APISpark.
+ *
+ * @param remainingPart
+ * The URI remaining part.
+ * @param request
+ * The request to handle.
+ * @param response
+ * The response to update.
+ */
+ protected boolean canDescribe(String remainingPart, Request request,
+ Response response) {
+ return isAutoDescribing()
+ && Method.OPTIONS.equals(request.getMethod())
+ && (response.getStatus().isClientError() || !response
+ .isEntityAvailable())
+ && ("/".equals(remainingPart) || "".equals(remainingPart));
+ }
+
+ /**
+ * Creates a new APISpark representation for a given {@link ApplicationInfo}
+ * instance describing an application.
+ *
+ * @param applicationInfo
+ * The application description.
+ * @return The created {@link ApisparkRepresentation}.
+ */
+ protected Representation createAPISparkRepresentation(
+ ApplicationInfo applicationInfo) {
+ return new ApisparkRepresentation(applicationInfo);
+ }
+
+ /**
+ * Creates a finder for the given resource info. By default, it looks up for
+ * an "id" attribute containing a fully qualified class name.
+ *
+ * @param router
+ * The parent router.
+ * @param resourceInfo
+ * The APISpark resource descriptor.
+ * @return The created finder.
+ * @throws ClassNotFoundException
+ */
+ @SuppressWarnings("unchecked")
+ protected Finder createFinder(Router router, String uriPattern,
+ ResourceInfo resourceInfo) throws ClassNotFoundException {
+ Finder result = null;
+
+ if (resourceInfo.getIdentifier() != null) {
+ // The "id" attribute conveys the target class name
+ Class<? extends ServerResource> targetClass = (Class<? extends ServerResource>) Engine
+ .loadClass(resourceInfo.getIdentifier());
+ result = router.createFinder(targetClass);
+ } else {
+ getLogger()
+ .fine("Unable to find the 'id' attribute of the resource element with this path attribute \""
+ + uriPattern + "\"");
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the available APISpark variants.
+ *
+ * @return The available APISpark variants.
+ */
+ protected List<Variant> getAPISparkVariants() {
+ final List<Variant> result = new ArrayList<Variant>();
+ result.add(new Variant(MediaType.APPLICATION_JSON));
+ result.add(new Variant(MediaType.APPLICATION_XML));
+ result.add(new Variant(MediaType.TEXT_XML));
+ return result;
+ }
+
+ /**
+ * Returns a APISpark description of the current application. By default,
+ * this method discovers all the resources attached to this application. It
+ * can be overridden to add documentation, list of representations, etc.
+ *
+ * @param request
+ * The current request.
+ * @param response
+ * The current response.
+ * @return An application description.
+ */
+ protected ApplicationInfo getApplicationInfo(Request request,
+ Response response) {
+ ApplicationInfo applicationInfo = new ApplicationInfo();
+ applicationInfo.getResources().setBaseRef(
+ request.getResourceRef().getBaseRef());
+ applicationInfo.getResources().setResources(
+ getResourceInfos(applicationInfo,
+ getNextRouter(getInboundRoot()), request, response));
+ return applicationInfo;
+ }
+
+ /**
+ * Returns the APISpark base reference.
+ *
+ * @return The APISpark base reference.
+ */
+ public Reference getBaseRef() {
+ return this.baseRef;
+ }
+
+ /**
+ * Returns the next router available.
+ *
+ * @param current
+ * The current Restlet to inspect.
+ * @return The first router available.
+ */
+ private Router getNextRouter(Restlet current) {
+ Router result = getRouter();
+
+ if (result == null) {
+ if (current instanceof Router) {
+ result = (Router) current;
+ } else if (current instanceof Filter) {
+ result = getNextRouter(((Filter) current).getNext());
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the preferred APISpark variant according to the client
+ * preferences specified in the request.
+ *
+ * @param request
+ * The request including client preferences.
+ * @return The preferred APISpark variant.
+ */
+ protected Variant getPreferredAPISparkVariant(Request request) {
+ return getConnegService().getPreferredVariant(getAPISparkVariants(),
+ request, getMetadataService());
+ }
+
+ /**
+ * Completes the data available about a given Filter instance.
+ *
+ * @param applicationInfo
+ * The parent application.
+ * @param filter
+ * The Filter instance to document.
+ * @param path
+ * The base path.
+ * @param request
+ * The current request.
+ * @param response
+ * The current response.
+ * @return The resource description.
+ */
+ private ResourceInfo getResourceInfo(ApplicationInfo applicationInfo,
+ Filter filter, String path, Request request, Response response) {
+ return getResourceInfo(applicationInfo, filter.getNext(), path,
+ request, response);
+ }
+
+ /**
+ * Completes the data available about a given Finder instance.
+ *
+ * @param applicationInfo
+ * The parent application.
+ * @param resourceInfo
+ * The ResourceInfo object to complete.
+ * @param finder
+ * The Finder instance to document.
+ * @param request
+ * The current request.
+ * @param response
+ * The current response.
+ */
+ private ResourceInfo getResourceInfo(ApplicationInfo applicationInfo,
+ Finder finder, String path, Request request, Response response) {
+ ResourceInfo result = null;
+ Object resource = null;
+
+ // Save the current application
+ Application.setCurrent(this);
+
+ if (finder instanceof Directory) {
+ resource = finder;
+ } else {
+ // The handler instance targeted by this finder.
+ ServerResource sr = finder.find(request, response);
+
+ if (sr != null) {
+ sr.init(getContext(), request, response);
+ sr.updateAllowedMethods();
+ resource = sr;
+ }
+ }
+
+ if (resource != null) {
+ result = new ResourceInfo();
+ ResourceInfo.describe(applicationInfo, result, resource, path);
+ }
+
+ return result;
+ }
+
+ /**
+ * Completes the data available about a given Restlet instance.
+ *
+ * @param applicationInfo
+ * The parent application.
+ * @param resourceInfo
+ * The ResourceInfo object to complete.
+ * @param restlet
+ * The Restlet instance to document.
+ * @param request
+ * The current request.
+ * @param response
+ * The current response.
+ */
+ private ResourceInfo getResourceInfo(ApplicationInfo applicationInfo,
+ Restlet restlet, String path, Request request, Response response) {
+ ResourceInfo result = null;
+
+ if (restlet instanceof ApisparkDescribable) {
+ result = ((ApisparkDescribable) restlet)
+ .getResourceInfo(applicationInfo);
+ result.setPath(path);
+ } else if (restlet instanceof Finder) {
+ result = getResourceInfo(applicationInfo, (Finder) restlet, path,
+ request, response);
+ } else if (restlet instanceof Router) {
+ result = new ResourceInfo();
+ result.setPath(path);
+ result.setChildResources(getResourceInfos(applicationInfo,
+ (Router) restlet, request, response));
+ } else if (restlet instanceof Filter) {
+ result = getResourceInfo(applicationInfo, (Filter) restlet, path,
+ request, response);
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the APISpark data about the given Route instance.
+ *
+ * @param applicationInfo
+ * The parent application.
+ * @param route
+ * The Route instance to document.
+ * @param basePath
+ * The base path.
+ * @param request
+ * The current request.
+ * @param response
+ * The current response.
+ * @return The APISpark data about the given Route instance.
+ */
+ private ResourceInfo getResourceInfo(ApplicationInfo applicationInfo,
+ Route route, String basePath, Request request, Response response) {
+ ResourceInfo result = null;
+
+ if (route instanceof TemplateRoute) {
+ TemplateRoute templateRoute = (TemplateRoute) route;
+ String path = templateRoute.getTemplate().getPattern();
+
+ // APISpark requires resource paths to be relative to parent path
+ if (path.startsWith("/") && basePath.endsWith("/")) {
+ path = path.substring(1);
+ }
+
+ result = getResourceInfo(applicationInfo, route.getNext(), path,
+ request, response);
+ }
+
+ return result;
+ }
+
+ /**
+ * Completes the list of ResourceInfo instances for the given Router
+ * instance.
+ *
+ * @param applicationInfo
+ * The parent application.
+ * @param router
+ * The router to document.
+ * @param request
+ * The current request.
+ * @param response
+ * The current response.
+ * @return The list of ResourceInfo instances to complete.
+ */
+ private List<ResourceInfo> getResourceInfos(
+ ApplicationInfo applicationInfo, Router router, Request request,
+ Response response) {
+ List<ResourceInfo> result = new ArrayList<ResourceInfo>();
+
+ for (Route route : router.getRoutes()) {
+ ResourceInfo resourceInfo = getResourceInfo(applicationInfo, route,
+ "/", request, response);
+
+ if (resourceInfo != null) {
+ result.add(resourceInfo);
+ }
+ }
+
+ if (router.getDefaultRoute() != null) {
+ ResourceInfo resourceInfo = getResourceInfo(applicationInfo,
+ router.getDefaultRoute(), "/", request, response);
+ if (resourceInfo != null) {
+ result.add(resourceInfo);
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the router where the {@link ServerResource} classes created from
+ * the APISpark description document are attached.
+ *
+ * @return The root router.
+ */
+ public Router getRouter() {
+ return this.router;
+ }
+
+ /**
+ * Returns the virtual host matching the APISpark application's base
+ * reference. Creates a new one and attaches it to the component if
+ * necessary.
+ *
+ * @param component
+ * The parent component.
+ * @return The related virtual host.
+ */
+ private VirtualHost getVirtualHost(Component component) {
+ // Create the virtual host if necessary
+ final String hostDomain = this.baseRef.getHostDomain();
+ final String hostPort = Integer.toString(this.baseRef.getHostPort());
+ final String hostScheme = this.baseRef.getScheme();
+
+ VirtualHost host = null;
+ for (final VirtualHost vh : component.getHosts()) {
+ if (vh.getHostDomain().equals(hostDomain)
+ && vh.getHostPort().equals(hostPort)
+ && vh.getHostScheme().equals(hostScheme)) {
+ host = vh;
+ }
+ }
+
+ if (host == null) {
+ // A new virtual host needs to be created
+ host = new VirtualHost(component.getContext().createChildContext());
+ host.setHostDomain(hostDomain);
+ host.setHostPort(hostPort);
+ host.setHostScheme(hostScheme);
+ component.getHosts().add(host);
+ }
+
+ return host;
+ }
+
+ /**
+ * Handles the requests normally in all cases then handles the special case
+ * of the OPTIONS requests that exactly target the application. In this
+ * case, the application is automatically introspected and described as a
+ * APISpark representation based on the result of the
+ * {@link #getApplicationInfo(Request, Response)} method.<br>
+ * The automatic introspection happens only if the request hasn't already
+ * been successfully handled. That is to say, it lets users provide their
+ * own handling of OPTIONS requests.
+ *
+ * @param request
+ * The request to handle.
+ * @param response
+ * The response to update.
+ */
+ @Override
+ public void handle(Request request, Response response) {
+ // Preserve the resource reference.
+ Reference rr = request.getResourceRef().clone();
+
+ // Do the regular handling
+ super.handle(request, response);
+
+ // Restore the resource reference
+ request.setResourceRef(rr);
+
+ // Handle OPTIONS requests.
+ String rp = rr.getRemainingPart(false, false);
+
+ if (canDescribe(rp, request, response)) {
+ // Make sure that the base of the "resources" element ends with a
+ // "/".
+ if (!rr.getBaseRef().getIdentifier().endsWith("/")) {
+ rr.setBaseRef(rr.getBaseRef() + "/");
+ }
+
+ // Returns a APISpark representation of the application.
+ response.setEntity(apisparkRepresent(request, response));
+
+ if (response.isEntityAvailable()) {
+ response.setStatus(Status.SUCCESS_OK);
+ }
+ }
+ }
+
+ /**
+ * Indicates if the application should be automatically described via
+ * APISpark when an OPTIONS request handles a "*" target URI.
+ *
+ * @return True if the application should be automatically described via
+ * APISpark.
+ */
+ public boolean isAutoDescribing() {
+ return autoDescribing;
+ }
+
+ /**
+ * Indicates if the application should be automatically described via
+ * APISpark when an OPTIONS request handles a "*" target URI.
+ *
+ * @param autoDescribed
+ * True if the application should be automatically described via
+ * APISpark.
+ */
+ public void setAutoDescribing(boolean autoDescribed) {
+ this.autoDescribing = autoDescribed;
+ }
+
+ /**
+ * Sets the APISpark base reference.
+ *
+ * @param baseRef
+ * The APISpark base reference.
+ */
+ public void setBaseRef(Reference baseRef) {
+ this.baseRef = baseRef;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkComponent.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkComponent.java
new file mode 100644
index 0000000000..0dd6b985b1
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkComponent.java
@@ -0,0 +1,176 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import org.restlet.Component;
+import org.restlet.Request;
+import org.restlet.Response;
+import org.restlet.data.Method;
+import org.restlet.data.Reference;
+import org.restlet.representation.Representation;
+
+/**
+ * Component that can configure itself given a APISpark document. First, it
+ * creates the server connectors and the virtual hosts if needed, trying to
+ * reuse existing ones if available. Then it creates a
+ * {@link ApisparkApplication} using this
+ * {@link ApisparkApplication#APISparkApplication(Representation)} constructor.<br>
+ * <br>
+ * Concurrency note: instances of this class or its subclasses can be invoked by
+ * several threads at the same time and therefore must be thread-safe. You
+ * should be especially careful when storing state in member variables.
+ *
+ * @author Jerome Louvel
+ */
+public class ApisparkComponent extends Component {
+
+ /**
+ * Main method capable of configuring and starting a whole Restlet Component
+ * based on a list of local APISpark documents URIs, for example
+ * "file:///C:/YahooSearch.apispark".<br>
+ * <br>
+ * The necessary client connectors are automatically created.
+ *
+ * @param args
+ * List of local APISpark document URIs.
+ * @throws Exception
+ */
+ public static void main(String[] args) throws Exception {
+ // Create a new APISpark-aware component
+ final ApisparkComponent component = new ApisparkComponent();
+
+ // For each APISpark document URI attach a matching Application
+ for (final String arg : args) {
+ component.attach(arg);
+ }
+
+ // Start the component
+ component.start();
+ }
+
+ /**
+ * Default constructor.
+ */
+ public ApisparkComponent() {
+ }
+
+ /**
+ * Constructor loading a APISpark description document at a given URI.<br>
+ * <br>
+ * The necessary client connectors are automatically created.
+ *
+ * @param apisparkRef
+ * The URI reference to the APISpark description document.
+ */
+ public ApisparkComponent(Reference apisparkRef) {
+ attach(apisparkRef);
+ }
+
+ /**
+ * Constructor based on a given APISpark description document.
+ *
+ * @param apispark
+ * The APISpark description document.
+ */
+ public ApisparkComponent(Representation apispark) {
+ attach(apispark);
+ }
+
+ /**
+ * Constructor loading a APISpark description document at a given URI.<br>
+ * <br>
+ * The necessary client connectors are automatically created.
+ *
+ * @param apisparkUri
+ * The URI to the APISpark description document.
+ */
+ public ApisparkComponent(String apisparkUri) {
+ attach(apisparkUri);
+ }
+
+ /**
+ * Attaches an application created from a APISpark description document
+ * available at a given URI reference.
+ *
+ * @param apisparkRef
+ * The URI reference to the APISpark description document.
+ * @return The created APISpark application.
+ */
+ public ApisparkApplication attach(Reference apisparkRef) {
+ ApisparkApplication result = null;
+
+ // Adds some common client connectors to load the APISpark documents
+ if (!getClients().contains(apisparkRef.getSchemeProtocol())) {
+ getClients().add(apisparkRef.getSchemeProtocol());
+ }
+
+ // Get the APISpark document
+ final Response response = getContext().getClientDispatcher().handle(
+ new Request(Method.GET, apisparkRef));
+
+ if (response.getStatus().isSuccess() && response.isEntityAvailable()) {
+ result = attach(response.getEntity());
+ }
+
+ return result;
+ }
+
+ /**
+ * Attaches an application created from a APISpark description document to
+ * the component.
+ *
+ * @param apispark
+ * The APISpark description document.
+ * @return The created APISpark application.
+ */
+ public ApisparkApplication attach(Representation apispark) {
+ final ApisparkApplication result = new ApisparkApplication(getContext()
+ .createChildContext(), apispark);
+ result.attachToComponent(this);
+ return result;
+ }
+
+ /**
+ * Attaches an application created from a APISpark description document
+ * available at a given URI.
+ *
+ * @param apisparkUri
+ * The URI to the APISpark description document.
+ * @return The created APISpark application.
+ */
+ public ApisparkApplication attach(String apisparkUri) {
+ return attach(new Reference(apisparkUri));
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkConverter.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkConverter.java
new file mode 100644
index 0000000000..76479f8c63
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkConverter.java
@@ -0,0 +1,141 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.restlet.data.MediaType;
+import org.restlet.data.Preference;
+import org.restlet.engine.converter.ConverterHelper;
+import org.restlet.engine.resource.VariantInfo;
+import org.restlet.representation.Representation;
+import org.restlet.representation.Variant;
+import org.restlet.resource.Resource;
+
+/**
+ * A converter helper to convert between {@link ApplicationInfo} objects and
+ * {@link ApisparkRepresentation} ones.
+ *
+ * @author Thierry Boileau
+ */
+public class ApisparkConverter extends ConverterHelper {
+
+ private static final VariantInfo VARIANT_APPLICATION_SWAGGER = new VariantInfo(
+ MediaType.APPLICATION_JSON);
+
+ @Override
+ public List<Class<?>> getObjectClasses(Variant source) {
+ List<Class<?>> result = null;
+
+ if (VARIANT_APPLICATION_SWAGGER.includes(source)) {
+ result = addObjectClass(result, ApplicationInfo.class);
+ }
+
+ return result;
+ }
+
+ @Override
+ public List<VariantInfo> getVariants(Class<?> source) {
+ List<VariantInfo> result = null;
+
+ if (ApplicationInfo.class.isAssignableFrom(source)) {
+ result = addVariant(result, VARIANT_APPLICATION_SWAGGER);
+ }
+
+ return result;
+ }
+
+ @Override
+ public float score(Object source, Variant target, Resource resource) {
+ if (source instanceof ApplicationInfo) {
+ return 1.0f;
+ }
+
+ return -1.0f;
+ }
+
+ @Override
+ public <T> float score(Representation source, Class<T> target,
+ Resource resource) {
+ float result = -1.0F;
+
+ if ((source != null)
+ && (ApplicationInfo.class.isAssignableFrom(target))) {
+ result = 1.0F;
+ }
+
+ return result;
+ }
+
+ @Override
+ public <T> T toObject(Representation source, Class<T> target,
+ Resource resource) throws IOException {
+ ApisparkRepresentation apisparkSource = null;
+ if (source instanceof ApisparkRepresentation) {
+ apisparkSource = (ApisparkRepresentation) source;
+ } else {
+ // TODO
+ // apisparkSource = new APISparkRepresentation(source);
+ }
+
+ T result = null;
+ if (target != null) {
+ if (ApplicationInfo.class.isAssignableFrom(target)) {
+ result = target.cast(apisparkSource.getApplication());
+ }
+ }
+
+ return result;
+ }
+
+ @Override
+ public Representation toRepresentation(Object source, Variant target,
+ Resource resource) throws IOException {
+ if (source instanceof ApplicationInfo) {
+ return new ApisparkRepresentation((ApplicationInfo) source);
+ }
+
+ return null;
+ }
+
+ @Override
+ public <T> void updatePreferences(List<Preference<MediaType>> preferences,
+ Class<T> entity) {
+ if (ApplicationInfo.class.isAssignableFrom(entity)) {
+ updatePreferences(preferences, MediaType.APPLICATION_JSON, 1.0F);
+ updatePreferences(preferences, MediaType.APPLICATION_XML, 0.9F);
+ }
+ }
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkDescribable.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkDescribable.java
new file mode 100644
index 0000000000..6de8f3a68d
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkDescribable.java
@@ -0,0 +1,60 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import org.restlet.resource.Directory;
+import org.restlet.resource.ServerResource;
+
+/**
+ * Interface that any Restlet can implement in order to provide their own
+ * APISpark documentation. This is especially useful for subclasses of
+ * {@link Directory} or other resource finders when the APISpark introspection
+ * can't reach {@link ServerResource} or better {@link ApisparkServerResource}
+ * instances.
+ *
+ * @author Thierry Boileau
+ */
+public interface ApisparkDescribable {
+
+ /**
+ * Returns a full documented {@link ResourceInfo} instance.
+ *
+ * @param applicationInfo
+ * The parent APISpark application descriptor.
+ *
+ * @return A full documented {@link ResourceInfo} instance.
+ */
+ public ResourceInfo getResourceInfo(ApplicationInfo applicationInfo);
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkRepresentation.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkRepresentation.java
new file mode 100644
index 0000000000..2a5750efde
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkRepresentation.java
@@ -0,0 +1,311 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.restlet.Server;
+import org.restlet.data.Protocol;
+import org.restlet.data.Status;
+import org.restlet.engine.Engine;
+import org.restlet.engine.connector.ConnectorHelper;
+import org.restlet.ext.apispark.Body;
+import org.restlet.ext.apispark.Contract;
+import org.restlet.ext.apispark.Documentation;
+import org.restlet.ext.apispark.Method;
+import org.restlet.ext.apispark.Operation;
+import org.restlet.ext.apispark.Parameter;
+import org.restlet.ext.apispark.PathVariable;
+import org.restlet.ext.apispark.Property;
+import org.restlet.ext.apispark.Representation;
+import org.restlet.ext.apispark.Resource;
+import org.restlet.ext.apispark.Response;
+import org.restlet.ext.apispark.Variant;
+import org.restlet.ext.jackson.JacksonRepresentation;
+
+/**
+ * Root of a APISpark description document.<br>
+ *
+ * @author Jerome Louvel
+ */
+public class ApisparkRepresentation extends
+ JacksonRepresentation<Documentation> {
+
+ private static Documentation toDocumentation(ApplicationInfo application) {
+ Documentation result = null;
+ if (application != null) {
+ result = new Documentation();
+ result.setVersion(application.getVersion());
+
+ Contract contract = new Contract();
+ result.setContract(contract);
+ contract.setDescription(toString(application.getDocumentations()));
+ contract.setName(application.getName());
+
+ // List of representations.
+ contract.setRepresentations(new ArrayList<Representation>());
+ for (RepresentationInfo ri : application.getRepresentations()) {
+ Representation rep = new Representation();
+
+ // TODO analyze
+ // The models differ : one representation / one variant for
+ // Restlet
+ // one representation / several variants for APIspark
+ rep.setDescription(toString(ri.getDocumentations()));
+ rep.setName(ri.getIdentifier());
+ Variant variant = new Variant();
+ variant.setDataType(ri.getMediaType().getName());
+ rep.setVariants(new ArrayList<Variant>());
+ rep.getVariants().add(variant);
+
+ rep.setProperties(new ArrayList<Property>());
+ for (int i = 0; i < ri.getParameters().size(); i++) {
+ ParameterInfo pi = ri.getParameters().get(i);
+
+ Property property = new Property();
+ property.setName(pi.getName());
+ property.setDescription(toString(pi.getDocumentations()));
+ property.setType(pi.getType());
+
+ rep.getProperties().add(property);
+ }
+
+ contract.getRepresentations().add(rep);
+ }
+
+ // List of resources.
+ // TODO Resource path/basePath?
+ contract.setResources(new ArrayList<Resource>());
+ for (ResourceInfo ri : application.getResources().getResources()) {
+
+ Resource resource = new Resource();
+ resource.setDescription(toString(ri.getDocumentations()));
+ resource.setName(ri.getIdentifier());
+ resource.setResourcePath(ri.getPath());
+
+ resource.setOperations(new ArrayList<Operation>());
+ int i = 0;
+ for (MethodInfo mi : ri.getMethods()) {
+
+ Operation operation = new Operation();
+ operation.setDescription(toString(mi.getDocumentations()));
+ operation.setName(mi.getName().getName());
+ // TODO complete Method class with mi.getName()
+ operation.setMethod(new Method());
+ operation.getMethod().setDescription(mi.getName().getDescription());
+ operation.getMethod().setName(mi.getName().getName());
+
+ // Complete parameters
+ operation.setHeaders(new ArrayList<Parameter>());
+ operation.setPathVariables(new ArrayList<PathVariable>());
+ operation.setQueryParameters(new ArrayList<Parameter>());
+ if (mi.getRequest() != null
+ && mi.getRequest().getParameters() != null) {
+ for (ParameterInfo pi : mi.getRequest().getParameters()) {
+ if (ParameterStyle.HEADER.equals(pi.getStyle())) {
+ Parameter parameter = new Parameter();
+ parameter.setAllowMultiple(pi.isRepeating());
+ parameter.setDefaultValue(pi.getDefaultValue());
+ parameter.setDescription(toString(pi
+ .getDocumentations()));
+ parameter.setName(pi.getName());
+ parameter
+ .setPossibleValues(new ArrayList<String>());
+ parameter.setRequired(pi.isRequired());
+
+ operation.getHeaders().add(parameter);
+ } else if (ParameterStyle.TEMPLATE.equals(pi
+ .getStyle())) {
+ PathVariable pathVariable = new PathVariable();
+
+ pathVariable.setDescription(toString(pi
+ .getDocumentations()));
+ pathVariable.setName(pi.getName());
+
+ operation.getPathVariables().add(pathVariable);
+ } else if (ParameterStyle.QUERY.equals(pi
+ .getStyle())) {
+ Parameter parameter = new Parameter();
+ parameter.setAllowMultiple(pi.isRepeating());
+ parameter.setDefaultValue(pi.getDefaultValue());
+ parameter.setDescription(toString(pi
+ .getDocumentations()));
+ parameter.setName(pi.getName());
+ parameter
+ .setPossibleValues(new ArrayList<String>());
+ parameter.setRequired(pi.isRequired());
+
+ operation.getHeaders().add(parameter);
+ }
+ }
+ }
+
+ if (mi.getRequest() != null
+ && mi.getRequest().getRepresentations() != null
+ && !mi.getRequest().getRepresentations().isEmpty()) {
+ Body body = new Body();
+ // TODO analyze
+ // The models differ : one representation / one variant
+ // for Restlet one representation / several variants for
+ // APIspark
+ body.setRepresentation(mi.getRequest()
+ .getRepresentations().get(0).getIdentifier());
+
+ operation.setInRepresentation(body);
+ }
+
+ if (mi.getResponses() != null
+ && !mi.getResponses().isEmpty()) {
+ operation.setResponses(new ArrayList<Response>());
+
+ Body body = new Body();
+ // TODO analyze
+ // The models differ : one representation / one variant
+ // for Restlet one representation / several variants for
+ // APIspark
+
+ operation.setOutRepresentation(body);
+
+ for (ResponseInfo rio : mi.getResponses()) {
+ if (!rio.getStatuses().isEmpty()) {
+ Status status = rio.getStatuses().get(0);
+ // TODO analyze
+ // The models differ : one representation / one variant
+ // for Restlet one representation / several variants for
+ // APIspark
+
+ Response response = new Response();
+ response.setBody(body);
+ response.setCode(status.getCode());
+ response.setDescription(toString(rio.getDocumentations()));
+ response.setMessage(status.getDescription());
+ //response.setName();
+
+ operation.getResponses().add(response);
+ }
+ }
+ }
+
+ resource.getOperations().add(operation);
+ }
+
+ contract.getResources().add(resource);
+ }
+
+ java.util.List<String> protocols = new ArrayList<String>();
+ for (ConnectorHelper<Server> helper : Engine.getInstance()
+ .getRegisteredServers()) {
+ for (Protocol protocol : helper.getProtocols()) {
+ if (!protocols.contains(protocol.getName())) {
+ protocols.add(protocol.getName());
+ }
+ }
+ }
+
+ }
+ return result;
+ }
+
+ private static String toString(List<DocumentationInfo> di) {
+ StringBuilder d = new StringBuilder();
+ for (DocumentationInfo doc : di) {
+ d.append(doc.getTextContent());
+ }
+ return d.toString();
+ }
+
+ /** The root element of the APISpark document. */
+ private ApplicationInfo application;
+
+ /**
+ * Constructor.
+ *
+ * @param application
+ * The root element of the APISpark document.
+ */
+ public ApisparkRepresentation(ApplicationInfo application) {
+ super(toDocumentation(application));
+
+ this.application = application;
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param documentation
+ * The description of the APISpark document.
+ */
+ public ApisparkRepresentation(Documentation documentation) {
+ super(documentation);
+ // Transform contract to ApplicationInfo
+ }
+
+ // /**
+ // * Constructor.
+ // *
+ // * @param representation
+ // * The XML APISpark document.
+ // * @throws IOException
+ // */
+ // public APISparkRepresentation(Representation representation)
+ // throws IOException {
+ // super(representation);
+ // setMediaType(MediaType.APPLICATION_JSON);
+ //
+ // // Parse the given document using SAX to produce an ApplicationInfo
+ // // instance.
+ // // parse(new ContentReader(this));
+ // }
+
+ /**
+ * Returns the root element of the APISpark document.
+ *
+ * @return The root element of the APISpark document.
+ */
+ public ApplicationInfo getApplication() {
+ return this.application;
+ }
+
+ /**
+ * Sets the root element of the APISpark document.
+ *
+ * @param application
+ * The root element of the APISpark document.
+ */
+ public void setApplication(ApplicationInfo application) {
+ this.application = application;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkServerResource.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkServerResource.java
new file mode 100644
index 0000000000..a4ca8787d2
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkServerResource.java
@@ -0,0 +1,591 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.restlet.data.Header;
+import org.restlet.data.MediaType;
+import org.restlet.data.Method;
+import org.restlet.data.Parameter;
+import org.restlet.data.Reference;
+import org.restlet.engine.header.HeaderConstants;
+import org.restlet.representation.Representation;
+import org.restlet.representation.Variant;
+import org.restlet.resource.ResourceException;
+import org.restlet.resource.ServerResource;
+import org.restlet.util.NamedValue;
+import org.restlet.util.Series;
+
+/**
+ * Resource that is able to automatically describe itself with APISpark. This
+ * description can be customized by overriding the {@link #describe()} and
+ * {@link #describeMethod(Method, MethodInfo)} methods.<br>
+ * <br>
+ * When used to describe a class of resources in the context of a parent
+ * application, a special instance will be created using the default constructor
+ * (with no request, response associated). In this case, the resource should do
+ * its best to return the generic information when the APISpark description
+ * methods are invoked, like {@link #describe()} and delegate methods.
+ *
+ * @author Jerome Louvel
+ */
+public class ApisparkServerResource extends ServerResource {
+
+ /**
+ * Indicates if the resource should be automatically described via APISpark
+ * when an OPTIONS request is handled.
+ */
+ private volatile boolean autoDescribing;
+
+ /**
+ * The description of this documented resource. Is seen as the text content
+ * of the "doc" tag of the "resource" element in a APISpark document.
+ */
+ private volatile String description;
+
+ /**
+ * The name of this documented resource. Is seen as the title of the "doc"
+ * tag of the "resource" element in a APISpark document.
+ */
+ private volatile String name;
+
+ /**
+ * Constructor.
+ */
+ public ApisparkServerResource() {
+ this.autoDescribing = true;
+ }
+
+ /**
+ * Indicates if the given method exposes its APISpark description. By
+ * default, HEAD and OPTIONS are not exposed. This method is called by
+ * {@link #describe(String, ResourceInfo)}.
+ *
+ * @param method
+ * The method
+ * @return True if the method exposes its description, false otherwise.
+ */
+ public boolean canDescribe(Method method) {
+ return !(Method.HEAD.equals(method) || Method.OPTIONS.equals(method));
+ }
+
+ /**
+ * Creates a new APISpark representation for a given {@link ApplicationInfo}
+ * instance describing an application.
+ *
+ * @param applicationInfo
+ * The application description.
+ * @return The created {@link ApisparkRepresentation}.
+ */
+ protected Representation createAPISparkRepresentation(
+ ApplicationInfo applicationInfo) {
+ return new ApisparkRepresentation(applicationInfo);
+ }
+
+ /**
+ * Describes the resource as a standalone APISpark document.
+ *
+ * @return The APISpark description.
+ */
+ protected Representation describe() {
+ return describe(getPreferredAPISparkVariant());
+ }
+
+ /**
+ * Updates the description of the parent application. This is typically used
+ * to add documentation on global representations used by several methods or
+ * resources. Does nothing by default.
+ *
+ * @param applicationInfo
+ * The parent application.
+ */
+ protected void describe(ApplicationInfo applicationInfo) {
+ }
+
+ /**
+ * Describes a representation class and variant couple as APISpark
+ * information. The variant contains the target media type that can be
+ * converted to by one of the available Restlet converters.
+ *
+ * @param methodInfo
+ * The parent method description.
+ * @param representationClass
+ * The representation bean class.
+ * @param variant
+ * The target variant.
+ * @return The APISpark representation information.
+ */
+ protected RepresentationInfo describe(MethodInfo methodInfo,
+ Class<?> representationClass, Variant variant) {
+ return new RepresentationInfo(variant);
+ }
+
+ /**
+ * Describes a representation class and variant couple as APISpark
+ * information for the given method and request. The variant contains the
+ * target media type that can be converted to by one of the available
+ * Restlet converters.<br>
+ * <br>
+ * By default, it calls {@link #describe(MethodInfo, Class, Variant)}.
+ *
+ * @param methodInfo
+ * The parent method description.
+ * @param requestInfo
+ * The parent request description.
+ * @param representationClass
+ * The representation bean class.
+ * @param variant
+ * The target variant.
+ * @return The APISpark representation information.
+ */
+ protected RepresentationInfo describe(MethodInfo methodInfo,
+ RequestInfo requestInfo, Class<?> representationClass,
+ Variant variant) {
+ return describe(methodInfo, representationClass, variant);
+ }
+
+ /**
+ * Describes a representation class and variant couple as APISpark
+ * information for the given method and response. The variant contains the
+ * target media type that can be converted to by one of the available
+ * Restlet converters.<br>
+ * <br>
+ * By default, it calls {@link #describe(MethodInfo, Class, Variant)}.
+ *
+ * @param methodInfo
+ * The parent method description.
+ * @param responseInfo
+ * The parent response description.
+ * @param representationClass
+ * The representation bean class.
+ * @param variant
+ * The target variant.
+ * @return The APISpark representation information.
+ */
+ protected RepresentationInfo describe(MethodInfo methodInfo,
+ ResponseInfo responseInfo, Class<?> representationClass,
+ Variant variant) {
+ return describe(methodInfo, representationClass, variant);
+ }
+
+ /**
+ * Returns a APISpark description of the current resource, leveraging the
+ * {@link #getResourcePath()} method.
+ *
+ * @param info
+ * APISpark description of the current resource to update.
+ */
+ public void describe(ResourceInfo info) {
+ describe(getResourcePath(), info);
+ }
+
+ /**
+ * Returns a APISpark description of the current resource.
+ *
+ * @param path
+ * Path of the current resource.
+ * @param info
+ * APISpark description of the current resource to update.
+ */
+ public void describe(String path, ResourceInfo info) {
+ ResourceInfo.describe(null, info, this, path);
+ }
+
+ /**
+ * Describes the resource as a APISpark document for the given variant.
+ *
+ * @param variant
+ * The APISpark variant.
+ * @return The APISpark description.
+ */
+ protected Representation describe(Variant variant) {
+ Representation result = null;
+
+ if (variant != null) {
+ ResourceInfo resource = new ResourceInfo();
+ describe(resource);
+ ApplicationInfo application = resource.createApplication();
+ describe(application);
+
+ if (MediaType.APPLICATION_JSON.equals(variant.getMediaType())) {
+ result = createAPISparkRepresentation(application);
+ } else if (MediaType.APPLICATION_XML.equals(variant.getMediaType())) {
+ result = createAPISparkRepresentation(application);
+ } else if (MediaType.TEXT_XML.equals(variant.getMediaType())) {
+ result = createAPISparkRepresentation(application);
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Describes the DELETE method.
+ *
+ * @param info
+ * The method description to update.
+ */
+ protected void describeDelete(MethodInfo info) {
+ MethodInfo.describeAnnotations(info, this);
+ }
+
+ /**
+ * Describes the GET method.<br>
+ * By default, it describes the response with the available variants based
+ * on the {@link #getVariants()} method. Thus in the majority of cases, the
+ * method of the super class must be called when overridden.
+ *
+ * @param info
+ * The method description to update.
+ */
+ protected void describeGet(MethodInfo info) {
+ MethodInfo.describeAnnotations(info, this);
+ }
+
+ /**
+ * Returns a APISpark description of the current method.
+ *
+ * @return A APISpark description of the current method.
+ */
+ protected MethodInfo describeMethod() {
+ MethodInfo result = new MethodInfo();
+ describeMethod(getMethod(), result);
+ return result;
+ }
+
+ /**
+ * Returns a APISpark description of the given method.
+ *
+ * @param method
+ * The method to describe.
+ * @param info
+ * The method description to update.
+ */
+ protected void describeMethod(Method method, MethodInfo info) {
+ info.setName(method);
+
+ if (Method.GET.equals(method)) {
+ describeGet(info);
+ } else if (Method.POST.equals(method)) {
+ describePost(info);
+ } else if (Method.PUT.equals(method)) {
+ describePut(info);
+ } else if (Method.DELETE.equals(method)) {
+ describeDelete(info);
+ } else if (Method.OPTIONS.equals(method)) {
+ describeOptions(info);
+ } else if (Method.PATCH.equals(method)) {
+ describePatch(info);
+ }
+ }
+
+ /**
+ * Describes the OPTIONS method.<br>
+ * By default it describes the response with the available variants based on
+ * the {@link #getAPISparkVariants()} method.
+ *
+ * @param info
+ * The method description to update.
+ */
+ protected void describeOptions(MethodInfo info) {
+ // Describe each variant
+ for (Variant variant : getAPISparkVariants()) {
+ RepresentationInfo result = new RepresentationInfo(variant);
+ info.getResponse().getRepresentations().add(result);
+ }
+ }
+
+ /**
+ * Returns the description of the parameters of this resource. Returns null
+ * by default.
+ *
+ * @return The description of the parameters.
+ */
+ protected List<ParameterInfo> describeParameters() {
+ return null;
+ }
+
+ /**
+ * Describes the Patch method.
+ *
+ * @param info
+ * The method description to update.
+ */
+ protected void describePatch(MethodInfo info) {
+ MethodInfo.describeAnnotations(info, this);
+ }
+
+ /**
+ * Describes the POST method.
+ *
+ * @param info
+ * The method description to update.
+ */
+ protected void describePost(MethodInfo info) {
+ MethodInfo.describeAnnotations(info, this);
+ }
+
+ /**
+ * Describes the PUT method.
+ *
+ * @param info
+ * The method description to update.
+ */
+ protected void describePut(MethodInfo info) {
+ MethodInfo.describeAnnotations(info, this);
+ }
+
+ @Override
+ protected void doInit() throws ResourceException {
+ super.doInit();
+ this.autoDescribing = true;
+ }
+
+ /**
+ * Returns the available APISpark variants.
+ *
+ * @return The available APISpark variants.
+ */
+ protected List<Variant> getAPISparkVariants() {
+ List<Variant> result = new ArrayList<Variant>();
+ result.add(new Variant(MediaType.APPLICATION_JSON));
+ result.add(new Variant(MediaType.TEXT_HTML));
+ return result;
+ }
+
+ /**
+ * Returns the description of this documented resource. Is seen as the text
+ * content of the "doc" tag of the "resource" element in a APISpark
+ * document.
+ *
+ * @return The description of this documented resource.
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * Returns the set of headers as a collection of {@link Parameter} objects.
+ *
+ * @return The set of headers as a collection of {@link Parameter} objects.
+ */
+ @SuppressWarnings("unchecked")
+ private Series<Header> getHeaders() {
+ return (Series<Header>) getRequestAttributes().get(
+ HeaderConstants.ATTRIBUTE_HEADERS);
+ }
+
+ /**
+ * Returns the name of this documented resource. Is seen as the title of the
+ * "doc" tag of the "resource" element in a APISpark document.
+ *
+ * @return The name of this documented resource.
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Returns the first parameter found in the current context (entity, query,
+ * headers, etc) with the given name.
+ *
+ * @param name
+ * The parameter name.
+ * @return The first parameter found with the given name.
+ */
+ protected NamedValue<String> getParameter(String name) {
+ NamedValue<String> result = null;
+ Series<? extends NamedValue<String>> set = getParameters(name);
+
+ if (set != null) {
+ result = set.getFirst(name);
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns a collection of parameters objects contained in the current
+ * context (entity, query, headers, etc) given a ParameterInfo instance.
+ *
+ * @param parameterInfo
+ * The ParameterInfo instance.
+ * @return A collection of parameters objects
+ */
+ private Series<? extends NamedValue<String>> getParameters(
+ ParameterInfo parameterInfo) {
+ Series<? extends NamedValue<String>> result = null;
+
+ if (parameterInfo.getFixed() != null) {
+ result = new Series<Parameter>(Parameter.class);
+ result.add(parameterInfo.getName(), parameterInfo.getFixed());
+ } else if (ParameterStyle.HEADER.equals(parameterInfo.getStyle())) {
+ result = getHeaders().subList(parameterInfo.getName());
+ } else if (ParameterStyle.TEMPLATE.equals(parameterInfo.getStyle())) {
+ Object parameter = getRequest().getAttributes().get(
+ parameterInfo.getName());
+
+ if (parameter != null) {
+ result = new Series<Parameter>(Parameter.class);
+ result.add(parameterInfo.getName(),
+ Reference.decode((String) parameter));
+ }
+ } else if (ParameterStyle.MATRIX.equals(parameterInfo.getStyle())) {
+ result = getMatrix().subList(parameterInfo.getName());
+ } else if (ParameterStyle.QUERY.equals(parameterInfo.getStyle())) {
+ result = getQuery().subList(parameterInfo.getName());
+ } else if (ParameterStyle.PLAIN.equals(parameterInfo.getStyle())) {
+ // TODO not yet implemented.
+ }
+
+ if (result == null && parameterInfo.getDefaultValue() != null) {
+ result = new Series<Parameter>(Parameter.class);
+ result.add(parameterInfo.getName(), parameterInfo.getDefaultValue());
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns a collection of parameters found in the current context (entity,
+ * query, headers, etc) given a parameter name. It returns null if the
+ * parameter name is unknown.
+ *
+ * @param name
+ * The name of the parameter.
+ * @return A collection of parameters.
+ */
+ protected Series<? extends NamedValue<String>> getParameters(String name) {
+ Series<? extends NamedValue<String>> result = null;
+
+ if (describeParameters() != null) {
+ for (ParameterInfo parameter : describeParameters()) {
+ if (name.equals(parameter.getName())) {
+ result = getParameters(parameter);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the preferred APISpark variant according to the client
+ * preferences specified in the request.
+ *
+ * @return The preferred APISpark variant.
+ */
+ protected Variant getPreferredAPISparkVariant() {
+ return getConnegService().getPreferredVariant(getAPISparkVariants(),
+ getRequest(), getMetadataService());
+ }
+
+ /**
+ * Returns the resource's relative path.
+ *
+ * @return The resource's relative path.
+ */
+ protected String getResourcePath() {
+ Reference ref = new Reference(getRequest().getRootRef(), getRequest()
+ .getResourceRef());
+ return ref.getRemainingPart();
+ }
+
+ /**
+ * Returns the application resources base URI.
+ *
+ * @return The application resources base URI.
+ */
+ protected Reference getResourcesBase() {
+ return getRequest().getRootRef();
+ }
+
+ /**
+ * Indicates if the resource should be automatically described via APISpark
+ * when an OPTIONS request is handled.
+ *
+ * @return True if the resource should be automatically described via
+ * APISpark.
+ */
+ public boolean isAutoDescribing() {
+ return this.autoDescribing;
+ }
+
+ @Override
+ public Representation options() {
+ if (isAutoDescribing()) {
+ return describe();
+ }
+
+ return null;
+ }
+
+ /**
+ * Indicates if the resource should be automatically described via APISpark
+ * when an OPTIONS request is handled.
+ *
+ * @param autoDescribed
+ * True if the resource should be automatically described via
+ * APISpark.
+ */
+ public void setAutoDescribing(boolean autoDescribed) {
+ this.autoDescribing = autoDescribed;
+ }
+
+ /**
+ * Sets the description of this documented resource. Is seen as the text
+ * content of the "doc" tag of the "resource" element in a APISpark
+ * document.
+ *
+ * @param description
+ * The description of this documented resource.
+ */
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Sets the name of this documented resource. Is seen as the title of the
+ * "doc" tag of the "resource" element in a APISpark document.
+ *
+ * @param name
+ * The name of this documented resource.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkWrapper.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkWrapper.java
new file mode 100644
index 0000000000..fd1e6d5e32
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApisparkWrapper.java
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import org.restlet.Restlet;
+import org.restlet.resource.Directory;
+import org.restlet.util.WrapperRestlet;
+
+/**
+ * APISpark wrapper for {@link Restlet} instances. Useful if you need to provide
+ * the APISpark documentation for instances of classes such as {@link Directory}
+ * .
+ *
+ * @author Thierry Boileau
+ */
+public abstract class ApisparkWrapper extends WrapperRestlet implements
+ ApisparkDescribable {
+
+ /** The description of the wrapped Restlet. */
+ private ResourceInfo resourceInfo;
+
+ /**
+ * Constructor.
+ *
+ * @param wrappedRestlet
+ * The Restlet to wrap.
+ */
+ public ApisparkWrapper(Restlet wrappedRestlet) {
+ super(wrappedRestlet);
+ }
+
+ /**
+ * Returns the description of the wrapped Restlet.
+ *
+ * @return The ResourceInfo object of the wrapped Restlet.
+ */
+ public ResourceInfo getResourceInfo() {
+ return this.resourceInfo;
+ }
+
+ /**
+ * Sets the description of the wrapped Restlet.
+ *
+ * @param resourceInfo
+ * The ResourceInfo object of the wrapped Restlet.
+ */
+ public void setResourceInfo(ResourceInfo resourceInfo) {
+ this.resourceInfo = resourceInfo;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApplicationInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApplicationInfo.java
new file mode 100644
index 0000000000..878b63e0a9
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ApplicationInfo.java
@@ -0,0 +1,247 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Root of a APISpark description document.
+ *
+ * @author Jerome Louvel
+ */
+public class ApplicationInfo extends DocumentedInfo {
+
+ /** List of methods. */
+ private List<MethodInfo> methods;
+
+ /** Name. */
+ private String name;
+
+ /** List of representations. */
+ private List<RepresentationInfo> representations;
+
+ /** Resources provided by the application. */
+ private ResourcesInfo resources;
+
+ /**
+ * Describes a set of methods that define the behavior of a type of
+ * resource.
+ */
+ private List<ResourceTypeInfo> resourceTypes;
+
+ /** The version of the Application. */
+ private String version;
+
+ /**
+ * Constructor.
+ */
+ public ApplicationInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ApplicationInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public ApplicationInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ApplicationInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Returns the list of method elements.
+ *
+ * @return The list of method elements.
+ */
+ public List<MethodInfo> getMethods() {
+ // Lazy initialization with double-check.
+ List<MethodInfo> m = this.methods;
+ if (m == null) {
+ synchronized (this) {
+ m = this.methods;
+ if (m == null) {
+ this.methods = m = new ArrayList<MethodInfo>();
+ }
+ }
+ }
+ return m;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Returns the list of representation elements.
+ *
+ * @return The list of representation elements.
+ */
+ public List<RepresentationInfo> getRepresentations() {
+ // Lazy initialization with double-check.
+ List<RepresentationInfo> r = this.representations;
+ if (r == null) {
+ synchronized (this) {
+ r = this.representations;
+ if (r == null) {
+ this.representations = r = new ArrayList<RepresentationInfo>();
+ }
+ }
+ }
+ return r;
+ }
+
+ /**
+ * Returns the resources root element.
+ *
+ * @return The resources root element.
+ */
+ public ResourcesInfo getResources() {
+ // Lazy initialization with double-check.
+ ResourcesInfo r = this.resources;
+ if (r == null) {
+ synchronized (this) {
+ r = this.resources;
+ if (r == null) {
+ this.resources = r = new ResourcesInfo();
+ }
+ }
+ }
+ return r;
+ }
+
+ /**
+ * Returns the list of resource type elements.
+ *
+ * @return The list of resource type elements.
+ */
+ public List<ResourceTypeInfo> getResourceTypes() {
+ // Lazy initialization with double-check.
+ List<ResourceTypeInfo> rt = this.resourceTypes;
+ if (rt == null) {
+ synchronized (this) {
+ rt = this.resourceTypes;
+ if (rt == null) {
+ this.resourceTypes = rt = new ArrayList<ResourceTypeInfo>();
+ }
+ }
+ }
+ return rt;
+ }
+
+ /**
+ * Returns the version of the Application.
+ *
+ * @return The version of the Application.
+ */
+ public String getVersion() {
+ return version;
+ }
+
+ /**
+ * Sets the list of documentation elements.
+ *
+ * @param methods
+ * The list of method elements.
+ */
+ public void setMethods(List<MethodInfo> methods) {
+ this.methods = methods;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Sets the list of representation elements.
+ *
+ * @param representations
+ * The list of representation elements.
+ */
+ public void setRepresentations(List<RepresentationInfo> representations) {
+ this.representations = representations;
+ }
+
+ /**
+ * Sets the list of resource elements.
+ *
+ * @param resources
+ * The list of resource elements.
+ */
+ public void setResources(ResourcesInfo resources) {
+ this.resources = resources;
+ }
+
+ /**
+ * Sets the list of resource type elements.
+ *
+ * @param resourceTypes
+ * The list of resource type elements.
+ */
+ public void setResourceTypes(List<ResourceTypeInfo> resourceTypes) {
+ this.resourceTypes = resourceTypes;
+ }
+
+ /**
+ * Sets the version of the Application.
+ *
+ * @param version
+ * The version of the Application.
+ */
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/DocumentationInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/DocumentationInfo.java
new file mode 100644
index 0000000000..0b0ec2aa0b
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/DocumentationInfo.java
@@ -0,0 +1,129 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import org.restlet.data.Language;
+
+/**
+ * Document APISpark description elements.
+ *
+ * @author Jerome Louvel
+ */
+public class DocumentationInfo {
+
+ /** The language of that documentation element. */
+ private Language language;
+
+ /** The content as a String. */
+ private String textContent;
+
+ /** The title of that documentation element. */
+ private String title;
+
+ /**
+ * Constructor.
+ */
+ public DocumentationInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with text content.
+ *
+ * @param textContent
+ * The text content.
+ */
+ public DocumentationInfo(String textContent) {
+ super();
+ setTextContent(textContent);
+ }
+
+ /**
+ * Returns the language of that documentation element.
+ *
+ * @return The language of this documentation element.
+ */
+ public Language getLanguage() {
+ return this.language;
+ }
+
+ /**
+ * Returns the language of that documentation element.
+ *
+ * @return The content of that element as text.
+ */
+ public String getTextContent() {
+ return this.textContent;
+ }
+
+ /**
+ * Returns the title of that documentation element.
+ *
+ * @return The title of that documentation element.
+ */
+ public String getTitle() {
+ return this.title;
+ }
+
+ /**
+ * The language of that documentation element.
+ *
+ * @param language
+ * The language of that documentation element.
+ */
+ public void setLanguage(Language language) {
+ this.language = language;
+ }
+
+ /**
+ * Sets the content of that element as text.
+ *
+ * @param textContent
+ * The content of that element as text.
+ */
+ public void setTextContent(String textContent) {
+ this.textContent = textContent;
+ }
+
+ /**
+ * Sets the title of that documentation element.
+ *
+ * @param title
+ * The title of that documentation element.
+ */
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/DocumentedInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/DocumentedInfo.java
new file mode 100644
index 0000000000..1663f701fd
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/DocumentedInfo.java
@@ -0,0 +1,136 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Superclass of APISpark elements that supports dcumentation.
+ *
+ */
+public abstract class DocumentedInfo {
+ /** Doc elements used to document that element. */
+ private List<DocumentationInfo> documentations;
+
+ /**
+ * Constructor.
+ */
+ public DocumentedInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public DocumentedInfo(DocumentationInfo documentation) {
+ super();
+ getDocumentations().add(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public DocumentedInfo(List<DocumentationInfo> documentations) {
+ super();
+ this.documentations = documentations;
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public DocumentedInfo(String documentation) {
+ this(new DocumentationInfo(documentation));
+ }
+
+ /**
+ * Returns the list of documentation elements.
+ *
+ * @return The list of documentation elements.
+ */
+ public List<DocumentationInfo> getDocumentations() {
+ // Lazy initialization with double-check.
+ List<DocumentationInfo> d = this.documentations;
+ if (d == null) {
+ synchronized (this) {
+ d = this.documentations;
+ if (d == null) {
+ this.documentations = d = new ArrayList<DocumentationInfo>();
+ }
+ }
+ }
+ return d;
+ }
+
+ /**
+ * Set the list of documentation elements with a single element.
+ *
+ * @param documentationInfo
+ * A single documentation element.
+ */
+ public void setDocumentation(DocumentationInfo documentationInfo) {
+ getDocumentations().clear();
+ getDocumentations().add(documentationInfo);
+ }
+
+ /**
+ * Set the list of documentation elements with a single element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public void setDocumentation(String documentation) {
+ getDocumentations().clear();
+ getDocumentations().add(new DocumentationInfo(documentation));
+ }
+
+ /**
+ * Sets the list of documentation elements.
+ *
+ * @param doc
+ * The list of documentation elements.
+ */
+ public void setDocumentations(List<DocumentationInfo> doc) {
+ this.documentations = doc;
+ }
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/LinkInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/LinkInfo.java
new file mode 100644
index 0000000000..d38a1960c0
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/LinkInfo.java
@@ -0,0 +1,157 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.List;
+
+import org.restlet.data.Reference;
+
+/**
+ * Allows description of links between representations and resources.
+ *
+ * @author Jerome Louvel
+ */
+public class LinkInfo extends DocumentedInfo {
+ /**
+ * Identifies the relationship of the resource identified by the link to the
+ * resource whose representation the link is embedded in.
+ */
+ private String relationship;
+
+ /**
+ * Defines the capabilities of the resource that the link identifies.
+ */
+ private Reference resourceType;
+
+ /**
+ * Identifies the relationship of the resource whose representation the link
+ * is embedded in to the resource identified by the link.
+ */
+ private String reverseRelationship;
+
+ /**
+ * Constructor.
+ */
+ public LinkInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public LinkInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public LinkInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public LinkInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Returns the relationship attribute value.
+ *
+ * @return The relationship attribute value.
+ */
+ public String getRelationship() {
+ return this.relationship;
+ }
+
+ /**
+ * Returns the reference to the resource type of the linked resource.
+ *
+ * @return The reference to the resource type of the linked resource.
+ */
+ public Reference getResourceType() {
+ return this.resourceType;
+ }
+
+ /**
+ * Returns the reverse relationship attribute value.
+ *
+ * @return The reverse relationship attribute value.
+ */
+ public String getReverseRelationship() {
+ return this.reverseRelationship;
+ }
+
+ /**
+ * Sets the relationship attribute value.
+ *
+ * @param relationship
+ * The relationship attribute value.
+ */
+ public void setRelationship(String relationship) {
+ this.relationship = relationship;
+ }
+
+ /**
+ * Sets the reference to the resource type of the linked resource.
+ *
+ * @param resourceType
+ * The reference to the resource type of the linked resource.
+ */
+ public void setResourceType(Reference resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ /**
+ * Sets the reverse relationship attribute value.
+ *
+ * @param reverseRelationship
+ * The reverse relationship attribute value.
+ */
+ public void setReverseRelationship(String reverseRelationship) {
+ this.reverseRelationship = reverseRelationship;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/MethodInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/MethodInfo.java
new file mode 100644
index 0000000000..efaed5a253
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/MethodInfo.java
@@ -0,0 +1,328 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.restlet.data.Method;
+import org.restlet.data.Reference;
+import org.restlet.engine.resource.AnnotationInfo;
+import org.restlet.engine.resource.AnnotationUtils;
+import org.restlet.representation.Variant;
+import org.restlet.resource.ResourceException;
+import org.restlet.resource.ServerResource;
+import org.restlet.service.MetadataService;
+
+/**
+ * Describes the expected requests and responses of a resource method.
+ *
+ * @author Jerome Louvel
+ */
+public class MethodInfo extends DocumentedInfo {
+
+ /**
+ * Automatically describe a method by discovering the resource's
+ * annotations.
+ *
+ * @param info
+ * The method description to update.
+ * @param resource
+ * The server resource to describe.
+ */
+ public static void describeAnnotations(MethodInfo info,
+ ServerResource resource) {
+ // Loop over the annotated Java methods
+ MetadataService metadataService = resource.getMetadataService();
+ List<AnnotationInfo> annotations = resource.isAnnotated() ? AnnotationUtils
+ .getInstance().getAnnotations(resource.getClass()) : null;
+
+ if (annotations != null && metadataService != null) {
+ for (AnnotationInfo annotationInfo : annotations) {
+ try {
+ if (info.getName()
+ .equals(annotationInfo.getRestletMethod())) {
+ // Describe the request
+ Class<?>[] classes = annotationInfo.getJavaInputTypes();
+
+ List<Variant> requestVariants = annotationInfo
+ .getRequestVariants(
+ resource.getMetadataService(),
+ resource.getConverterService());
+
+ if (requestVariants != null) {
+ for (Variant variant : requestVariants) {
+ if ((variant.getMediaType() != null)
+ && ((info.getRequest() == null) || !info
+ .getRequest()
+ .getRepresentations()
+ .contains(variant))) {
+ RepresentationInfo representationInfo = null;
+
+ if (info.getRequest() == null) {
+ info.setRequest(new RequestInfo());
+ }
+
+ if (resource instanceof ApisparkServerResource) {
+ representationInfo = ((ApisparkServerResource) resource)
+ .describe(info,
+ info.getRequest(),
+ classes[0], variant);
+ } else {
+ representationInfo = new RepresentationInfo(
+ variant);
+ }
+
+ info.getRequest().getRepresentations()
+ .add(representationInfo);
+ }
+ }
+ }
+
+ // Describe the response
+ Class<?> outputClass = annotationInfo
+ .getJavaOutputType();
+
+ if (outputClass != null) {
+ List<Variant> responseVariants = annotationInfo
+ .getResponseVariants(
+ resource.getMetadataService(),
+ resource.getConverterService());
+
+ if (responseVariants != null) {
+ for (Variant variant : responseVariants) {
+ if ((variant.getMediaType() != null)
+ && !info.getResponse()
+ .getRepresentations()
+ .contains(variant)) {
+ RepresentationInfo representationInfo = null;
+
+ if (resource instanceof ApisparkServerResource) {
+ representationInfo = ((ApisparkServerResource) resource)
+ .describe(info,
+ info.getResponse(),
+ outputClass,
+ variant);
+ } else {
+ representationInfo = new RepresentationInfo(
+ variant);
+ }
+
+ info.getResponse().getRepresentations()
+ .add(representationInfo);
+ }
+ }
+ }
+ }
+ }
+ } catch (IOException e) {
+ throw new ResourceException(e);
+ }
+ }
+ }
+ }
+
+ /** Identifier for the method. */
+ private String identifier;
+
+ /** Name of the method. */
+ private Method name;
+
+ /** Describes the input to the method. */
+ private RequestInfo request;
+
+ /** Describes the output of the method. */
+ private List<ResponseInfo> responses;
+
+ /** Reference to a method definition element. */
+ private Reference targetRef;
+
+ /**
+ * Constructor.
+ */
+ public MethodInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public MethodInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public MethodInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public MethodInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Returns the identifier for the method.
+ *
+ * @return The identifier for the method.
+ */
+ public String getIdentifier() {
+ return this.identifier;
+ }
+
+ /**
+ * Returns the name of the method.
+ *
+ * @return The name of the method.
+ */
+
+ public Method getName() {
+ return this.name;
+ }
+
+ /**
+ * Returns the input to the method.
+ *
+ * @return The input to the method.
+ */
+ public RequestInfo getRequest() {
+ return this.request;
+ }
+
+ /**
+ * Returns the last added response of the method.
+ *
+ * @return The last added response of the method.
+ */
+ public ResponseInfo getResponse() {
+ if (getResponses().isEmpty()) {
+ getResponses().add(new ResponseInfo());
+ }
+
+ return getResponses().get(getResponses().size() - 1);
+ }
+
+ /**
+ * Returns the output of the method.
+ *
+ * @return The output of the method.
+ */
+ public List<ResponseInfo> getResponses() {
+ // Lazy initialization with double-check.
+ List<ResponseInfo> r = this.responses;
+ if (r == null) {
+ synchronized (this) {
+ r = this.responses;
+ if (r == null) {
+ this.responses = r = new ArrayList<ResponseInfo>();
+ }
+ }
+ }
+ return r;
+ }
+
+ /**
+ * Returns the reference to a method definition element.
+ *
+ * @return The reference to a method definition element.
+ */
+ public Reference getTargetRef() {
+ return this.targetRef;
+ }
+
+ /**
+ * Sets the identifier for the method.
+ *
+ * @param identifier
+ * The identifier for the method.
+ */
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ /**
+ * Sets the name of the method.
+ *
+ * @param name
+ * The name of the method.
+ */
+ public void setName(Method name) {
+ this.name = name;
+ }
+
+ /**
+ * Sets the input to the method.
+ *
+ * @param request
+ * The input to the method.
+ */
+ public void setRequest(RequestInfo request) {
+ this.request = request;
+ }
+
+ /**
+ * Sets the output of the method.
+ *
+ * @param responses
+ * The output of the method.
+ */
+ public void setResponses(List<ResponseInfo> responses) {
+ this.responses = responses;
+ }
+
+ /**
+ * Sets the reference to a method definition element.
+ *
+ * @param targetRef
+ * The reference to a method definition element.
+ */
+ public void setTargetRef(Reference targetRef) {
+ this.targetRef = targetRef;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/OptionInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/OptionInfo.java
new file mode 100644
index 0000000000..8d5aa0d309
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/OptionInfo.java
@@ -0,0 +1,104 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.List;
+
+/**
+ * Defines a potential value for a parent parameter description.
+ *
+ * @author Jerome Louvel
+ */
+public class OptionInfo extends DocumentedInfo {
+
+ /** Value of this option element. */
+ private String value;
+
+ /**
+ * Constructor.
+ */
+ public OptionInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public OptionInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public OptionInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public OptionInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Returns the value of this option element.
+ *
+ * @return The value of this option element.
+ */
+ public String getValue() {
+ return this.value;
+ }
+
+ /**
+ * Sets the value of this option element.
+ *
+ * @param value
+ * The value of this option element.
+ */
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ParameterInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ParameterInfo.java
new file mode 100644
index 0000000000..c9137da42c
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ParameterInfo.java
@@ -0,0 +1,402 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Describes a parameterized aspect of a parent {@link ResourceInfo},
+ * {@link RequestInfo}, {@link ResponseInfo} or {@link RepresentationInfo}
+ * element.
+ *
+ * @author Jerome Louvel
+ */
+public class ParameterInfo extends DocumentedInfo {
+
+ /** Default value of this parameter. */
+ private String defaultValue;
+
+ /** Provides a fixed value for the parameter. */
+ private String fixed;
+
+ /** Identifier of this parameter element. */
+ private String identifier;
+
+ /** Link element. */
+ private LinkInfo link;
+
+ /** Name of this element. */
+ private String name;
+
+ /** List of option elements for that element. */
+ private List<OptionInfo> options;
+
+ /**
+ * Path to the value of this parameter (within a parent representation).
+ */
+ private String path;
+
+ /**
+ * Indicates whether the parameter is single valued or may have multiple
+ * values.
+ */
+ private boolean repeating;
+
+ /**
+ * Indicates whether the parameter is required.
+ */
+ private boolean required;
+
+ /** Parameter style. */
+ private ParameterStyle style;
+
+ /** Parameter type. */
+ private String type;
+
+ /**
+ * Constructor.
+ */
+ public ParameterInfo() {
+ super();
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param name
+ * The name of the parameter.
+ * @param required
+ * True if thes parameter is required.
+ * @param type
+ * The type of the parameter.
+ * @param style
+ * The style of the parameter.
+ * @param documentation
+ * A single documentation element.
+ */
+ public ParameterInfo(String name, boolean required, String type,
+ ParameterStyle style, String documentation) {
+ super(documentation);
+ this.name = name;
+ this.required = required;
+ this.style = style;
+ this.type = type;
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param name
+ * The required name of the parameter.
+ * @param style
+ * The required style of the parameter.
+ * @param documentation
+ * A single documentation element.
+ */
+ public ParameterInfo(String name, ParameterStyle style,
+ DocumentationInfo documentation) {
+ super(documentation);
+ this.name = name;
+ this.style = style;
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param name
+ * The required name of the parameter.
+ * @param style
+ * The required style of the parameter.
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public ParameterInfo(String name, ParameterStyle style,
+ List<DocumentationInfo> documentations) {
+ super(documentations);
+ this.name = name;
+ this.style = style;
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param name
+ * The required name of the parameter.
+ * @param style
+ * The required style of the parameter.
+ * @param documentation
+ * A single documentation element.
+ */
+ public ParameterInfo(String name, ParameterStyle style, String documentation) {
+ super(documentation);
+ this.name = name;
+ this.style = style;
+ }
+
+ /**
+ * Returns the default value of this parameter.
+ *
+ * @return The default value of this parameter.
+ */
+ public String getDefaultValue() {
+ return this.defaultValue;
+ }
+
+ /**
+ * Returns the fixed value for the parameter.
+ *
+ * @return The fixed value for the parameter.
+ */
+ public String getFixed() {
+ return this.fixed;
+ }
+
+ /**
+ * Returns the identifier of this parameter element.
+ *
+ * @return The identifier of this parameter element.
+ */
+
+ public String getIdentifier() {
+ return this.identifier;
+ }
+
+ /**
+ * Returns the link element.
+ *
+ * @return The link element.
+ */
+
+ public LinkInfo getLink() {
+ return this.link;
+ }
+
+ /**
+ * Returns the name of this element.
+ *
+ * @return The name of this element.
+ */
+
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * Returns the list of option elements for that element.
+ *
+ * @return The list of option elements for that element.
+ */
+
+ public List<OptionInfo> getOptions() {
+ // Lazy initialization with double-check.
+ List<OptionInfo> o = this.options;
+ if (o == null) {
+ synchronized (this) {
+ o = this.options;
+ if (o == null) {
+ this.options = o = new ArrayList<OptionInfo>();
+ }
+ }
+ }
+ return o;
+ }
+
+ /**
+ * Returns the path to the value of this parameter (within a parent
+ * representation).
+ *
+ * @return The path to the value of this parameter (within a parent
+ * representation).
+ */
+
+ public String getPath() {
+ return this.path;
+ }
+
+ /**
+ * Returns the parameter style.
+ *
+ * @return The parameter style.
+ */
+
+ public ParameterStyle getStyle() {
+ return this.style;
+ }
+
+ /**
+ * Returns the parameter type.
+ *
+ * @return The parameter type.
+ */
+ public String getType() {
+ return this.type;
+ }
+
+ /**
+ * Returns true if the parameter is single valued or may have multiple
+ * values, false otherwise.
+ *
+ * @return True if the parameter is single valued or may have multiple
+ * values, false otherwise.
+ */
+
+ public boolean isRepeating() {
+ return this.repeating;
+ }
+
+ /**
+ * Indicates whether the parameter is required.
+ *
+ * @return True if the parameter is required, false otherwise.
+ */
+ public boolean isRequired() {
+ return this.required;
+ }
+
+ /**
+ * Sets the default value of this parameter.
+ *
+ * @param defaultValue
+ * The default value of this parameter.
+ */
+ public void setDefaultValue(String defaultValue) {
+ this.defaultValue = defaultValue;
+ }
+
+ /**
+ * Sets the fixed value for the parameter.
+ *
+ * @param fixed
+ * The fixed value for the parameter.
+ */
+ public void setFixed(String fixed) {
+ this.fixed = fixed;
+ }
+
+ /**
+ * Sets the identifier of this parameter element.
+ *
+ * @param identifier
+ * The identifier of this parameter element.
+ */
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ /**
+ * Sets the link element.
+ *
+ * @param link
+ * The link element.
+ */
+ public void setLink(LinkInfo link) {
+ this.link = link;
+ }
+
+ /**
+ * Sets the name of this element.
+ *
+ * @param name
+ * The name of this element.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Sets the list of option elements for that element.
+ *
+ * @param options
+ * The list of option elements for that element.
+ */
+ public void setOptions(List<OptionInfo> options) {
+ this.options = options;
+ }
+
+ /**
+ * Sets the path to the value of this parameter (within a parent
+ * representation).
+ *
+ * @param path
+ * The path to the value of this parameter (within a parent
+ * representation).
+ */
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ /**
+ * Indicates whether the parameter is single valued or may have multiple
+ * values.
+ *
+ * @param repeating
+ * True if the parameter is single valued or may have multiple
+ * values, false otherwise.
+ */
+ public void setRepeating(boolean repeating) {
+ this.repeating = repeating;
+ }
+
+ /**
+ * Indicates whether the parameter is required.
+ *
+ * @param required
+ * True if the parameter is required, false otherwise.
+ */
+ public void setRequired(boolean required) {
+ this.required = required;
+ }
+
+ /**
+ * Sets the parameter style.
+ *
+ * @param style
+ * The parameter style.
+ */
+ public void setStyle(ParameterStyle style) {
+ this.style = style;
+ }
+
+ /**
+ * Sets the parameter type.
+ *
+ * @param type
+ * The parameter type.
+ */
+ public void setType(String type) {
+ this.type = type;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ParameterStyle.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ParameterStyle.java
new file mode 100644
index 0000000000..6ee694a94b
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ParameterStyle.java
@@ -0,0 +1,63 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+/**
+ * Enumerates the supported styles of parameters.
+ *
+ * @author Jerome Louvel
+ */
+public enum ParameterStyle {
+
+ HEADER, MATRIX, PLAIN, QUERY, TEMPLATE;
+
+ @Override
+ public String toString() {
+ String result = null;
+ if (equals(HEADER)) {
+ result = "header";
+ } else if (equals(MATRIX)) {
+ result = "matrix";
+ } else if (equals(PLAIN)) {
+ result = "plain";
+ } else if (equals(QUERY)) {
+ result = "query";
+ } else if (equals(TEMPLATE)) {
+ result = "template";
+ }
+
+ return result;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/RepresentationInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/RepresentationInfo.java
new file mode 100644
index 0000000000..4d85e285ea
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/RepresentationInfo.java
@@ -0,0 +1,237 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.restlet.data.MediaType;
+import org.restlet.data.Reference;
+import org.restlet.representation.Variant;
+
+/**
+ * Describes a variant representation for a target resource.
+ *
+ * @author Jerome Louvel
+ */
+public class RepresentationInfo extends DocumentedInfo {
+
+ /** Identifier for that element. */
+ private String identifier;
+
+ /** Media type of that element. */
+ private MediaType mediaType;
+
+ /** List of parameters. */
+ private List<ParameterInfo> parameters;
+
+ /** List of locations of one or more meta data profiles. */
+ private List<Reference> profiles;
+
+ /** Reference to an representation identifier. */
+ private String reference;
+
+ /**
+ * Constructor.
+ */
+ public RepresentationInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public RepresentationInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public RepresentationInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a media type.
+ *
+ * @param mediaType
+ * The media type of the representation.
+ */
+ public RepresentationInfo(MediaType mediaType) {
+ setMediaType(mediaType);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public RepresentationInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a variant.
+ *
+ * @param variant
+ * The variant to describe.
+ */
+ public RepresentationInfo(Variant variant) {
+ setMediaType(variant.getMediaType());
+ }
+
+ /**
+ * Returns the identifier for that element.
+ *
+ * @return The identifier for that element.
+ */
+ public String getIdentifier() {
+ return this.identifier;
+ }
+
+ /**
+ * Returns the media type of that element.
+ *
+ * @return The media type of that element.
+ */
+ public MediaType getMediaType() {
+ return this.mediaType;
+ }
+
+ /**
+ * Returns the list of parameters.
+ *
+ * @return The list of parameters.
+ */
+ public List<ParameterInfo> getParameters() {
+ // Lazy initialization with double-check.
+ List<ParameterInfo> p = this.parameters;
+ if (p == null) {
+ synchronized (this) {
+ p = this.parameters;
+ if (p == null) {
+ this.parameters = p = new ArrayList<ParameterInfo>();
+ }
+ }
+ }
+ return p;
+ }
+
+ /**
+ * Returns the list of locations of one or more meta data profiles.
+ *
+ * @return The list of locations of one or more meta data profiles.
+ */
+ public List<Reference> getProfiles() {
+ // Lazy initialization with double-check.
+ List<Reference> p = this.profiles;
+ if (p == null) {
+ synchronized (this) {
+ p = this.profiles;
+ if (p == null) {
+ this.profiles = p = new ArrayList<Reference>();
+ }
+ }
+ }
+ return p;
+ }
+
+ /**
+ * Returns the reference to an representation identifier.
+ *
+ * @return The reference to an representation identifier.
+ */
+ public String getReference() {
+ return reference;
+ }
+
+ /**
+ * Sets the identifier for that element.
+ *
+ * @param identifier
+ * The identifier for that element.
+ */
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ /**
+ * Sets the media type of that element.
+ *
+ * @param mediaType
+ * The media type of that element.
+ */
+ public void setMediaType(MediaType mediaType) {
+ this.mediaType = mediaType;
+ }
+
+ /**
+ * Sets the list of parameters.
+ *
+ * @param parameters
+ * The list of parameters.
+ */
+ public void setParameters(List<ParameterInfo> parameters) {
+ this.parameters = parameters;
+ }
+
+ /**
+ * Sets the list of locations of one or more meta data profiles.
+ *
+ * @param profiles
+ * The list of locations of one or more meta data profiles.
+ */
+ public void setProfiles(List<Reference> profiles) {
+ this.profiles = profiles;
+ }
+
+ /**
+ * Sets the reference to an representation identifier.
+ *
+ * @param reference
+ * The reference to an representation identifier.
+ */
+ public void setReference(String reference) {
+ this.reference = reference;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/RequestInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/RequestInfo.java
new file mode 100644
index 0000000000..80070d771d
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/RequestInfo.java
@@ -0,0 +1,147 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Describes the properties of a request associated to a parent method.
+ *
+ * @author Jerome Louvel
+ */
+public class RequestInfo extends DocumentedInfo {
+
+ /** List of parameters. */
+ private List<ParameterInfo> parameters;
+
+ /** List of supported input representations. */
+ private List<RepresentationInfo> representations;
+
+ /**
+ * Constructor.
+ */
+ public RequestInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public RequestInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public RequestInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public RequestInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Returns the list of parameters.
+ *
+ * @return The list of parameters.
+ */
+ public List<ParameterInfo> getParameters() {
+ // Lazy initialization with double-check.
+ List<ParameterInfo> p = this.parameters;
+ if (p == null) {
+ synchronized (this) {
+ p = this.parameters;
+ if (p == null) {
+ this.parameters = p = new ArrayList<ParameterInfo>();
+ }
+ }
+ }
+ return p;
+ }
+
+ /**
+ * Returns the list of supported input representations.
+ *
+ * @return The list of supported input representations.
+ */
+ public List<RepresentationInfo> getRepresentations() {
+ // Lazy initialization with double-check.
+ List<RepresentationInfo> r = this.representations;
+ if (r == null) {
+ synchronized (this) {
+ r = this.representations;
+ if (r == null) {
+ this.representations = r = new ArrayList<RepresentationInfo>();
+ }
+ }
+ }
+ return r;
+ }
+
+ /**
+ * Sets the list of parameters.
+ *
+ * @param parameters
+ * The list of parameters.
+ */
+ public void setParameters(List<ParameterInfo> parameters) {
+ this.parameters = parameters;
+ }
+
+ /**
+ * Sets the list of supported input representations.
+ *
+ * @param representations
+ * The list of supported input representations.
+ */
+ public void setRepresentations(List<RepresentationInfo> representations) {
+ this.representations = representations;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourceInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourceInfo.java
new file mode 100644
index 0000000000..92bb520674
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourceInfo.java
@@ -0,0 +1,412 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.restlet.data.MediaType;
+import org.restlet.data.Method;
+import org.restlet.data.Reference;
+import org.restlet.resource.Directory;
+import org.restlet.resource.ServerResource;
+
+/**
+ * Describes a class of closely related resources.
+ *
+ * @author Jerome Louvel
+ */
+public class ResourceInfo extends DocumentedInfo {
+
+ /**
+ * Returns a APISpark description of the current resource.
+ *
+ * @param applicationInfo
+ * The parent application.
+ * @param resource
+ * The resource to describe.
+ * @param path
+ * Path of the current resource.
+ * @param info
+ * APISpark description of the current resource to update.
+ */
+ public static void describe(ApplicationInfo applicationInfo,
+ ResourceInfo info, Object resource, String path) {
+ if ((path != null) && path.startsWith("/")) {
+ path = path.substring(1);
+ }
+
+ info.setPath(path);
+
+ // Introspect the current resource to detect the allowed methods
+ List<Method> methodsList = new ArrayList<Method>();
+
+ if (resource instanceof ServerResource) {
+ ((ServerResource) resource).updateAllowedMethods();
+ methodsList.addAll(((ServerResource) resource).getAllowedMethods());
+
+ if (resource instanceof ApisparkServerResource) {
+ info.setParameters(((ApisparkServerResource) resource)
+ .describeParameters());
+
+ if (applicationInfo != null) {
+ ((ApisparkServerResource) resource)
+ .describe(applicationInfo);
+ }
+ }
+ } else if (resource instanceof Directory) {
+ Directory directory = (Directory) resource;
+ methodsList.add(Method.GET);
+
+ if (directory.isModifiable()) {
+ methodsList.add(Method.DELETE);
+ methodsList.add(Method.PUT);
+ }
+ }
+
+ Method.sort(methodsList);
+
+ // Update the resource info with the description of the allowed methods
+ List<MethodInfo> methods = info.getMethods();
+ MethodInfo methodInfo;
+
+ for (Method method : methodsList) {
+ methodInfo = new MethodInfo();
+ methods.add(methodInfo);
+ methodInfo.setName(method);
+
+ if (resource instanceof ServerResource) {
+ if (resource instanceof ApisparkServerResource) {
+ ApisparkServerResource wsResource = (ApisparkServerResource) resource;
+
+ if (wsResource.canDescribe(method)) {
+ wsResource.describeMethod(method, methodInfo);
+ }
+ } else {
+ MethodInfo.describeAnnotations(methodInfo,
+ (ServerResource) resource);
+ }
+ }
+ }
+
+ // Document the resource
+ String title = null;
+ String textContent = null;
+
+ if (resource instanceof ApisparkServerResource) {
+ title = ((ApisparkServerResource) resource).getName();
+ textContent = ((ApisparkServerResource) resource).getDescription();
+ }
+
+ if ((title != null) && !"".equals(title)) {
+ DocumentationInfo doc = null;
+
+ if (info.getDocumentations().isEmpty()) {
+ doc = new DocumentationInfo();
+ info.getDocumentations().add(doc);
+ } else {
+ info.getDocumentations().get(0);
+ }
+
+ doc.setTitle(title);
+ doc.setTextContent(textContent);
+ }
+ }
+
+ /** List of child resources. */
+ private List<ResourceInfo> childResources;
+
+ /** Identifier for that element. */
+ private String identifier;
+
+ /** List of supported methods. */
+ private List<MethodInfo> methods;
+
+ /** List of parameters. */
+ private List<ParameterInfo> parameters;
+
+ /** URI template for the identifier of the resource. */
+ private String path;
+
+ /** Media type for the query component of the resource URI. */
+ private MediaType queryType;
+
+ /** List of references to resource type elements. */
+ private List<Reference> type;
+
+ /**
+ * Constructor.
+ */
+ public ResourceInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ResourceInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public ResourceInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ResourceInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Creates an application descriptor that wraps this resource descriptor.
+ * The title of the resource, that is to say the title of its first
+ * documentation tag is transfered to the title of the first documentation
+ * tag of the main application tag.
+ *
+ * @return The new application descriptor.
+ */
+ public ApplicationInfo createApplication() {
+ ApplicationInfo result = new ApplicationInfo();
+
+ if (!getDocumentations().isEmpty()) {
+ String titleResource = getDocumentations().get(0).getTitle();
+ if (titleResource != null && !"".equals(titleResource)) {
+ DocumentationInfo doc = null;
+
+ if (result.getDocumentations().isEmpty()) {
+ doc = new DocumentationInfo();
+ result.getDocumentations().add(doc);
+ } else {
+ doc = result.getDocumentations().get(0);
+ }
+
+ doc.setTitle(titleResource);
+ }
+ }
+
+ ResourcesInfo resources = new ResourcesInfo();
+ result.setResources(resources);
+ resources.getResources().add(this);
+ return result;
+ }
+
+ /**
+ * Returns the list of child resources.
+ *
+ * @return The list of child resources.
+ */
+ public List<ResourceInfo> getChildResources() {
+ // Lazy initialization with double-check.
+ List<ResourceInfo> r = this.childResources;
+ if (r == null) {
+ synchronized (this) {
+ r = this.childResources;
+ if (r == null) {
+ this.childResources = r = new ArrayList<ResourceInfo>();
+ }
+ }
+ }
+ return r;
+ }
+
+ /**
+ * Returns the identifier for that element.
+ *
+ * @return The identifier for that element.
+ */
+ public String getIdentifier() {
+ return this.identifier;
+ }
+
+ /**
+ * Returns the list of supported methods.
+ *
+ * @return The list of supported methods.
+ */
+ public List<MethodInfo> getMethods() {
+ // Lazy initialization with double-check.
+ List<MethodInfo> m = this.methods;
+ if (m == null) {
+ synchronized (this) {
+ m = this.methods;
+
+ if (m == null) {
+ this.methods = m = new ArrayList<MethodInfo>();
+ }
+ }
+ }
+ return m;
+ }
+
+ /**
+ * Returns the list of parameters.
+ *
+ * @return The list of parameters.
+ */
+ public List<ParameterInfo> getParameters() {
+ // Lazy initialization with double-check.
+ List<ParameterInfo> p = this.parameters;
+ if (p == null) {
+ synchronized (this) {
+ p = this.parameters;
+ if (p == null) {
+ this.parameters = p = new ArrayList<ParameterInfo>();
+ }
+ }
+ }
+ return p;
+ }
+
+ /**
+ * Returns the URI template for the identifier of the resource.
+ *
+ * @return The URI template for the identifier of the resource.
+ */
+ public String getPath() {
+ return this.path;
+ }
+
+ /**
+ * Returns the media type for the query component of the resource URI.
+ *
+ * @return The media type for the query component of the resource URI.
+ */
+ public MediaType getQueryType() {
+ return this.queryType;
+ }
+
+ /**
+ * Returns the list of references to resource type elements.
+ *
+ * @return The list of references to resource type elements.
+ */
+ public List<Reference> getType() {
+ // Lazy initialization with double-check.
+ List<Reference> t = this.type;
+ if (t == null) {
+ synchronized (this) {
+ t = this.type;
+ if (t == null) {
+ this.type = t = new ArrayList<Reference>();
+ }
+ }
+ }
+ return t;
+ }
+
+ /**
+ * Sets the list of child resources.
+ *
+ * @param resources
+ * The list of child resources.
+ */
+ public void setChildResources(List<ResourceInfo> resources) {
+ this.childResources = resources;
+ }
+
+ /**
+ * Sets the identifier for that element.
+ *
+ * @param identifier
+ * The identifier for that element.
+ */
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ /**
+ * Sets the list of supported methods.
+ *
+ * @param methods
+ * The list of supported methods.
+ */
+ public void setMethods(List<MethodInfo> methods) {
+ this.methods = methods;
+ }
+
+ /**
+ * Sets the list of parameters.
+ *
+ * @param parameters
+ * The list of parameters.
+ */
+ public void setParameters(List<ParameterInfo> parameters) {
+ this.parameters = parameters;
+ }
+
+ /**
+ * Sets the URI template for the identifier of the resource.
+ *
+ * @param path
+ * The URI template for the identifier of the resource.
+ */
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ /**
+ * Sets the media type for the query component of the resource URI.
+ *
+ * @param queryType
+ * The media type for the query component of the resource URI.
+ */
+ public void setQueryType(MediaType queryType) {
+ this.queryType = queryType;
+ }
+
+ /**
+ * Sets the list of references to resource type elements.
+ *
+ * @param type
+ * The list of references to resource type elements.
+ */
+ public void setType(List<Reference> type) {
+ this.type = type;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourceTypeInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourceTypeInfo.java
new file mode 100644
index 0000000000..38c7113203
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourceTypeInfo.java
@@ -0,0 +1,169 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Describes a reusable type of resources.
+ *
+ * @author Jerome Louvel
+ */
+public class ResourceTypeInfo extends DocumentedInfo {
+
+ /** Identifier for that element. */
+ private String identifier;
+
+ /** List of supported methods. */
+ private List<MethodInfo> methods;
+
+ /** List of parameters. */
+ private List<ParameterInfo> parameters;
+
+ /**
+ * Constructor.
+ */
+ public ResourceTypeInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ResourceTypeInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public ResourceTypeInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ResourceTypeInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Returns the identifier for that element.
+ *
+ * @return The identifier for that element.
+ */
+ public String getIdentifier() {
+ return this.identifier;
+ }
+
+ /**
+ * Returns the list of supported methods.
+ *
+ * @return The list of supported methods.
+ */
+ public List<MethodInfo> getMethods() {
+ // Lazy initialization with double-check.
+ List<MethodInfo> m = this.methods;
+ if (m == null) {
+ synchronized (this) {
+ m = this.methods;
+ if (m == null) {
+ this.methods = m = new ArrayList<MethodInfo>();
+ }
+ }
+ }
+ return m;
+ }
+
+ /**
+ * Returns the list of parameters.
+ *
+ * @return The list of parameters.
+ */
+ public List<ParameterInfo> getParameters() {
+ // Lazy initialization with double-check.
+ List<ParameterInfo> p = this.parameters;
+ if (p == null) {
+ synchronized (this) {
+ p = this.parameters;
+ if (p == null) {
+ this.parameters = p = new ArrayList<ParameterInfo>();
+ }
+ }
+ }
+ return p;
+ }
+
+ /**
+ * Sets the identifier for that element.
+ *
+ * @param identifier
+ * The identifier for that element.
+ */
+ public void setIdentifier(String identifier) {
+ this.identifier = identifier;
+ }
+
+ /**
+ * Sets the list of supported methods.
+ *
+ * @param methods
+ * The list of supported methods.
+ */
+ public void setMethods(List<MethodInfo> methods) {
+ this.methods = methods;
+ }
+
+ /**
+ * Sets the list of parameters.
+ *
+ * @param parameters
+ * The list of parameters.
+ */
+ public void setParameters(List<ParameterInfo> parameters) {
+ this.parameters = parameters;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourcesInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourcesInfo.java
new file mode 100644
index 0000000000..0274dcd5e7
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResourcesInfo.java
@@ -0,0 +1,138 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.restlet.data.Reference;
+
+/**
+ * Describes the root resources of an application.
+ *
+ * @author Jerome Louvel
+ */
+public class ResourcesInfo extends DocumentedInfo {
+ /** Base URI for each child resource identifier. */
+ private Reference baseRef;
+
+ /** List of child resources. */
+ private List<ResourceInfo> resources;
+
+ /**
+ * Constructor.
+ */
+ public ResourcesInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ResourcesInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public ResourcesInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ResourcesInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Returns the base URI for each child resource identifier.
+ *
+ * @return The base URI for each child resource identifier.
+ */
+ public Reference getBaseRef() {
+ return this.baseRef;
+ }
+
+ /**
+ * Returns the list of child resources.
+ *
+ * @return The list of child resources.
+ */
+ public List<ResourceInfo> getResources() {
+ // Lazy initialization with double-check.
+ List<ResourceInfo> r = this.resources;
+ if (r == null) {
+ synchronized (this) {
+ r = this.resources;
+ if (r == null) {
+ this.resources = r = new ArrayList<ResourceInfo>();
+ }
+ }
+ }
+ return r;
+ }
+
+ /**
+ * Sets the base URI for each child resource identifier.
+ *
+ * @param baseRef
+ * The base URI for each child resource identifier.
+ */
+ public void setBaseRef(Reference baseRef) {
+ this.baseRef = baseRef;
+ }
+
+ /**
+ * Sets the list of child resources.
+ *
+ * @param resources
+ * The list of child resources.
+ */
+ public void setResources(List<ResourceInfo> resources) {
+ this.resources = resources;
+ }
+
+}
diff --git a/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResponseInfo.java b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResponseInfo.java
new file mode 100644
index 0000000000..0a653d33af
--- /dev/null
+++ b/modules/org.restlet.ext.apispark/src/org/restlet/ext/apispark/info/ResponseInfo.java
@@ -0,0 +1,186 @@
+/**
+ * Copyright 2005-2014 Restlet
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: Apache 2.0 or 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 Apache 2.0 license at
+ * http://www.opensource.org/licenses/apache-2.0
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0
+ *
+ * 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://restlet.com/products/restlet-framework
+ *
+ * Restlet is a registered trademark of Restlet S.A.S.
+ */
+
+package org.restlet.ext.apispark.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.restlet.data.Status;
+
+/**
+ * Describes the properties of a response associated to a parent method.
+ *
+ * @author Jerome Louvel
+ */
+public class ResponseInfo extends DocumentedInfo {
+
+ /** List of parameters. */
+ private List<ParameterInfo> parameters;
+
+ /** List of representations. */
+ private List<RepresentationInfo> representations;
+
+ /**
+ * List of statuses associated with this response representation.
+ */
+ private List<Status> statuses;
+
+ /**
+ * Constructor.
+ */
+ public ResponseInfo() {
+ super();
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ResponseInfo(DocumentationInfo documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Constructor with a list of documentation elements.
+ *
+ * @param documentations
+ * The list of documentation elements.
+ */
+ public ResponseInfo(List<DocumentationInfo> documentations) {
+ super(documentations);
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param documentation
+ * A single documentation element.
+ */
+ public ResponseInfo(String documentation) {
+ super(documentation);
+ }
+
+ /**
+ * Returns the list of parameters.
+ *
+ * @return The list of parameters.
+ */
+ public List<ParameterInfo> getParameters() {
+ // Lazy initialization with double-check.
+ List<ParameterInfo> p = this.parameters;
+ if (p == null) {
+ synchronized (this) {
+ p = this.parameters;
+ if (p == null) {
+ this.parameters = p = new ArrayList<ParameterInfo>();
+ }
+ }
+ }
+ return p;
+ }
+
+ /**
+ * Returns the list of representations
+ *
+ * @return The list of representations
+ */
+ public List<RepresentationInfo> getRepresentations() {
+ // Lazy initialization with double-check.
+ List<RepresentationInfo> r = this.representations;
+ if (r == null) {
+ synchronized (this) {
+ r = this.representations;
+ if (r == null) {
+ this.representations = r = new ArrayList<RepresentationInfo>();
+ }
+ }
+ }
+ return r;
+ }
+
+ /**
+ * Returns the list of statuses associated with this response
+ * representation.
+ *
+ * @return The list of statuses associated with this response
+ * representation.
+ */
+ public List<Status> getStatuses() {
+ // Lazy initialization with double-check.
+ List<Status> s = this.statuses;
+ if (s == null) {
+ synchronized (this) {
+ s = this.statuses;
+ if (s == null) {
+ this.statuses = s = new ArrayList<Status>();
+ }
+ }
+ }
+ return s;
+ }
+
+ /**
+ * Sets the list of parameters.
+ *
+ * @param parameters
+ * The list of parameters.
+ */
+ public void setParameters(List<ParameterInfo> parameters) {
+ this.parameters = parameters;
+ }
+
+ /**
+ * Sets the list of representations
+ *
+ * @param representations
+ * The list of representations
+ */
+ public void setRepresentations(List<RepresentationInfo> representations) {
+ this.representations = representations;
+ }
+
+ /**
+ * Sets the list of statuses associated with this response representation.
+ *
+ * @param statuses
+ * The list of statuses associated with this response
+ * representation.
+ */
+ public void setStatuses(List<Status> statuses) {
+ this.statuses = statuses;
+ }
+
+}
diff --git a/modules/org.restlet/.settings/org.eclipse.jdt.core.prefs b/modules/org.restlet/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000000..f42de363af
--- /dev/null
+++ b/modules/org.restlet/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,7 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
+org.eclipse.jdt.core.compiler.compliance=1.7
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.7
|
52bd53f5ea5eec84818d65b40e81d0a82ada6ba8
|
ReactiveX-RxJava
|
Restructure into smaller files--
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/.classpath b/.classpath
deleted file mode 100644
index b1ae8bae1c..0000000000
--- a/.classpath
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry exported="true" kind="con" path="GROOVY_DSL_SUPPORT"/>
- <classpathentry kind="con" path="GROOVY_SUPPORT"/>
- <classpathentry exported="true" kind="con" path="com.springsource.sts.gradle.classpathcontainer"/>
- <classpathentry kind="con" path="com.springsource.sts.gradle.dsld.classpathcontainer"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/.gitignore b/.gitignore
index 618e741f86..313af3cb82 100644
--- a/.gitignore
+++ b/.gitignore
@@ -38,3 +38,26 @@ Thumbs.db
# Gradle Files #
################
.gradle
+
+# Build output directies
+/target
+*/target
+/build
+*/build
+#
+# # IntelliJ specific files/directories
+out
+.idea
+*.ipr
+*.iws
+*.iml
+atlassian-ide-plugin.xml
+
+# Eclipse specific files/directories
+.classpath
+.project
+.settings
+.metadata
+
+# NetBeans specific files/directories
+.nbattrs
diff --git a/.project b/.project
deleted file mode 100644
index f2d845e45a..0000000000
--- a/.project
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>gradle-template</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>com.springsource.sts.gradle.core.nature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.jdt.groovy.core.groovyNature</nature>
- </natures>
- <filteredResources>
- <filter>
- <id>1332049227118</id>
- <name></name>
- <type>10</type>
- <matcher>
- <id>org.eclipse.ui.ide.orFilterMatcher</id>
- <arguments>
- <matcher>
- <id>org.eclipse.ui.ide.multiFilter</id>
- <arguments>1.0-projectRelativePath-equals-true-false-template-server</arguments>
- </matcher>
- <matcher>
- <id>org.eclipse.ui.ide.multiFilter</id>
- <arguments>1.0-projectRelativePath-equals-true-false-template-client</arguments>
- </matcher>
- </arguments>
- </matcher>
- </filter>
- </filteredResources>
-</projectDescription>
diff --git a/.settings/gradle/com.springsource.sts.gradle.core.import.prefs b/.settings/gradle/com.springsource.sts.gradle.core.import.prefs
deleted file mode 100644
index e86c91081f..0000000000
--- a/.settings/gradle/com.springsource.sts.gradle.core.import.prefs
+++ /dev/null
@@ -1,9 +0,0 @@
-#com.springsource.sts.gradle.core.preferences.GradleImportPreferences
-#Sat Mar 17 22:40:13 PDT 2012
-enableAfterTasks=true
-afterTasks=afterEclipseImport;
-enableDependendencyManagement=true
-enableBeforeTasks=true
-projects=;template-client;template-server;
-enableDSLD=true
-beforeTasks=cleanEclipse;eclipse;
diff --git a/.settings/gradle/com.springsource.sts.gradle.core.prefs b/.settings/gradle/com.springsource.sts.gradle.core.prefs
deleted file mode 100644
index 445ff6da6f..0000000000
--- a/.settings/gradle/com.springsource.sts.gradle.core.prefs
+++ /dev/null
@@ -1,4 +0,0 @@
-#com.springsource.sts.gradle.core.preferences.GradleProjectPreferences
-#Sat Mar 17 22:40:29 PDT 2012
-com.springsource.sts.gradle.rootprojectloc=
-com.springsource.sts.gradle.linkedresources=
diff --git a/.settings/gradle/com.springsource.sts.gradle.refresh.prefs b/.settings/gradle/com.springsource.sts.gradle.refresh.prefs
deleted file mode 100644
index 01e59693e7..0000000000
--- a/.settings/gradle/com.springsource.sts.gradle.refresh.prefs
+++ /dev/null
@@ -1,9 +0,0 @@
-#com.springsource.sts.gradle.core.actions.GradleRefreshPreferences
-#Sat Mar 17 22:40:27 PDT 2012
-enableAfterTasks=true
-afterTasks=afterEclipseImport;
-useHierarchicalNames=false
-enableBeforeTasks=true
-addResourceFilters=true
-enableDSLD=true
-beforeTasks=cleanEclipse;eclipse;
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000..7f8ced0d1f
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2012 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.
diff --git a/build.gradle b/build.gradle
index 5297034a51..9eef3329e1 100644
--- a/build.gradle
+++ b/build.gradle
@@ -5,18 +5,16 @@ ext.githubProjectName = rootProject.name // TEMPLATE: change to match github pro
apply from: file('gradle/convention.gradle')
apply from: file('gradle/maven.gradle')
apply from: file('gradle/check.gradle')
+apply from: file('gradle/license.gradle')
-subprojects
-{
- group = 'com.netflix'
+subprojects {
+ group = 'com.netflix.osstemplate' // TEMPLATE: Set to organization of project
- repositories
- {
+ repositories {
mavenCentral()
}
- dependencies
- {
+ dependencies {
compile 'javax.ws.rs:jsr311-api:1.1.1'
compile 'com.sun.jersey:jersey-core:1.11'
testCompile 'org.testng:testng:6.1.1'
@@ -24,21 +22,17 @@ subprojects
}
}
-project(':template-client')
-{
- dependencies
- {
+project(':template-client') {
+ dependencies {
compile 'org.slf4j:slf4j-api:1.6.3'
compile 'com.sun.jersey:jersey-client:1.11'
}
}
-project(':template-server')
-{
+project(':template-server') {
apply plugin: 'war'
apply plugin: 'jetty'
- dependencies
- {
+ dependencies {
compile 'com.sun.jersey:jersey-server:1.11'
compile 'com.sun.jersey:jersey-servlet:1.11'
compile project(':template-client')
diff --git a/codequality/HEADER b/codequality/HEADER
new file mode 100644
index 0000000000..b27b192925
--- /dev/null
+++ b/codequality/HEADER
@@ -0,0 +1,13 @@
+ Copyright 2012 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.
diff --git a/codequality/checkstyle.xml b/codequality/checkstyle.xml
index 3c8a8e6c75..481d2829fd 100644
--- a/codequality/checkstyle.xml
+++ b/codequality/checkstyle.xml
@@ -50,6 +50,7 @@
<property name="allowMissingReturnTag" value="true"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="allowUndeclaredRTE" value="true"/>
+ <property name="allowMissingPropertyJavadoc" value="true"/>
</module>
<module name="JavadocType">
<property name="scope" value="package"/>
diff --git a/gradle/check.gradle b/gradle/check.gradle
index cf6f0461ae..0f80516d45 100644
--- a/gradle/check.gradle
+++ b/gradle/check.gradle
@@ -9,8 +9,10 @@ subprojects {
// FindBugs
apply plugin: 'findbugs'
+ //tasks.withType(Findbugs) { reports.html.enabled true }
// PMD
apply plugin: 'pmd'
+ //tasks.withType(Pmd) { reports.html.enabled true }
}
diff --git a/gradle/license.gradle b/gradle/license.gradle
new file mode 100644
index 0000000000..9d04830321
--- /dev/null
+++ b/gradle/license.gradle
@@ -0,0 +1,5 @@
+buildscript {
+ dependencies { classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.4' }
+}
+
+apply plugin: 'license'
\ No newline at end of file
diff --git a/gradle/local.gradle b/gradle/local.gradle
new file mode 100644
index 0000000000..6f2d204b8a
--- /dev/null
+++ b/gradle/local.gradle
@@ -0,0 +1 @@
+apply from: 'file://Users/jryan/Workspaces/jryan_build/Tools/nebula-boot/artifactory.gradle'
diff --git a/gradle/maven.gradle b/gradle/maven.gradle
index 8639564ce4..cb75dfb637 100644
--- a/gradle/maven.gradle
+++ b/gradle/maven.gradle
@@ -4,7 +4,7 @@ subprojects {
apply plugin: 'signing'
signing {
- required rootProject.performingRelease
+ required { performingRelease && gradle.taskGraph.hasTask("uploadMavenCentral")}
sign configurations.archives
}
diff --git a/template-client/bin/com/netflix/template/client/TalkClient.class b/template-client/bin/com/netflix/template/client/TalkClient.class
deleted file mode 100644
index 90bbaeb353..0000000000
Binary files a/template-client/bin/com/netflix/template/client/TalkClient.class and /dev/null differ
diff --git a/template-client/bin/com/netflix/template/common/Sentence.class b/template-client/bin/com/netflix/template/common/Sentence.class
deleted file mode 100644
index 0083f33477..0000000000
Binary files a/template-client/bin/com/netflix/template/common/Sentence.class and /dev/null differ
diff --git a/template-client/src/main/java/com/netflix/template/client/TalkClient.java b/template-client/src/main/java/com/netflix/template/client/TalkClient.java
index c3ebf86090..fc9d20d33d 100644
--- a/template-client/src/main/java/com/netflix/template/client/TalkClient.java
+++ b/template-client/src/main/java/com/netflix/template/client/TalkClient.java
@@ -8,26 +8,42 @@
import javax.ws.rs.core.MediaType;
+/**
+ * Delegates to remote TalkServer over REST.
+ * @author jryan
+ *
+ */
public class TalkClient implements Conversation {
- WebResource webResource;
+ private WebResource webResource;
- TalkClient(String location) {
+ /**
+ * Instantiate client.
+ *
+ * @param location URL to the base of resources, e.g. http://localhost:8080/template-server/rest
+ */
+ public TalkClient(String location) {
Client client = Client.create();
client.addFilter(new LoggingFilter(System.out));
webResource = client.resource(location + "/talk");
}
+ @Override
public Sentence greeting() {
Sentence s = webResource.accept(MediaType.APPLICATION_XML).get(Sentence.class);
return s;
}
+ @Override
public Sentence farewell() {
Sentence s = webResource.accept(MediaType.APPLICATION_XML).delete(Sentence.class);
return s;
}
+ /**
+ * Tests out client.
+ * @param args Not applicable
+ */
public static void main(String[] args) {
TalkClient remote = new TalkClient("http://localhost:8080/template-server/rest");
System.out.println(remote.greeting().getWhole());
diff --git a/template-client/src/main/java/com/netflix/template/common/Conversation.java b/template-client/src/main/java/com/netflix/template/common/Conversation.java
index b85e23e98b..c190f03bb7 100644
--- a/template-client/src/main/java/com/netflix/template/common/Conversation.java
+++ b/template-client/src/main/java/com/netflix/template/common/Conversation.java
@@ -1,6 +1,21 @@
package com.netflix.template.common;
+/**
+ * Hold a conversation.
+ * @author jryan
+ *
+ */
public interface Conversation {
+
+ /**
+ * Initiates a conversation.
+ * @return Sentence words from geeting
+ */
Sentence greeting();
+
+ /**
+ * End the conversation.
+ * @return
+ */
Sentence farewell();
-}
\ No newline at end of file
+}
diff --git a/template-client/src/main/java/com/netflix/template/common/Sentence.java b/template-client/src/main/java/com/netflix/template/common/Sentence.java
index bf561a6d5a..616f72efb0 100644
--- a/template-client/src/main/java/com/netflix/template/common/Sentence.java
+++ b/template-client/src/main/java/com/netflix/template/common/Sentence.java
@@ -3,17 +3,31 @@
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
+/**
+ * Container for words going back and forth.
+ * @author jryan
+ *
+ */
@XmlRootElement
public class Sentence {
private String whole;
+ @SuppressWarnings("unused")
private Sentence() {
};
+ /**
+ * Initialize sentence.
+ * @param whole
+ */
public Sentence(String whole) {
this.whole = whole;
}
+ /**
+ * whole getter.
+ * @return
+ */
@XmlElement
public String getWhole() {
return whole;
@@ -22,4 +36,4 @@ public String getWhole() {
public void setWhole(String whole) {
this.whole = whole;
}
-}
\ No newline at end of file
+}
|
12aa442f95c567f3bc1488bb641fca1e9636e9f1
|
restlet-framework-java
|
Fixed issue 210 : a Language tag is composed of a- list of subtags--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/module/org.restlet/src/org/restlet/data/Language.java b/module/org.restlet/src/org/restlet/data/Language.java
index 050fea006c..cae571f3ef 100644
--- a/module/org.restlet/src/org/restlet/data/Language.java
+++ b/module/org.restlet/src/org/restlet/data/Language.java
@@ -60,9 +60,6 @@ public final class Language extends Metadata {
public static final Language SPANISH = new Language("es",
"Spanish language");
- /** The metadata main tag taken from the metadata name like "en" for "en-us". */
- private String primaryTag;
-
/** The metadata main list of subtags taken from the metadata name. */
private List<String> subTags;
@@ -117,15 +114,7 @@ public Language(final String name) {
*/
public Language(final String name, final String description) {
super(name, description);
- String[] tags = getName().split("-");
- subTags = new ArrayList<String>();
-
- if (tags.length > 0) {
- primaryTag = tags[0];
- for (int i = 1; i < tags.length; i++) {
- subTags.add(tags[i]);
- }
- }
+ this.subTags = null;
}
/** {@inheritDoc} */
@@ -141,7 +130,29 @@ public boolean equals(final Object object) {
* @return The primary tag.
*/
public String getPrimaryTag() {
- return this.primaryTag;
+ int separator = getName().indexOf('-');
+
+ if (separator == -1) {
+ return getName();
+ } else {
+ return getName().substring(0, separator);
+ }
+ }
+
+ /**
+ * Returns the main tag.
+ *
+ * @return The main tag.
+ */
+ @Deprecated
+ public String getMainTag() {
+ int separator = getName().indexOf('-');
+
+ if (separator == -1) {
+ return getName();
+ } else {
+ return getName().substring(0, separator);
+ }
}
/**
@@ -150,6 +161,17 @@ public String getPrimaryTag() {
* @return The list of subtags for this language Tag.
*/
public List<String> getSubTags() {
+ if (subTags == null) {
+ String[] tags = getName().split("-");
+ subTags = new ArrayList<String>();
+
+ if (tags.length > 0) {
+ for (int i = 1; i < tags.length; i++) {
+ subTags.add(tags[i]);
+ }
+ }
+ }
+
return subTags;
}
|
02ffd6ae37a11cb0acc920bada87c994559d396b
|
drools
|
BZ-1044973 - Guided rule editor does not let the- user to set objects as a parameters for method calls that have objects super- type as a parameter--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/ActionCallMethodBuilder.java b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/ActionCallMethodBuilder.java
index 8a5938ec0a4..08156a0452e 100644
--- a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/ActionCallMethodBuilder.java
+++ b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/ActionCallMethodBuilder.java
@@ -116,16 +116,27 @@ private String getDataType( String param,
}
private MethodInfo getMethodInfo() {
- String variableType = boundParams.get( variable );
- if ( variableType != null ) {
- List<MethodInfo> methods = getMethodInfosForType( model,
- dmo,
- variableType );
- if ( methods != null ) {
- for ( MethodInfo method : methods ) {
- if ( method.getName().equals( methodName ) ) {
- return method;
+ String variableType = boundParams.get(variable);
+ if (variableType != null) {
+ List<MethodInfo> methods = getMethodInfosForType(model,
+ dmo,
+ variableType);
+ if (methods != null) {
+
+ ArrayList<MethodInfo> methodInfos = getMethodInfos(methodName, methods);
+
+ if (methodInfos.size() > 1) {
+ // Now if there were more than one method with the same name
+ // we need to start figuring out what is the correct one.
+ for (MethodInfo methodInfo : methodInfos) {
+ if (compareParameters(methodInfo.getParams())) {
+ return methodInfo;
+ }
}
+ } else if (!methodInfos.isEmpty()){
+ // Not perfect, but works on most cases.
+ // There is no check if the parameter types match.
+ return methodInfos.get(0);
}
}
}
@@ -133,4 +144,27 @@ private MethodInfo getMethodInfo() {
return null;
}
+ private ArrayList<MethodInfo> getMethodInfos(String methodName, List<MethodInfo> methods) {
+ ArrayList<MethodInfo> result = new ArrayList<MethodInfo>();
+ for (MethodInfo method : methods) {
+ if (method.getName().equals(methodName)) {
+ result.add(method);
+ }
+ }
+ return result;
+ }
+
+ private boolean compareParameters(List<String> methodParams) {
+ if (methodParams.size() != parameters.length) {
+ return false;
+ } else {
+ for (int index = 0; index < methodParams.size(); index++) {
+ if (!methodParams.get(index).equals(boundParams.get(parameters[index]))) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+
}
diff --git a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
index 9bf47778577..a1de643d986 100644
--- a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
+++ b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
@@ -3273,7 +3273,6 @@ public void testDSLExpansionRHS() {
}
@Test
- @Ignore(" Still does not know the difference between indexOf(int) and indexOf(String) ")
public void testFunctionCalls() {
String drl =
"package org.mortgages\n" +
@@ -3289,21 +3288,19 @@ public void testFunctionCalls() {
+ "end\n";
Map<String, List<MethodInfo>> methodInformation = new HashMap<String, List<MethodInfo>>();
- List<MethodInfo> mapMethodInformation1 = new ArrayList<MethodInfo>();
- mapMethodInformation1.add( new MethodInfo( "indexOf",
+ List<MethodInfo> mapMethodInformation = new ArrayList<MethodInfo>();
+ mapMethodInformation.add( new MethodInfo( "indexOf",
Arrays.asList( new String[]{ "String" } ),
"int",
null,
"String" ) );
- List<MethodInfo> mapMethodInformation2 = new ArrayList<MethodInfo>();
- mapMethodInformation2.add( new MethodInfo( "indexOf",
+ mapMethodInformation.add( new MethodInfo( "indexOf",
Arrays.asList( new String[]{ "Integer" } ),
"int",
null,
"String" ) );
- methodInformation.put( "java.lang.String", mapMethodInformation2 );
- methodInformation.put( "java.lang.String", mapMethodInformation1 );
+ methodInformation.put( "java.lang.String", mapMethodInformation );
when( dmo.getProjectMethodInformation() ).thenReturn( methodInformation );
|
8467928cf0639c9783a5f03168af547ffe8a23c8
|
camel
|
CAMEL-4023 Properties to Cxf ClientProxyFactory- can be set on endpoint uri or CxfEndpoint bean.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1128561 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/camel
|
diff --git a/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfComponent.java b/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfComponent.java
index 5133229a23c88..f7bfe4b9b5713 100644
--- a/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfComponent.java
+++ b/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfComponent.java
@@ -88,6 +88,8 @@ protected Endpoint createEndpoint(String uri, String remaining,
Map<String, Object> properties = IntrospectionSupport.extractProperties(parameters, "properties.");
if (properties != null) {
result.setProperties(properties);
+ // set the properties of MTOM
+ result.setMtomEnabled(Boolean.valueOf((String)properties.get(Message.MTOM_ENABLED)));
}
return result;
diff --git a/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java b/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java
index 10f70ea88739c..d66ae60c8076a 100644
--- a/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java
+++ b/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java
@@ -188,12 +188,12 @@ protected void setupServerFactoryBean(ServerFactoryBean sfb, Class<?> cls) {
}
// any optional properties
- if (properties != null) {
+ if (getProperties() != null) {
if (sfb.getProperties() != null) {
// add to existing properties
- sfb.getProperties().putAll(properties);
+ sfb.getProperties().putAll(getProperties());
} else {
- sfb.setProperties(properties);
+ sfb.setProperties(getProperties());
}
LOG.debug("ServerFactoryBean: {} added properties: {}", sfb, properties);
}
@@ -299,6 +299,17 @@ protected void setupClientFactoryBean(ClientProxyFactoryBean factoryBean, Class<
factoryBean.getServiceFactory().setWrapped(getWrappedStyle());
}
+ // set the properties on CxfProxyFactoryBean
+ if (getProperties() != null) {
+ if (factoryBean.getProperties() != null) {
+ // add to existing properties
+ factoryBean.getProperties().putAll(getProperties());
+ } else {
+ factoryBean.setProperties(getProperties());
+ }
+ LOG.debug("ClientProxyFactoryBean: {} added properties: {}", factoryBean, properties);
+ }
+
factoryBean.setBus(getBus());
}
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java
index 7fce8263687f6..cf69d4ee9b6b4 100644
--- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java
+++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java
@@ -36,7 +36,8 @@ public class CxfJavaOnlyPayloadModeTest extends CamelTestSupport {
+ "?wsdlURL=classpath:person.wsdl"
+ "&serviceName={http://camel.apache.org/wsdl-first}PersonService"
+ "&portName={http://camel.apache.org/wsdl-first}soap"
- + "&dataFormat=PAYLOAD";
+ + "&dataFormat=PAYLOAD"
+ + "&properties.exceptionMessageCauseEnabled=true&properties.faultStackTraceEnabled=true";
@Test
public void testCxfJavaOnly() throws Exception {
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/mtom/CxfMtomConsumerTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/mtom/CxfMtomConsumerTest.java
index 71c0d77041751..275412bfb2883 100644
--- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/mtom/CxfMtomConsumerTest.java
+++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/mtom/CxfMtomConsumerTest.java
@@ -40,7 +40,7 @@
public class CxfMtomConsumerTest extends CamelTestSupport {
protected static final String MTOM_ENDPOINT_ADDRESS = "http://localhost:9091/jaxws-mtom/hello";
protected static final String MTOM_ENDPOINT_URI = "cxf://" + MTOM_ENDPOINT_ADDRESS
- + "?serviceClass=org.apache.camel.component.cxf.HelloImpl";
+ + "?serviceClass=org.apache.camel.cxf.mtom_feature.Hello";
private final QName serviceName = new QName("http://apache.org/camel/cxf/mtom_feature", "HelloService");
@@ -83,12 +83,12 @@ private Hello getPort() {
return service.getHelloPort();
}
- private Image getImage(String name) throws Exception {
+ protected Image getImage(String name) throws Exception {
return ImageIO.read(getClass().getResource(name));
}
@Test
- public void testInvokingServiceFromCXFClient() throws Exception {
+ public void testInvokingService() throws Exception {
if (Boolean.getBoolean("java.awt.headless")
|| System.getProperty("os.name").startsWith("Mac OS") && System.getProperty("user.name").equals("cruise")) {
|
ca2f1678d75d9d42867f2124fa3e7dfcf1c367f7
|
hbase
|
HBASE-2757. Fix flaky TestFromClientSide test by- forcing region assignment--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@956716 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 6bba3feb2be6..a0cfef66001f 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -403,6 +403,7 @@ Release 0.21.0 - Unreleased
HBASE-2760 Fix MetaScanner TableNotFoundException when scanning starting at
the first row in a table.
HBASE-1025 Reconstruction log playback has no bounds on memory used
+ HBASE-2757 Fix flaky TestFromClientSide test by forcing region assignment
IMPROVEMENTS
HBASE-1760 Cleanup TODOs in HTable
diff --git a/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java b/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
index 74a0c63c9a96..fc7b2afa7132 100644
--- a/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
+++ b/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
@@ -3637,7 +3637,13 @@ public void testRegionCachePreWarm() throws Exception {
// create many regions for the table.
TEST_UTIL.createMultiRegions(table, FAMILY);
-
+ // This count effectively waits until the regions have been
+ // fully assigned
+ TEST_UTIL.countRows(table);
+ table.getConnection().clearRegionCache();
+ assertEquals("Clearing cache should have 0 cached ", 0,
+ HConnectionManager.getCachedRegionCount(conf, TABLENAME));
+
// A Get is suppose to do a region lookup request
Get g = new Get(Bytes.toBytes("aaa"));
table.get(g);
|
c9d4924dcf129512dadd22dcd6fe0046cbcded43
|
drools
|
BZ-1039639 - GRE doesn't recognize MVEL inline- lists when opening rule--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
index 05b7b836bf1..9da1dd93e78 100644
--- a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
+++ b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
@@ -26,7 +26,9 @@
import org.drools.workbench.models.datamodel.oracle.ModelField;
import org.drools.workbench.models.datamodel.oracle.PackageDataModelOracle;
import org.drools.workbench.models.datamodel.rule.ActionCallMethod;
+import org.drools.workbench.models.datamodel.rule.ActionFieldValue;
import org.drools.workbench.models.datamodel.rule.ActionGlobalCollectionAdd;
+import org.drools.workbench.models.datamodel.rule.ActionSetField;
import org.drools.workbench.models.datamodel.rule.BaseSingleFieldConstraint;
import org.drools.workbench.models.datamodel.rule.CEPWindow;
import org.drools.workbench.models.datamodel.rule.CompositeFactPattern;
@@ -36,6 +38,8 @@
import org.drools.workbench.models.datamodel.rule.ExpressionVariable;
import org.drools.workbench.models.datamodel.rule.FactPattern;
import org.drools.workbench.models.datamodel.rule.FieldConstraint;
+import org.drools.workbench.models.datamodel.rule.FieldNature;
+import org.drools.workbench.models.datamodel.rule.FieldNatureType;
import org.drools.workbench.models.datamodel.rule.FreeFormLine;
import org.drools.workbench.models.datamodel.rule.IPattern;
import org.drools.workbench.models.datamodel.rule.RuleModel;
@@ -1982,6 +1986,43 @@ public void testExpressionWithListSize() throws Exception {
assertEquals(1,constraint.getConstraintValueType());
}
+ @Test
+ @Ignore("https://bugzilla.redhat.com/show_bug.cgi?id=1039639 - GRE doesn't recognize MVEL inline lists when opening rule")
+ public void testMVELInlineList() throws Exception {
+ String drl = "" +
+ "rule \"Borked\"\n" +
+ " dialect \"mvel\"\n" +
+ " when\n" +
+ " c : Company( )\n" +
+ " then\n" +
+ " c.setEmps( [\"item1\", \"item2\"] );\n" +
+ "end";
+
+ addModelField("Company",
+ "emps",
+ "java.util.List",
+ "List");
+
+ RuleModel m = RuleModelDRLPersistenceImpl.getInstance().unmarshal( drl,
+ dmo );
+ assertEquals( 1,
+ m.rhs.length );
+ assertTrue( m.rhs[0] instanceof ActionSetField);
+ ActionSetField actionSetField = (ActionSetField) m.rhs[0];
+
+ assertEquals("c", actionSetField.getVariable());
+
+ assertEquals(1, actionSetField.getFieldValues().length);
+
+ ActionFieldValue actionFieldValue = actionSetField.getFieldValues()[0];
+
+ assertEquals("[\"item1\", \"item2\"]",actionFieldValue.getValue());
+ assertEquals("emps",actionFieldValue.getField());
+ assertEquals(FieldNatureType.TYPE_FORMULA, actionFieldValue.getNature());
+ assertEquals("Collection",actionFieldValue.getType());
+
+ }
+
private void assertEqualsIgnoreWhitespace( final String expected,
final String actual ) {
final String cleanExpected = expected.replaceAll( "\\s+",
|
d4bc187be90fb4bf65bde43d6166073429041749
|
elasticsearch
|
rename node to DiscoveryNode--
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodeInfo.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodeInfo.java
index 88480851d0bdc..a942fced4d2f6 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodeInfo.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/node/info/NodeInfo.java
@@ -21,7 +21,7 @@
import com.google.common.collect.ImmutableMap;
import org.elasticsearch.action.support.nodes.NodeOperationResponse;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.util.io.stream.StreamInput;
import org.elasticsearch.util.io.stream.StreamOutput;
import org.elasticsearch.util.settings.ImmutableSettings;
@@ -42,11 +42,11 @@ public class NodeInfo extends NodeOperationResponse {
NodeInfo() {
}
- public NodeInfo(Node node, Map<String, String> attributes, Settings settings) {
+ public NodeInfo(DiscoveryNode node, Map<String, String> attributes, Settings settings) {
this(node, ImmutableMap.copyOf(attributes), settings);
}
- public NodeInfo(Node node, ImmutableMap<String, String> attributes, Settings settings) {
+ public NodeInfo(DiscoveryNode node, ImmutableMap<String, String> attributes, Settings settings) {
super(node);
this.attributes = attributes;
this.settings = settings;
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/node/shutdown/NodesShutdownResponse.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/node/shutdown/NodesShutdownResponse.java
index 9b6104df3fe84..4c887230a8891 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/node/shutdown/NodesShutdownResponse.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/cluster/node/shutdown/NodesShutdownResponse.java
@@ -22,7 +22,7 @@
import org.elasticsearch.action.support.nodes.NodeOperationResponse;
import org.elasticsearch.action.support.nodes.NodesOperationResponse;
import org.elasticsearch.cluster.ClusterName;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.util.io.stream.StreamInput;
import org.elasticsearch.util.io.stream.StreamOutput;
@@ -61,7 +61,7 @@ public static class NodeShutdownResponse extends NodeOperationResponse {
NodeShutdownResponse() {
}
- public NodeShutdownResponse(Node node) {
+ public NodeShutdownResponse(DiscoveryNode node) {
super(node);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryAndFetchAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryAndFetchAction.java
index a29f247815614..4f46b1e1c382d 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryAndFetchAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryAndFetchAction.java
@@ -23,7 +23,7 @@
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.*;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.search.SearchShardTarget;
@@ -74,7 +74,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
return "dfs";
}
- @Override protected void sendExecuteFirstPhase(Node node, InternalSearchRequest request, SearchServiceListener<DfsSearchResult> listener) {
+ @Override protected void sendExecuteFirstPhase(DiscoveryNode node, InternalSearchRequest request, SearchServiceListener<DfsSearchResult> listener) {
searchService.sendExecuteDfs(node, request, listener);
}
@@ -88,7 +88,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
int localOperations = 0;
for (DfsSearchResult dfsResult : dfsResults) {
- Node node = nodes.get(dfsResult.shardTarget().nodeId());
+ DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
localOperations++;
} else {
@@ -101,7 +101,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
threadPool.execute(new Runnable() {
@Override public void run() {
for (DfsSearchResult dfsResult : dfsResults) {
- Node node = nodes.get(dfsResult.shardTarget().nodeId());
+ DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
QuerySearchRequest querySearchRequest = new QuerySearchRequest(dfsResult.id(), dfs);
executeSecondPhase(counter, node, querySearchRequest);
@@ -112,7 +112,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (DfsSearchResult dfsResult : dfsResults) {
- final Node node = nodes.get(dfsResult.shardTarget().nodeId());
+ final DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
final QuerySearchRequest querySearchRequest = new QuerySearchRequest(dfsResult.id(), dfs);
if (localAsync) {
@@ -130,7 +130,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
}
}
- private void executeSecondPhase(final AtomicInteger counter, Node node, QuerySearchRequest querySearchRequest) {
+ private void executeSecondPhase(final AtomicInteger counter, DiscoveryNode node, QuerySearchRequest querySearchRequest) {
searchService.sendExecuteFetch(node, querySearchRequest, new SearchServiceListener<QueryFetchSearchResult>() {
@Override public void onResult(QueryFetchSearchResult result) {
queryFetchResults.put(result.shardTarget(), result);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryThenFetchAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryThenFetchAction.java
index 13581b8ed75d2..b282333958171 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryThenFetchAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryThenFetchAction.java
@@ -23,7 +23,7 @@
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.*;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.search.SearchShardTarget;
@@ -78,7 +78,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
return "dfs";
}
- @Override protected void sendExecuteFirstPhase(Node node, InternalSearchRequest request, SearchServiceListener<DfsSearchResult> listener) {
+ @Override protected void sendExecuteFirstPhase(DiscoveryNode node, InternalSearchRequest request, SearchServiceListener<DfsSearchResult> listener) {
searchService.sendExecuteDfs(node, request, listener);
}
@@ -93,7 +93,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
int localOperations = 0;
for (DfsSearchResult dfsResult : dfsResults) {
- Node node = nodes.get(dfsResult.shardTarget().nodeId());
+ DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
localOperations++;
} else {
@@ -107,7 +107,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
threadPool.execute(new Runnable() {
@Override public void run() {
for (DfsSearchResult dfsResult : dfsResults) {
- Node node = nodes.get(dfsResult.shardTarget().nodeId());
+ DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
QuerySearchRequest querySearchRequest = new QuerySearchRequest(dfsResult.id(), dfs);
executeQuery(counter, querySearchRequest, node);
@@ -118,7 +118,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (DfsSearchResult dfsResult : dfsResults) {
- final Node node = nodes.get(dfsResult.shardTarget().nodeId());
+ final DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
final QuerySearchRequest querySearchRequest = new QuerySearchRequest(dfsResult.id(), dfs);
if (localAsync) {
@@ -136,7 +136,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
}
}
- private void executeQuery(final AtomicInteger counter, QuerySearchRequest querySearchRequest, Node node) {
+ private void executeQuery(final AtomicInteger counter, QuerySearchRequest querySearchRequest, DiscoveryNode node) {
searchService.sendExecuteQuery(node, querySearchRequest, new SearchServiceListener<QuerySearchResult>() {
@Override public void onResult(QuerySearchResult result) {
queryResults.put(result.shardTarget(), result);
@@ -178,7 +178,7 @@ private void innerExecuteFetchPhase() {
final AtomicInteger counter = new AtomicInteger(docIdsToLoad.size());
int localOperations = 0;
for (Map.Entry<SearchShardTarget, ExtTIntArrayList> entry : docIdsToLoad.entrySet()) {
- Node node = nodes.get(entry.getKey().nodeId());
+ DiscoveryNode node = nodes.get(entry.getKey().nodeId());
if (node.id().equals(nodes.localNodeId())) {
localOperations++;
} else {
@@ -192,7 +192,7 @@ private void innerExecuteFetchPhase() {
threadPool.execute(new Runnable() {
@Override public void run() {
for (Map.Entry<SearchShardTarget, ExtTIntArrayList> entry : docIdsToLoad.entrySet()) {
- Node node = nodes.get(entry.getKey().nodeId());
+ DiscoveryNode node = nodes.get(entry.getKey().nodeId());
if (node.id().equals(nodes.localNodeId())) {
FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(queryResults.get(entry.getKey()).id(), entry.getValue());
executeFetch(counter, fetchSearchRequest, node);
@@ -203,7 +203,7 @@ private void innerExecuteFetchPhase() {
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (Map.Entry<SearchShardTarget, ExtTIntArrayList> entry : docIdsToLoad.entrySet()) {
- final Node node = nodes.get(entry.getKey().nodeId());
+ final DiscoveryNode node = nodes.get(entry.getKey().nodeId());
if (node.id().equals(nodes.localNodeId())) {
final FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(queryResults.get(entry.getKey()).id(), entry.getValue());
if (localAsync) {
@@ -223,7 +223,7 @@ private void innerExecuteFetchPhase() {
releaseIrrelevantSearchContexts(queryResults, docIdsToLoad);
}
- private void executeFetch(final AtomicInteger counter, FetchSearchRequest fetchSearchRequest, Node node) {
+ private void executeFetch(final AtomicInteger counter, FetchSearchRequest fetchSearchRequest, DiscoveryNode node) {
searchService.sendExecuteFetch(node, fetchSearchRequest, new SearchServiceListener<FetchSearchResult>() {
@Override public void onResult(FetchSearchResult result) {
fetchResults.put(result.shardTarget(), result);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java
index 37818542ca7cd..3c4682b68a573 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java
@@ -24,7 +24,7 @@
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.search.SearchShardTarget;
@@ -68,7 +68,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
return "query_fetch";
}
- @Override protected void sendExecuteFirstPhase(Node node, InternalSearchRequest request, SearchServiceListener<QueryFetchSearchResult> listener) {
+ @Override protected void sendExecuteFirstPhase(DiscoveryNode node, InternalSearchRequest request, SearchServiceListener<QueryFetchSearchResult> listener) {
searchService.sendExecuteFetch(node, request, listener);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryThenFetchAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryThenFetchAction.java
index adcc6f5b5b150..ef82fa0cc43f9 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryThenFetchAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryThenFetchAction.java
@@ -23,7 +23,7 @@
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.*;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.search.SearchShardTarget;
@@ -72,7 +72,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
return "query";
}
- @Override protected void sendExecuteFirstPhase(Node node, InternalSearchRequest request, SearchServiceListener<QuerySearchResult> listener) {
+ @Override protected void sendExecuteFirstPhase(DiscoveryNode node, InternalSearchRequest request, SearchServiceListener<QuerySearchResult> listener) {
searchService.sendExecuteQuery(node, request, listener);
}
@@ -93,7 +93,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
int localOperations = 0;
for (Map.Entry<SearchShardTarget, ExtTIntArrayList> entry : docIdsToLoad.entrySet()) {
- Node node = nodes.get(entry.getKey().nodeId());
+ DiscoveryNode node = nodes.get(entry.getKey().nodeId());
if (node.id().equals(nodes.localNodeId())) {
localOperations++;
} else {
@@ -107,7 +107,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
threadPool.execute(new Runnable() {
@Override public void run() {
for (Map.Entry<SearchShardTarget, ExtTIntArrayList> entry : docIdsToLoad.entrySet()) {
- Node node = nodes.get(entry.getKey().nodeId());
+ DiscoveryNode node = nodes.get(entry.getKey().nodeId());
if (node.id().equals(nodes.localNodeId())) {
FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(queryResults.get(entry.getKey()).id(), entry.getValue());
executeFetch(counter, fetchSearchRequest, node);
@@ -118,7 +118,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (Map.Entry<SearchShardTarget, ExtTIntArrayList> entry : docIdsToLoad.entrySet()) {
- final Node node = nodes.get(entry.getKey().nodeId());
+ final DiscoveryNode node = nodes.get(entry.getKey().nodeId());
if (node.id().equals(nodes.localNodeId())) {
final FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(queryResults.get(entry.getKey()).id(), entry.getValue());
if (localAsync) {
@@ -138,7 +138,7 @@ private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listen
releaseIrrelevantSearchContexts(queryResults, docIdsToLoad);
}
- private void executeFetch(final AtomicInteger counter, FetchSearchRequest fetchSearchRequest, Node node) {
+ private void executeFetch(final AtomicInteger counter, FetchSearchRequest fetchSearchRequest, DiscoveryNode node) {
searchService.sendExecuteFetch(node, fetchSearchRequest, new SearchServiceListener<FetchSearchResult>() {
@Override public void onResult(FetchSearchResult result) {
fetchResults.put(result.shardTarget(), result);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryAndFetchAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryAndFetchAction.java
index 9d2f0eddbac62..5ccde73ec9f8a 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryAndFetchAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryAndFetchAction.java
@@ -23,8 +23,8 @@
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.*;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.action.SearchServiceListener;
import org.elasticsearch.search.action.SearchServiceTransportAction;
@@ -81,7 +81,7 @@ private class AsyncAction {
private final ParsedScrollId scrollId;
- private final Nodes nodes;
+ private final DiscoveryNodes nodes;
protected final Collection<ShardSearchFailure> shardFailures = searchCache.obtainShardFailures();
@@ -107,7 +107,7 @@ public void start() {
int localOperations = 0;
for (Tuple<String, Long> target : scrollId.values()) {
- Node node = nodes.get(target.v1());
+ DiscoveryNode node = nodes.get(target.v1());
if (node != null) {
if (nodes.localNodeId().equals(node.id())) {
localOperations++;
@@ -130,7 +130,7 @@ public void start() {
threadPool.execute(new Runnable() {
@Override public void run() {
for (Tuple<String, Long> target : scrollId.values()) {
- Node node = nodes.get(target.v1());
+ DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
executePhase(node, target.v2());
}
@@ -140,7 +140,7 @@ public void start() {
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (final Tuple<String, Long> target : scrollId.values()) {
- final Node node = nodes.get(target.v1());
+ final DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
if (localAsync) {
threadPool.execute(new Runnable() {
@@ -157,7 +157,7 @@ public void start() {
}
for (Tuple<String, Long> target : scrollId.values()) {
- Node node = nodes.get(target.v1());
+ DiscoveryNode node = nodes.get(target.v1());
if (node == null) {
if (logger.isDebugEnabled()) {
logger.debug("Node [" + target.v1() + "] not available for scroll request [" + scrollId.source() + "]");
@@ -171,7 +171,7 @@ public void start() {
}
}
- private void executePhase(Node node, long searchId) {
+ private void executePhase(DiscoveryNode node, long searchId) {
searchService.sendExecuteFetch(node, internalScrollSearchRequest(searchId, request), new SearchServiceListener<QueryFetchSearchResult>() {
@Override public void onResult(QueryFetchSearchResult result) {
queryFetchResults.put(result.shardTarget(), result);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryThenFetchAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryThenFetchAction.java
index a146019e986ab..a2f1a00eb04b1 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryThenFetchAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryThenFetchAction.java
@@ -23,8 +23,8 @@
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.*;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.action.SearchServiceListener;
import org.elasticsearch.search.action.SearchServiceTransportAction;
@@ -85,7 +85,7 @@ private class AsyncAction {
private final ParsedScrollId scrollId;
- private final Nodes nodes;
+ private final DiscoveryNodes nodes;
protected final Collection<ShardSearchFailure> shardFailures = searchCache.obtainShardFailures();
@@ -113,7 +113,7 @@ public void start() {
int localOperations = 0;
for (Tuple<String, Long> target : scrollId.values()) {
- Node node = nodes.get(target.v1());
+ DiscoveryNode node = nodes.get(target.v1());
if (node != null) {
if (nodes.localNodeId().equals(node.id())) {
localOperations++;
@@ -136,7 +136,7 @@ public void start() {
threadPool.execute(new Runnable() {
@Override public void run() {
for (Tuple<String, Long> target : scrollId.values()) {
- Node node = nodes.get(target.v1());
+ DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
executeQueryPhase(counter, node, target.v2());
}
@@ -146,7 +146,7 @@ public void start() {
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (final Tuple<String, Long> target : scrollId.values()) {
- final Node node = nodes.get(target.v1());
+ final DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
if (localAsync) {
threadPool.execute(new Runnable() {
@@ -163,7 +163,7 @@ public void start() {
}
}
- private void executeQueryPhase(final AtomicInteger counter, Node node, long searchId) {
+ private void executeQueryPhase(final AtomicInteger counter, DiscoveryNode node, long searchId) {
searchService.sendExecuteQuery(node, internalScrollSearchRequest(searchId, request), new SearchServiceListener<QuerySearchResult>() {
@Override public void onResult(QuerySearchResult result) {
queryResults.put(result.shardTarget(), result);
@@ -199,7 +199,7 @@ private void executeFetchPhase() {
SearchShardTarget shardTarget = entry.getKey();
ExtTIntArrayList docIds = entry.getValue();
FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(queryResults.get(shardTarget).id(), docIds);
- Node node = nodes.get(shardTarget.nodeId());
+ DiscoveryNode node = nodes.get(shardTarget.nodeId());
searchService.sendExecuteFetch(node, fetchSearchRequest, new SearchServiceListener<FetchSearchResult>() {
@Override public void onResult(FetchSearchResult result) {
fetchResults.put(result.shardTarget(), result);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchTypeAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchTypeAction.java
index 5e0ca3d3b8a6d..b186a9e9b5aff 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchTypeAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/search/type/TransportSearchTypeAction.java
@@ -24,8 +24,8 @@
import org.elasticsearch.action.support.BaseAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.GroupShardsIterator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardsIterator;
@@ -83,7 +83,7 @@ protected abstract class BaseAsyncAction<FirstResult> {
protected final SearchRequest request;
- protected final Nodes nodes;
+ protected final DiscoveryNodes nodes;
protected final int expectedSuccessfulOps;
@@ -172,7 +172,7 @@ private void performFirstPhase(final ShardsIterator shardIt) {
// no more active shards... (we should not really get here, but just for safety)
onFirstPhaseResult(shard, shardIt, null);
} else {
- Node node = nodes.get(shard.currentNodeId());
+ DiscoveryNode node = nodes.get(shard.currentNodeId());
sendExecuteFirstPhase(node, internalSearchRequest(shard, request), new SearchServiceListener<FirstResult>() {
@Override public void onResult(FirstResult result) {
onFirstPhaseResult(shard, result, shardIt);
@@ -281,7 +281,7 @@ protected void releaseIrrelevantSearchContexts(Map<SearchShardTarget, QuerySearc
Map<SearchShardTarget, ExtTIntArrayList> docIdsToLoad) {
for (Map.Entry<SearchShardTarget, QuerySearchResultProvider> entry : queryResults.entrySet()) {
if (!docIdsToLoad.containsKey(entry.getKey())) {
- Node node = nodes.get(entry.getKey().nodeId());
+ DiscoveryNode node = nodes.get(entry.getKey().nodeId());
if (node != null) { // should not happen (==null) but safeguard anyhow
searchService.sendFreeContext(node, entry.getValue().id());
}
@@ -313,7 +313,7 @@ protected void invokeListener(final Throwable t) {
}
}
- protected abstract void sendExecuteFirstPhase(Node node, InternalSearchRequest request, SearchServiceListener<FirstResult> listener);
+ protected abstract void sendExecuteFirstPhase(DiscoveryNode node, InternalSearchRequest request, SearchServiceListener<FirstResult> listener);
protected abstract void processFirstPhaseResult(ShardRouting shard, FirstResult result);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastOperationAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastOperationAction.java
index 585a8270ffdb3..ed26cca460e87 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastOperationAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastOperationAction.java
@@ -25,8 +25,8 @@
import org.elasticsearch.action.support.BaseAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.GroupShardsIterator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardsIterator;
@@ -111,7 +111,7 @@ class AsyncBroadcastAction {
private final ClusterState clusterState;
- private final Nodes nodes;
+ private final DiscoveryNodes nodes;
private final GroupShardsIterator shardsIts;
@@ -216,7 +216,7 @@ private void performOperation(final ShardsIterator shardIt, boolean localAsync)
}
}
} else {
- Node node = nodes.get(shard.currentNodeId());
+ DiscoveryNode node = nodes.get(shard.currentNodeId());
transportService.sendRequest(node, transportShardAction(), shardRequest, new BaseTransportResponseHandler<ShardResponse>() {
@Override public ShardResponse newInstance() {
return newShardResponse();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/master/TransportMasterNodeOperationAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/master/TransportMasterNodeOperationAction.java
index 5d0679817754b..8928a5b6ac675 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/master/TransportMasterNodeOperationAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/master/TransportMasterNodeOperationAction.java
@@ -24,7 +24,7 @@
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.support.BaseAction;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import org.elasticsearch.util.settings.Settings;
@@ -60,7 +60,7 @@ protected TransportMasterNodeOperationAction(Settings settings, TransportService
protected abstract Response masterOperation(Request request) throws ElasticSearchException;
@Override protected void doExecute(final Request request, final ActionListener<Response> listener) {
- Nodes nodes = clusterService.state().nodes();
+ DiscoveryNodes nodes = clusterService.state().nodes();
if (nodes.localNodeMaster()) {
threadPool.execute(new Runnable() {
@Override public void run() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/nodes/NodeOperationResponse.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/nodes/NodeOperationResponse.java
index 6e15509d5614d..cd58ba28adcdf 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/nodes/NodeOperationResponse.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/nodes/NodeOperationResponse.java
@@ -19,7 +19,7 @@
package org.elasticsearch.action.support.nodes;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.util.io.stream.StreamInput;
import org.elasticsearch.util.io.stream.StreamOutput;
import org.elasticsearch.util.io.stream.Streamable;
@@ -31,21 +31,21 @@
*/
public abstract class NodeOperationResponse implements Streamable {
- private Node node;
+ private DiscoveryNode node;
protected NodeOperationResponse() {
}
- protected NodeOperationResponse(Node node) {
+ protected NodeOperationResponse(DiscoveryNode node) {
this.node = node;
}
- public Node node() {
+ public DiscoveryNode node() {
return node;
}
@Override public void readFrom(StreamInput in) throws IOException {
- node = Node.readNode(in);
+ node = DiscoveryNode.readNode(in);
}
@Override public void writeTo(StreamOutput out) throws IOException {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/nodes/TransportNodesOperationAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/nodes/TransportNodesOperationAction.java
index 459a8a02e89f1..1406bc171da69 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/nodes/TransportNodesOperationAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/nodes/TransportNodesOperationAction.java
@@ -28,7 +28,7 @@
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import org.elasticsearch.util.settings.Settings;
@@ -108,7 +108,7 @@ private AsyncAction(Request request, ActionListener<Response> listener) {
if (nodesIds == null || nodesIds.length == 0 || (nodesIds.length == 1 && nodesIds[0].equals("_all"))) {
int index = 0;
nodesIds = new String[clusterState.nodes().size()];
- for (Node node : clusterState.nodes()) {
+ for (DiscoveryNode node : clusterState.nodes()) {
nodesIds[index++] = node.id();
}
}
@@ -118,7 +118,7 @@ private AsyncAction(Request request, ActionListener<Response> listener) {
private void start() {
for (final String nodeId : nodesIds) {
- final Node node = clusterState.nodes().nodes().get(nodeId);
+ final DiscoveryNode node = clusterState.nodes().nodes().get(nodeId);
if (nodeId.equals("_local") || nodeId.equals(clusterState.nodes().localNodeId())) {
threadPool.execute(new Runnable() {
@Override public void run() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/replication/TransportShardReplicationOperationAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/replication/TransportShardReplicationOperationAction.java
index 687af98b45983..307c55ba8d373 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/replication/TransportShardReplicationOperationAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/replication/TransportShardReplicationOperationAction.java
@@ -29,8 +29,8 @@
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.TimeoutClusterStateListener;
import org.elasticsearch.cluster.action.shard.ShardStateAction;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardsIterator;
import org.elasticsearch.index.IndexShardMissingException;
@@ -201,7 +201,7 @@ private class AsyncShardOperationAction {
private final Request request;
- private Nodes nodes;
+ private DiscoveryNodes nodes;
private ShardsIterator shards;
@@ -255,7 +255,7 @@ public boolean start(final boolean fromClusterEvent) throws ElasticSearchExcepti
performOnPrimary(shard.id(), fromClusterEvent, false, shard);
}
} else {
- Node node = nodes.get(shard.currentNodeId());
+ DiscoveryNode node = nodes.get(shard.currentNodeId());
transportService.sendRequest(node, transportAction(), request, new BaseTransportResponseHandler<Response>() {
@Override public Response newInstance() {
@@ -399,7 +399,7 @@ private void performBackups(final Response response, boolean alreadyThreaded) {
private void performOnBackup(final Response response, final AtomicInteger counter, final ShardRouting shard, String nodeId) {
final ShardOperationRequest shardRequest = new ShardOperationRequest(shards.shardId().id(), request);
if (!nodeId.equals(nodes.localNodeId())) {
- Node node = nodes.get(nodeId);
+ DiscoveryNode node = nodes.get(nodeId);
transportService.sendRequest(node, transportBackupAction(), shardRequest, new VoidTransportResponseHandler() {
@Override public void handleResponse(VoidStreamable vResponse) {
finishIfPossible();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/single/TransportSingleOperationAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/single/TransportSingleOperationAction.java
index c9299800119a5..2f658c1057a72 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/single/TransportSingleOperationAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/support/single/TransportSingleOperationAction.java
@@ -26,8 +26,8 @@
import org.elasticsearch.action.support.BaseAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardsIterator;
import org.elasticsearch.indices.IndicesService;
@@ -86,7 +86,7 @@ private class AsyncSingleAction {
private final Request request;
- private final Nodes nodes;
+ private final DiscoveryNodes nodes;
private AsyncSingleAction(Request request, ActionListener<Response> listener) {
this.request = request;
@@ -164,7 +164,7 @@ private void perform(final Exception lastException) {
final ShardRouting shard = shardsIt.nextActive();
// no need to check for local nodes, we tried them already in performFirstGet
if (!shard.currentNodeId().equals(nodes.localNodeId())) {
- Node node = nodes.get(shard.currentNodeId());
+ DiscoveryNode node = nodes.get(shard.currentNodeId());
transportService.sendRequest(node, transportShardAction(), new ShardSingleOperationRequest(request, shard.id()), new BaseTransportResponseHandler<Response>() {
@Override public Response newInstance() {
return newResponse();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClient.java b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClient.java
index 4d46c434dd2b3..c9761b7179f9e 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClient.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClient.java
@@ -47,7 +47,7 @@
import org.elasticsearch.client.transport.action.ClientTransportActionModule;
import org.elasticsearch.client.transport.support.InternalTransportClient;
import org.elasticsearch.cluster.ClusterNameModule;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.EnvironmentModule;
import org.elasticsearch.server.internal.InternalSettingsPerparer;
@@ -166,7 +166,7 @@ public ImmutableList<TransportAddress> transportAddresses() {
* <p>The nodes include all the nodes that are currently alive based on the transport
* addresses provided.
*/
- public ImmutableList<Node> connectedNodes() {
+ public ImmutableList<DiscoveryNode> connectedNodes() {
return nodesService.connectedNodes();
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java
index 2e202c239af3a..de32ec5ca6c4b 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java
@@ -28,8 +28,8 @@
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterStateListener;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.BaseTransportResponseHandler;
import org.elasticsearch.transport.ConnectTransportException;
@@ -65,9 +65,9 @@ public class TransportClientNodesService extends AbstractComponent implements Cl
private final Object transportMutex = new Object();
- private volatile ImmutableList<Node> nodes = ImmutableList.of();
+ private volatile ImmutableList<DiscoveryNode> nodes = ImmutableList.of();
- private volatile Nodes discoveredNodes;
+ private volatile DiscoveryNodes discoveredNodes;
private final AtomicInteger tempNodeIdGenerator = new AtomicInteger();
@@ -100,7 +100,7 @@ public ImmutableList<TransportAddress> transportAddresses() {
return this.transportAddresses;
}
- public ImmutableList<Node> connectedNodes() {
+ public ImmutableList<DiscoveryNode> connectedNodes() {
return this.nodes;
}
@@ -128,13 +128,13 @@ public TransportClientNodesService removeTransportAddress(TransportAddress trans
}
public <T> T execute(NodeCallback<T> callback) throws ElasticSearchException {
- ImmutableList<Node> nodes = this.nodes;
+ ImmutableList<DiscoveryNode> nodes = this.nodes;
if (nodes.isEmpty()) {
throw new NoNodeAvailableException();
}
int index = randomNodeGenerator.incrementAndGet();
for (int i = 0; i < nodes.size(); i++) {
- Node node = nodes.get((index + i) % nodes.size());
+ DiscoveryNode node = nodes.get((index + i) % nodes.size());
try {
return callback.doWithNode(node);
} catch (ConnectTransportException e) {
@@ -151,9 +151,9 @@ public void close() {
@Override public void clusterChanged(ClusterChangedEvent event) {
transportService.nodesAdded(event.nodesDelta().addedNodes());
this.discoveredNodes = event.state().nodes();
- HashSet<Node> newNodes = new HashSet<Node>(nodes);
+ HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(nodes);
newNodes.addAll(discoveredNodes.nodes().values());
- nodes = new ImmutableList.Builder<Node>().addAll(newNodes).build();
+ nodes = new ImmutableList.Builder<DiscoveryNode>().addAll(newNodes).build();
transportService.nodesRemoved(event.nodesDelta().removedNodes());
}
@@ -163,11 +163,11 @@ private class ScheduledNodesSampler implements Runnable {
ImmutableList<TransportAddress> transportAddresses = TransportClientNodesService.this.transportAddresses;
final CountDownLatch latch = new CountDownLatch(transportAddresses.size());
final CopyOnWriteArrayList<NodesInfoResponse> nodesInfoResponses = new CopyOnWriteArrayList<NodesInfoResponse>();
- final CopyOnWriteArrayList<Node> tempNodes = new CopyOnWriteArrayList<Node>();
+ final CopyOnWriteArrayList<DiscoveryNode> tempNodes = new CopyOnWriteArrayList<DiscoveryNode>();
for (final TransportAddress transportAddress : transportAddresses) {
threadPool.execute(new Runnable() {
@Override public void run() {
- Node tempNode = new Node("#temp#-" + tempNodeIdGenerator.incrementAndGet(), transportAddress);
+ DiscoveryNode tempNode = new DiscoveryNode("#temp#-" + tempNodeIdGenerator.incrementAndGet(), transportAddress);
tempNodes.add(tempNode);
try {
transportService.nodesAdded(ImmutableList.of(tempNode));
@@ -201,10 +201,10 @@ private class ScheduledNodesSampler implements Runnable {
return;
}
- HashSet<Node> newNodes = new HashSet<Node>();
+ HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>();
for (NodesInfoResponse nodesInfoResponse : nodesInfoResponses) {
if (nodesInfoResponse.nodes().length > 0) {
- Node node = nodesInfoResponse.nodes()[0].node();
+ DiscoveryNode node = nodesInfoResponse.nodes()[0].node();
if (!clusterName.equals(nodesInfoResponse.clusterName())) {
logger.warn("Node {} not part of the cluster {}, ignoring...", node, clusterName);
} else {
@@ -218,7 +218,7 @@ private class ScheduledNodesSampler implements Runnable {
if (discoveredNodes != null) {
newNodes.addAll(discoveredNodes.nodes().values());
}
- nodes = new ImmutableList.Builder<Node>().addAll(newNodes).build();
+ nodes = new ImmutableList.Builder<DiscoveryNode>().addAll(newNodes).build();
transportService.nodesRemoved(tempNodes);
}
@@ -226,6 +226,6 @@ private class ScheduledNodesSampler implements Runnable {
public static interface NodeCallback<T> {
- T doWithNode(Node node) throws ElasticSearchException;
+ T doWithNode(DiscoveryNode node) throws ElasticSearchException;
}
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/action/ClientTransportAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/action/ClientTransportAction.java
index 1fcd4a5145664..cb227b4ffce63 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/action/ClientTransportAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/action/ClientTransportAction.java
@@ -24,14 +24,14 @@
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
/**
* @author kimchy (Shay Banon)
*/
public interface ClientTransportAction<Request extends ActionRequest, Response extends ActionResponse> {
- ActionFuture<Response> execute(Node node, Request request) throws ElasticSearchException;
+ ActionFuture<Response> execute(DiscoveryNode node, Request request) throws ElasticSearchException;
- void execute(Node node, Request request, ActionListener<Response> listener);
+ void execute(DiscoveryNode node, Request request, ActionListener<Response> listener);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/action/support/BaseClientTransportAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/action/support/BaseClientTransportAction.java
index f0d2d5378717d..36c4a853e0c76 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/action/support/BaseClientTransportAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/action/support/BaseClientTransportAction.java
@@ -28,7 +28,7 @@
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.transport.action.ClientTransportAction;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.transport.BaseTransportResponseHandler;
import org.elasticsearch.transport.RemoteTransportException;
import org.elasticsearch.transport.TransportService;
@@ -59,14 +59,14 @@ protected BaseClientTransportAction(Settings settings, TransportService transpor
responseConstructor.setAccessible(true);
}
- @Override public ActionFuture<Response> execute(Node node, Request request) throws ElasticSearchException {
+ @Override public ActionFuture<Response> execute(DiscoveryNode node, Request request) throws ElasticSearchException {
PlainActionFuture<Response> future = newFuture();
request.listenerThreaded(false);
execute(node, request, future);
return future;
}
- @Override public void execute(Node node, final Request request, final ActionListener<Response> listener) {
+ @Override public void execute(DiscoveryNode node, final Request request, final ActionListener<Response> listener) {
transportService.sendRequest(node, action(), request, new BaseTransportResponseHandler<Response>() {
@Override public Response newInstance() {
return BaseClientTransportAction.this.newInstance();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportClient.java b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportClient.java
index 03ef658e0c024..9e9a7fc905233 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportClient.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportClient.java
@@ -51,7 +51,7 @@
import org.elasticsearch.client.transport.action.search.ClientTransportSearchAction;
import org.elasticsearch.client.transport.action.search.ClientTransportSearchScrollAction;
import org.elasticsearch.client.transport.action.terms.ClientTransportTermsAction;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.util.component.AbstractComponent;
import org.elasticsearch.util.settings.Settings;
@@ -112,7 +112,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<IndexResponse> index(final IndexRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<IndexResponse>>() {
- @Override public ActionFuture<IndexResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<IndexResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return indexAction.execute(node, request);
}
});
@@ -120,7 +120,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void index(final IndexRequest request, final ActionListener<IndexResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
indexAction.execute(node, request, listener);
return null;
}
@@ -129,7 +129,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<DeleteResponse> delete(final DeleteRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<DeleteResponse>>() {
- @Override public ActionFuture<DeleteResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<DeleteResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return deleteAction.execute(node, request);
}
});
@@ -137,7 +137,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void delete(final DeleteRequest request, final ActionListener<DeleteResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
deleteAction.execute(node, request, listener);
return null;
}
@@ -146,7 +146,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<DeleteByQueryResponse> deleteByQuery(final DeleteByQueryRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<DeleteByQueryResponse>>() {
- @Override public ActionFuture<DeleteByQueryResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<DeleteByQueryResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return deleteByQueryAction.execute(node, request);
}
});
@@ -154,7 +154,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void deleteByQuery(final DeleteByQueryRequest request, final ActionListener<DeleteByQueryResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
deleteByQueryAction.execute(node, request, listener);
return null;
}
@@ -163,7 +163,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<GetResponse> get(final GetRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<GetResponse>>() {
- @Override public ActionFuture<GetResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<GetResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return getAction.execute(node, request);
}
});
@@ -171,7 +171,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void get(final GetRequest request, final ActionListener<GetResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Object>() {
- @Override public Object doWithNode(Node node) throws ElasticSearchException {
+ @Override public Object doWithNode(DiscoveryNode node) throws ElasticSearchException {
getAction.execute(node, request, listener);
return null;
}
@@ -180,7 +180,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<CountResponse> count(final CountRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<CountResponse>>() {
- @Override public ActionFuture<CountResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<CountResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return countAction.execute(node, request);
}
});
@@ -188,7 +188,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void count(final CountRequest request, final ActionListener<CountResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
countAction.execute(node, request, listener);
return null;
}
@@ -197,7 +197,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<SearchResponse> search(final SearchRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<SearchResponse>>() {
- @Override public ActionFuture<SearchResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<SearchResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return searchAction.execute(node, request);
}
});
@@ -205,7 +205,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void search(final SearchRequest request, final ActionListener<SearchResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Object>() {
- @Override public Object doWithNode(Node node) throws ElasticSearchException {
+ @Override public Object doWithNode(DiscoveryNode node) throws ElasticSearchException {
searchAction.execute(node, request, listener);
return null;
}
@@ -214,7 +214,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<SearchResponse> searchScroll(final SearchScrollRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<SearchResponse>>() {
- @Override public ActionFuture<SearchResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<SearchResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return searchScrollAction.execute(node, request);
}
});
@@ -222,7 +222,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void searchScroll(final SearchScrollRequest request, final ActionListener<SearchResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Object>() {
- @Override public Object doWithNode(Node node) throws ElasticSearchException {
+ @Override public Object doWithNode(DiscoveryNode node) throws ElasticSearchException {
searchScrollAction.execute(node, request, listener);
return null;
}
@@ -231,7 +231,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<TermsResponse> terms(final TermsRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<TermsResponse>>() {
- @Override public ActionFuture<TermsResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<TermsResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return termsAction.execute(node, request);
}
});
@@ -239,7 +239,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void terms(final TermsRequest request, final ActionListener<TermsResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Void>>() {
- @Override public ActionFuture<Void> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<Void> doWithNode(DiscoveryNode node) throws ElasticSearchException {
termsAction.execute(node, request, listener);
return null;
}
@@ -248,7 +248,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public ActionFuture<SearchResponse> moreLikeThis(final MoreLikeThisRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<SearchResponse>>() {
- @Override public ActionFuture<SearchResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<SearchResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return moreLikeThisAction.execute(node, request);
}
});
@@ -256,7 +256,7 @@ public class InternalTransportClient extends AbstractComponent implements Client
@Override public void moreLikeThis(final MoreLikeThisRequest request, final ActionListener<SearchResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
moreLikeThisAction.execute(node, request, listener);
return null;
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportClusterAdminClient.java b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportClusterAdminClient.java
index 0420e6b47f05d..7fa4dbcb7837b 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportClusterAdminClient.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportClusterAdminClient.java
@@ -46,7 +46,7 @@
import org.elasticsearch.client.transport.action.admin.cluster.ping.replication.ClientTransportReplicationPingAction;
import org.elasticsearch.client.transport.action.admin.cluster.ping.single.ClientTransportSinglePingAction;
import org.elasticsearch.client.transport.action.admin.cluster.state.ClientTransportClusterStateAction;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.util.component.AbstractComponent;
import org.elasticsearch.util.settings.Settings;
@@ -88,7 +88,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public ActionFuture<ClusterHealthResponse> health(final ClusterHealthRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<ClusterHealthResponse>>() {
- @Override public ActionFuture<ClusterHealthResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<ClusterHealthResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return clusterHealthAction.execute(node, request);
}
});
@@ -96,7 +96,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public void health(final ClusterHealthRequest request, final ActionListener<ClusterHealthResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
clusterHealthAction.execute(node, request, listener);
return null;
}
@@ -105,7 +105,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public ActionFuture<ClusterStateResponse> state(final ClusterStateRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<ClusterStateResponse>>() {
- @Override public ActionFuture<ClusterStateResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<ClusterStateResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return clusterStateAction.execute(node, request);
}
});
@@ -113,7 +113,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public void state(final ClusterStateRequest request, final ActionListener<ClusterStateResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
clusterStateAction.execute(node, request, listener);
return null;
}
@@ -122,7 +122,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public ActionFuture<SinglePingResponse> ping(final SinglePingRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<SinglePingResponse>>() {
- @Override public ActionFuture<SinglePingResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<SinglePingResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return singlePingAction.execute(node, request);
}
});
@@ -130,7 +130,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public void ping(final SinglePingRequest request, final ActionListener<SinglePingResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
singlePingAction.execute(node, request, listener);
return null;
}
@@ -139,7 +139,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public ActionFuture<BroadcastPingResponse> ping(final BroadcastPingRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<BroadcastPingResponse>>() {
- @Override public ActionFuture<BroadcastPingResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<BroadcastPingResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return broadcastPingAction.execute(node, request);
}
});
@@ -147,7 +147,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public void ping(final BroadcastPingRequest request, final ActionListener<BroadcastPingResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
broadcastPingAction.execute(node, request, listener);
return null;
}
@@ -156,7 +156,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public ActionFuture<ReplicationPingResponse> ping(final ReplicationPingRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<ReplicationPingResponse>>() {
- @Override public ActionFuture<ReplicationPingResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<ReplicationPingResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return replicationPingAction.execute(node, request);
}
});
@@ -164,7 +164,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public void ping(final ReplicationPingRequest request, final ActionListener<ReplicationPingResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
replicationPingAction.execute(node, request, listener);
return null;
}
@@ -173,7 +173,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public ActionFuture<NodesInfoResponse> nodesInfo(final NodesInfoRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<NodesInfoResponse>>() {
- @Override public ActionFuture<NodesInfoResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<NodesInfoResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return nodesInfoAction.execute(node, request);
}
});
@@ -181,7 +181,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public void nodesInfo(final NodesInfoRequest request, final ActionListener<NodesInfoResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
nodesInfoAction.execute(node, request, listener);
return null;
}
@@ -190,7 +190,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public ActionFuture<NodesShutdownResponse> nodesShutdown(final NodesShutdownRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<NodesShutdownResponse>>() {
- @Override public ActionFuture<NodesShutdownResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<NodesShutdownResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return nodesShutdownAction.execute(node, request);
}
});
@@ -198,7 +198,7 @@ public class InternalTransportClusterAdminClient extends AbstractComponent imple
@Override public void nodesShutdown(final NodesShutdownRequest request, final ActionListener<NodesShutdownResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Void>>() {
- @Override public ActionFuture<Void> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<Void> doWithNode(DiscoveryNode node) throws ElasticSearchException {
nodesShutdownAction.execute(node, request, listener);
return null;
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportIndicesAdminClient.java b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportIndicesAdminClient.java
index d55ab7210b804..170f711c73a2f 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportIndicesAdminClient.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/client/transport/support/InternalTransportIndicesAdminClient.java
@@ -55,7 +55,7 @@
import org.elasticsearch.client.transport.action.admin.indices.optimize.ClientTransportOptimizeAction;
import org.elasticsearch.client.transport.action.admin.indices.refresh.ClientTransportRefreshAction;
import org.elasticsearch.client.transport.action.admin.indices.status.ClientTransportIndicesStatusAction;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.util.component.AbstractComponent;
import org.elasticsearch.util.settings.Settings;
@@ -108,7 +108,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<IndicesStatusResponse> status(final IndicesStatusRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<IndicesStatusResponse>>() {
- @Override public ActionFuture<IndicesStatusResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<IndicesStatusResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return indicesStatusAction.execute(node, request);
}
});
@@ -116,7 +116,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void status(final IndicesStatusRequest request, final ActionListener<IndicesStatusResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
indicesStatusAction.execute(node, request, listener);
return null;
}
@@ -125,7 +125,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<CreateIndexResponse> create(final CreateIndexRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<CreateIndexResponse>>() {
- @Override public ActionFuture<CreateIndexResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<CreateIndexResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return createIndexAction.execute(node, request);
}
});
@@ -133,7 +133,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void create(final CreateIndexRequest request, final ActionListener<CreateIndexResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Object>() {
- @Override public Object doWithNode(Node node) throws ElasticSearchException {
+ @Override public Object doWithNode(DiscoveryNode node) throws ElasticSearchException {
createIndexAction.execute(node, request, listener);
return null;
}
@@ -142,7 +142,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<DeleteIndexResponse> delete(final DeleteIndexRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<DeleteIndexResponse>>() {
- @Override public ActionFuture<DeleteIndexResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<DeleteIndexResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return deleteIndexAction.execute(node, request);
}
});
@@ -150,7 +150,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void delete(final DeleteIndexRequest request, final ActionListener<DeleteIndexResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Object>() {
- @Override public Object doWithNode(Node node) throws ElasticSearchException {
+ @Override public Object doWithNode(DiscoveryNode node) throws ElasticSearchException {
deleteIndexAction.execute(node, request, listener);
return null;
}
@@ -159,7 +159,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<RefreshResponse> refresh(final RefreshRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<RefreshResponse>>() {
- @Override public ActionFuture<RefreshResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<RefreshResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return refreshAction.execute(node, request);
}
});
@@ -167,7 +167,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void refresh(final RefreshRequest request, final ActionListener<RefreshResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
refreshAction.execute(node, request, listener);
return null;
}
@@ -176,7 +176,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<FlushResponse> flush(final FlushRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<FlushResponse>>() {
- @Override public ActionFuture<FlushResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<FlushResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return flushAction.execute(node, request);
}
});
@@ -184,7 +184,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void flush(final FlushRequest request, final ActionListener<FlushResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Object>() {
- @Override public Object doWithNode(Node node) throws ElasticSearchException {
+ @Override public Object doWithNode(DiscoveryNode node) throws ElasticSearchException {
flushAction.execute(node, request, listener);
return null;
}
@@ -193,7 +193,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<OptimizeResponse> optimize(final OptimizeRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<OptimizeResponse>>() {
- @Override public ActionFuture<OptimizeResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<OptimizeResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return optimizeAction.execute(node, request);
}
});
@@ -201,7 +201,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void optimize(final OptimizeRequest request, final ActionListener<OptimizeResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Void>>() {
- @Override public ActionFuture<Void> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<Void> doWithNode(DiscoveryNode node) throws ElasticSearchException {
optimizeAction.execute(node, request, listener);
return null;
}
@@ -210,7 +210,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<PutMappingResponse> putMapping(final PutMappingRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<PutMappingResponse>>() {
- @Override public ActionFuture<PutMappingResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<PutMappingResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return putMappingAction.execute(node, request);
}
});
@@ -218,7 +218,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void putMapping(final PutMappingRequest request, final ActionListener<PutMappingResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
putMappingAction.execute(node, request, listener);
return null;
}
@@ -227,7 +227,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<GatewaySnapshotResponse> gatewaySnapshot(final GatewaySnapshotRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<GatewaySnapshotResponse>>() {
- @Override public ActionFuture<GatewaySnapshotResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<GatewaySnapshotResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return gatewaySnapshotAction.execute(node, request);
}
});
@@ -235,7 +235,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void gatewaySnapshot(final GatewaySnapshotRequest request, final ActionListener<GatewaySnapshotResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Object>() {
- @Override public Object doWithNode(Node node) throws ElasticSearchException {
+ @Override public Object doWithNode(DiscoveryNode node) throws ElasticSearchException {
gatewaySnapshotAction.execute(node, request, listener);
return null;
}
@@ -244,7 +244,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<IndicesAliasesResponse> aliases(final IndicesAliasesRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<IndicesAliasesResponse>>() {
- @Override public ActionFuture<IndicesAliasesResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<IndicesAliasesResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return indicesAliasesAction.execute(node, request);
}
});
@@ -252,7 +252,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void aliases(final IndicesAliasesRequest request, final ActionListener<IndicesAliasesResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
indicesAliasesAction.execute(node, request, listener);
return null;
}
@@ -261,7 +261,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public ActionFuture<ClearIndicesCacheResponse> clearCache(final ClearIndicesCacheRequest request) {
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<ClearIndicesCacheResponse>>() {
- @Override public ActionFuture<ClearIndicesCacheResponse> doWithNode(Node node) throws ElasticSearchException {
+ @Override public ActionFuture<ClearIndicesCacheResponse> doWithNode(DiscoveryNode node) throws ElasticSearchException {
return clearIndicesCacheAction.execute(node, request);
}
});
@@ -269,7 +269,7 @@ public class InternalTransportIndicesAdminClient extends AbstractComponent imple
@Override public void clearCache(final ClearIndicesCacheRequest request, final ActionListener<ClearIndicesCacheResponse> listener) {
nodesService.execute(new TransportClientNodesService.NodeCallback<Void>() {
- @Override public Void doWithNode(Node node) throws ElasticSearchException {
+ @Override public Void doWithNode(DiscoveryNode node) throws ElasticSearchException {
clearIndicesCacheAction.execute(node, request, listener);
return null;
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterChangedEvent.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterChangedEvent.java
index 62b70fe9d2fd0..8f829cd758c74 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterChangedEvent.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterChangedEvent.java
@@ -19,7 +19,7 @@
package org.elasticsearch.cluster;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
/**
* @author kimchy (Shay Banon)
@@ -34,7 +34,7 @@ public class ClusterChangedEvent {
private final boolean firstMaster;
- private final Nodes.Delta nodesDelta;
+ private final DiscoveryNodes.Delta nodesDelta;
public ClusterChangedEvent(String source, ClusterState state, ClusterState previousState, boolean firstMaster) {
this.source = source;
@@ -75,7 +75,7 @@ public boolean firstMaster() {
return firstMaster;
}
- public Nodes.Delta nodesDelta() {
+ public DiscoveryNodes.Delta nodesDelta() {
return this.nodesDelta;
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterState.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterState.java
index 0b85e1bdc8c46..44232580a4592 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterState.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/ClusterState.java
@@ -20,8 +20,8 @@
package org.elasticsearch.cluster;
import org.elasticsearch.cluster.metadata.MetaData;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.util.Nullable;
@@ -42,14 +42,14 @@ public class ClusterState {
private final RoutingTable routingTable;
- private final Nodes nodes;
+ private final DiscoveryNodes nodes;
private final MetaData metaData;
// built on demand
private volatile RoutingNodes routingNodes;
- public ClusterState(long version, MetaData metaData, RoutingTable routingTable, Nodes nodes) {
+ public ClusterState(long version, MetaData metaData, RoutingTable routingTable, DiscoveryNodes nodes) {
this.version = version;
this.metaData = metaData;
this.routingTable = routingTable;
@@ -60,7 +60,7 @@ public long version() {
return this.version;
}
- public Nodes nodes() {
+ public DiscoveryNodes nodes() {
return this.nodes;
}
@@ -100,13 +100,13 @@ public static class Builder {
private RoutingTable routingTable = RoutingTable.EMPTY_ROUTING_TABLE;
- private Nodes nodes = Nodes.EMPTY_NODES;
+ private DiscoveryNodes nodes = DiscoveryNodes.EMPTY_NODES;
- public Builder nodes(Nodes.Builder nodesBuilder) {
+ public Builder nodes(DiscoveryNodes.Builder nodesBuilder) {
return nodes(nodesBuilder.build());
}
- public Builder nodes(Nodes nodes) {
+ public Builder nodes(DiscoveryNodes nodes) {
this.nodes = nodes;
return this;
}
@@ -147,7 +147,7 @@ public static byte[] toBytes(ClusterState state) throws IOException {
return os.copiedByteArray();
}
- public static ClusterState fromBytes(byte[] data, Settings globalSettings, Node localNode) throws IOException {
+ public static ClusterState fromBytes(byte[] data, Settings globalSettings, DiscoveryNode localNode) throws IOException {
return readFrom(new BytesStreamInput(data), globalSettings, localNode);
}
@@ -155,15 +155,15 @@ public static void writeTo(ClusterState state, StreamOutput out) throws IOExcept
out.writeLong(state.version());
MetaData.Builder.writeTo(state.metaData(), out);
RoutingTable.Builder.writeTo(state.routingTable(), out);
- Nodes.Builder.writeTo(state.nodes(), out);
+ DiscoveryNodes.Builder.writeTo(state.nodes(), out);
}
- public static ClusterState readFrom(StreamInput in, @Nullable Settings globalSettings, @Nullable Node localNode) throws IOException {
+ public static ClusterState readFrom(StreamInput in, @Nullable Settings globalSettings, @Nullable DiscoveryNode localNode) throws IOException {
Builder builder = new Builder();
builder.version = in.readLong();
builder.metaData = MetaData.Builder.readFrom(in, globalSettings);
builder.routingTable = RoutingTable.Builder.readFrom(in);
- builder.nodes = Nodes.Builder.readFrom(in, localNode);
+ builder.nodes = DiscoveryNodes.Builder.readFrom(in, localNode);
return builder.build();
}
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexCreatedAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexCreatedAction.java
index deb15e97a5155..e9affa656f13e 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexCreatedAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexCreatedAction.java
@@ -22,7 +22,7 @@
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.BaseTransportRequestHandler;
import org.elasticsearch.transport.TransportChannel;
@@ -69,7 +69,7 @@ public void remove(Listener listener) {
}
public void nodeIndexCreated(final String index, final String nodeId) throws ElasticSearchException {
- Nodes nodes = clusterService.state().nodes();
+ DiscoveryNodes nodes = clusterService.state().nodes();
if (nodes.localNodeMaster()) {
threadPool.execute(new Runnable() {
@Override public void run() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexDeletedAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexDeletedAction.java
index e6a1a686b9076..8df5b788f315e 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexDeletedAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeIndexDeletedAction.java
@@ -22,7 +22,7 @@
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.BaseTransportRequestHandler;
import org.elasticsearch.transport.TransportChannel;
@@ -69,7 +69,7 @@ public void remove(Listener listener) {
}
public void nodeIndexDeleted(final String index, final String nodeId) throws ElasticSearchException {
- Nodes nodes = clusterService.state().nodes();
+ DiscoveryNodes nodes = clusterService.state().nodes();
if (nodes.localNodeMaster()) {
threadPool.execute(new Runnable() {
@Override public void run() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeMappingCreatedAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeMappingCreatedAction.java
index 82c0618416df7..8cef1f8bfbf3d 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeMappingCreatedAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/index/NodeMappingCreatedAction.java
@@ -22,7 +22,7 @@
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.BaseTransportRequestHandler;
import org.elasticsearch.transport.TransportChannel;
@@ -69,7 +69,7 @@ public void remove(Listener listener) {
}
public void nodeMappingCreated(final NodeMappingCreatedResponse response) throws ElasticSearchException {
- Nodes nodes = clusterService.state().nodes();
+ DiscoveryNodes nodes = clusterService.state().nodes();
if (nodes.localNodeMaster()) {
threadPool.execute(new Runnable() {
@Override public void run() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
index be28fc628bb2f..cbd7fc78f734f 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
@@ -24,7 +24,7 @@
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
@@ -75,7 +75,7 @@ public class ShardStateAction extends AbstractComponent {
public void shardFailed(final ShardRouting shardRouting, final String reason) throws ElasticSearchException {
logger.warn("Sending failed shard for {}, reason [{}]", shardRouting, reason);
- Nodes nodes = clusterService.state().nodes();
+ DiscoveryNodes nodes = clusterService.state().nodes();
if (nodes.localNodeMaster()) {
threadPool.execute(new Runnable() {
@Override public void run() {
@@ -92,7 +92,7 @@ public void shardStarted(final ShardRouting shardRouting, final String reason) t
if (logger.isDebugEnabled()) {
logger.debug("Sending shard started for {}, reason [{}]", shardRouting, reason);
}
- Nodes nodes = clusterService.state().nodes();
+ DiscoveryNodes nodes = clusterService.state().nodes();
if (nodes.localNodeMaster()) {
threadPool.execute(new Runnable() {
@Override public void run() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/Node.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java
similarity index 86%
rename from modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/Node.java
rename to modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java
index 678ac34445c21..7a6f35380fe72 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/Node.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java
@@ -33,9 +33,9 @@
/**
* @author kimchy (Shay Banon)
*/
-public class Node implements Streamable, Serializable {
+public class DiscoveryNode implements Streamable, Serializable {
- public static final ImmutableList<Node> EMPTY_LIST = ImmutableList.of();
+ public static final ImmutableList<DiscoveryNode> EMPTY_LIST = ImmutableList.of();
private String nodeName = StringHelper.intern("");
@@ -45,14 +45,14 @@ public class Node implements Streamable, Serializable {
private boolean dataNode = true;
- private Node() {
+ private DiscoveryNode() {
}
- public Node(String nodeId, TransportAddress address) {
+ public DiscoveryNode(String nodeId, TransportAddress address) {
this("", true, nodeId, address);
}
- public Node(String nodeName, boolean dataNode, String nodeId, TransportAddress address) {
+ public DiscoveryNode(String nodeName, boolean dataNode, String nodeId, TransportAddress address) {
if (nodeName == null) {
this.nodeName = StringHelper.intern("");
} else {
@@ -91,8 +91,8 @@ public boolean dataNode() {
return dataNode;
}
- public static Node readNode(StreamInput in) throws IOException {
- Node node = new Node();
+ public static DiscoveryNode readNode(StreamInput in) throws IOException {
+ DiscoveryNode node = new DiscoveryNode();
node.readFrom(in);
return node;
}
@@ -112,10 +112,10 @@ public static Node readNode(StreamInput in) throws IOException {
}
@Override public boolean equals(Object obj) {
- if (!(obj instanceof Node))
+ if (!(obj instanceof DiscoveryNode))
return false;
- Node other = (Node) obj;
+ DiscoveryNode other = (DiscoveryNode) obj;
return this.nodeId.equals(other.nodeId);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/Nodes.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNodes.java
similarity index 73%
rename from modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/Nodes.java
rename to modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNodes.java
index 09e10599c673e..dea023aae1e0e 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/Nodes.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/node/DiscoveryNodes.java
@@ -37,26 +37,26 @@
/**
* @author kimchy (Shay Banon)
*/
-public class Nodes implements Iterable<Node> {
+public class DiscoveryNodes implements Iterable<DiscoveryNode> {
- public static Nodes EMPTY_NODES = newNodesBuilder().build();
+ public static DiscoveryNodes EMPTY_NODES = newNodesBuilder().build();
- private final ImmutableMap<String, Node> nodes;
+ private final ImmutableMap<String, DiscoveryNode> nodes;
- private final ImmutableMap<String, Node> dataNodes;
+ private final ImmutableMap<String, DiscoveryNode> dataNodes;
private final String masterNodeId;
private final String localNodeId;
- private Nodes(ImmutableMap<String, Node> nodes, ImmutableMap<String, Node> dataNodes, String masterNodeId, String localNodeId) {
+ private DiscoveryNodes(ImmutableMap<String, DiscoveryNode> nodes, ImmutableMap<String, DiscoveryNode> dataNodes, String masterNodeId, String localNodeId) {
this.nodes = nodes;
this.dataNodes = dataNodes;
this.masterNodeId = masterNodeId;
this.localNodeId = localNodeId;
}
- @Override public UnmodifiableIterator<Node> iterator() {
+ @Override public UnmodifiableIterator<DiscoveryNode> iterator() {
return nodes.values().iterator();
}
@@ -83,15 +83,15 @@ public int size() {
return nodes.size();
}
- public ImmutableMap<String, Node> nodes() {
+ public ImmutableMap<String, DiscoveryNode> nodes() {
return this.nodes;
}
- public ImmutableMap<String, Node> dataNodes() {
+ public ImmutableMap<String, DiscoveryNode> dataNodes() {
return this.dataNodes;
}
- public Node get(String nodeId) {
+ public DiscoveryNode get(String nodeId) {
return nodes.get(nodeId);
}
@@ -107,17 +107,17 @@ public String localNodeId() {
return this.localNodeId;
}
- public Node localNode() {
+ public DiscoveryNode localNode() {
return nodes.get(localNodeId);
}
- public Node masterNode() {
+ public DiscoveryNode masterNode() {
return nodes.get(masterNodeId);
}
- public Nodes removeDeadMembers(Set<String> newNodes, String masterNodeId) {
+ public DiscoveryNodes removeDeadMembers(Set<String> newNodes, String masterNodeId) {
Builder builder = new Builder().masterNodeId(masterNodeId).localNodeId(localNodeId);
- for (Node node : this) {
+ for (DiscoveryNode node : this) {
if (newNodes.contains(node.id())) {
builder.put(node);
}
@@ -125,28 +125,28 @@ public Nodes removeDeadMembers(Set<String> newNodes, String masterNodeId) {
return builder.build();
}
- public Nodes newNode(Node node) {
+ public DiscoveryNodes newNode(DiscoveryNode node) {
return new Builder().putAll(this).put(node).build();
}
/**
* Returns the changes comparing this nodes to the provided nodes.
*/
- public Delta delta(Nodes other) {
- List<Node> removed = newArrayList();
- List<Node> added = newArrayList();
- for (Node node : other) {
+ public Delta delta(DiscoveryNodes other) {
+ List<DiscoveryNode> removed = newArrayList();
+ List<DiscoveryNode> added = newArrayList();
+ for (DiscoveryNode node : other) {
if (!this.nodeExists(node.id())) {
removed.add(node);
}
}
- for (Node node : this) {
+ for (DiscoveryNode node : this) {
if (!other.nodeExists(node.id())) {
added.add(node);
}
}
- Node previousMasterNode = null;
- Node newMasterNode = null;
+ DiscoveryNode previousMasterNode = null;
+ DiscoveryNode newMasterNode = null;
if (masterNodeId != null) {
if (other.masterNodeId == null || !other.masterNodeId.equals(masterNodeId)) {
previousMasterNode = other.masterNode();
@@ -159,7 +159,7 @@ public Delta delta(Nodes other) {
public String prettyPrint() {
StringBuilder sb = new StringBuilder();
sb.append("Nodes: \n");
- for (Node node : this) {
+ for (DiscoveryNode node : this) {
sb.append(" ").append(node);
if (node == localNode()) {
sb.append(", local");
@@ -173,23 +173,23 @@ public String prettyPrint() {
}
public Delta emptyDelta() {
- return new Delta(null, null, localNodeId, Node.EMPTY_LIST, Node.EMPTY_LIST);
+ return new Delta(null, null, localNodeId, DiscoveryNode.EMPTY_LIST, DiscoveryNode.EMPTY_LIST);
}
public static class Delta {
private final String localNodeId;
- private final Node previousMasterNode;
- private final Node newMasterNode;
- private final ImmutableList<Node> removed;
- private final ImmutableList<Node> added;
+ private final DiscoveryNode previousMasterNode;
+ private final DiscoveryNode newMasterNode;
+ private final ImmutableList<DiscoveryNode> removed;
+ private final ImmutableList<DiscoveryNode> added;
- public Delta(String localNodeId, ImmutableList<Node> removed, ImmutableList<Node> added) {
+ public Delta(String localNodeId, ImmutableList<DiscoveryNode> removed, ImmutableList<DiscoveryNode> added) {
this(null, null, localNodeId, removed, added);
}
- public Delta(@Nullable Node previousMasterNode, @Nullable Node newMasterNode, String localNodeId, ImmutableList<Node> removed, ImmutableList<Node> added) {
+ public Delta(@Nullable DiscoveryNode previousMasterNode, @Nullable DiscoveryNode newMasterNode, String localNodeId, ImmutableList<DiscoveryNode> removed, ImmutableList<DiscoveryNode> added) {
this.previousMasterNode = previousMasterNode;
this.newMasterNode = newMasterNode;
this.localNodeId = localNodeId;
@@ -205,11 +205,11 @@ public boolean masterNodeChanged() {
return newMasterNode != null;
}
- public Node previousMasterNode() {
+ public DiscoveryNode previousMasterNode() {
return previousMasterNode;
}
- public Node newMasterNode() {
+ public DiscoveryNode newMasterNode() {
return newMasterNode;
}
@@ -217,7 +217,7 @@ public boolean removed() {
return !removed.isEmpty();
}
- public ImmutableList<Node> removedNodes() {
+ public ImmutableList<DiscoveryNode> removedNodes() {
return removed;
}
@@ -225,7 +225,7 @@ public boolean added() {
return !added.isEmpty();
}
- public ImmutableList<Node> addedNodes() {
+ public ImmutableList<DiscoveryNode> addedNodes() {
return added;
}
@@ -252,7 +252,7 @@ public String shortSummary() {
sb.append(", ");
}
sb.append("Removed {");
- for (Node node : removedNodes()) {
+ for (DiscoveryNode node : removedNodes()) {
sb.append(node).append(',');
}
sb.append("}");
@@ -265,7 +265,7 @@ public String shortSummary() {
sb.append(", ");
}
sb.append("Added {");
- for (Node node : addedNodes()) {
+ for (DiscoveryNode node : addedNodes()) {
if (!node.id().equals(localNodeId)) {
// don't print ourself
sb.append(node).append(',');
@@ -284,28 +284,28 @@ public static Builder newNodesBuilder() {
public static class Builder {
- private Map<String, Node> nodes = newHashMap();
+ private Map<String, DiscoveryNode> nodes = newHashMap();
private String masterNodeId;
private String localNodeId;
- public Builder putAll(Nodes nodes) {
+ public Builder putAll(DiscoveryNodes nodes) {
this.masterNodeId = nodes.masterNodeId();
this.localNodeId = nodes.localNodeId();
- for (Node node : nodes) {
+ for (DiscoveryNode node : nodes) {
put(node);
}
return this;
}
- public Builder put(Node node) {
+ public Builder put(DiscoveryNode node) {
nodes.put(node.id(), node);
return this;
}
- public Builder putAll(Iterable<Node> nodes) {
- for (Node node : nodes) {
+ public Builder putAll(Iterable<DiscoveryNode> nodes) {
+ for (DiscoveryNode node : nodes) {
put(node);
}
return this;
@@ -326,25 +326,25 @@ public Builder localNodeId(String localNodeId) {
return this;
}
- public Nodes build() {
- ImmutableMap.Builder<String, Node> dataNodesBuilder = ImmutableMap.builder();
- for (Map.Entry<String, Node> nodeEntry : nodes.entrySet()) {
+ public DiscoveryNodes build() {
+ ImmutableMap.Builder<String, DiscoveryNode> dataNodesBuilder = ImmutableMap.builder();
+ for (Map.Entry<String, DiscoveryNode> nodeEntry : nodes.entrySet()) {
if (nodeEntry.getValue().dataNode()) {
dataNodesBuilder.put(nodeEntry.getKey(), nodeEntry.getValue());
}
}
- return new Nodes(ImmutableMap.copyOf(nodes), dataNodesBuilder.build(), masterNodeId, localNodeId);
+ return new DiscoveryNodes(ImmutableMap.copyOf(nodes), dataNodesBuilder.build(), masterNodeId, localNodeId);
}
- public static void writeTo(Nodes nodes, StreamOutput out) throws IOException {
+ public static void writeTo(DiscoveryNodes nodes, StreamOutput out) throws IOException {
out.writeUTF(nodes.masterNodeId);
out.writeVInt(nodes.size());
- for (Node node : nodes) {
+ for (DiscoveryNode node : nodes) {
node.writeTo(out);
}
}
- public static Nodes readFrom(StreamInput in, @Nullable Node localNode) throws IOException {
+ public static DiscoveryNodes readFrom(StreamInput in, @Nullable DiscoveryNode localNode) throws IOException {
Builder builder = new Builder();
builder.masterNodeId(in.readUTF());
if (localNode != null) {
@@ -352,7 +352,7 @@ public static Nodes readFrom(StreamInput in, @Nullable Node localNode) throws IO
}
int size = in.readVInt();
for (int i = 0; i < size; i++) {
- Node node = Node.readNode(in);
+ DiscoveryNode node = DiscoveryNode.readNode(in);
if (localNode != null && node.id().equals(localNode.id())) {
// reuse the same instance of our address and local node id for faster equality
node = localNode;
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/routing/strategy/DefaultShardsRoutingStrategy.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/routing/strategy/DefaultShardsRoutingStrategy.java
index c22417421916a..6a7052a327681 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/routing/strategy/DefaultShardsRoutingStrategy.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/routing/strategy/DefaultShardsRoutingStrategy.java
@@ -20,7 +20,7 @@
package org.elasticsearch.cluster.routing.strategy;
import org.elasticsearch.cluster.ClusterState;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.*;
import java.util.Iterator;
@@ -54,7 +54,7 @@ public class DefaultShardsRoutingStrategy implements ShardsRoutingStrategy {
@Override public RoutingTable reroute(ClusterState clusterState) {
RoutingNodes routingNodes = clusterState.routingNodes();
- Iterable<Node> dataNodes = clusterState.nodes().dataNodes().values();
+ Iterable<DiscoveryNode> dataNodes = clusterState.nodes().dataNodes().values();
boolean changed = false;
// first, clear from the shards any node id they used to belong to that is now dead
@@ -212,8 +212,8 @@ private boolean allocateUnassigned(RoutingNodes routingNodes) {
*
* @param liveNodes currently live nodes.
*/
- private void applyNewNodes(RoutingNodes routingNodes, Iterable<Node> liveNodes) {
- for (Node node : liveNodes) {
+ private void applyNewNodes(RoutingNodes routingNodes, Iterable<DiscoveryNode> liveNodes) {
+ for (DiscoveryNode node : liveNodes) {
if (!routingNodes.nodesToShards().containsKey(node.id())) {
RoutingNode routingNode = new RoutingNode(node.id());
routingNodes.nodesToShards().put(node.id(), routingNode);
@@ -221,10 +221,10 @@ private void applyNewNodes(RoutingNodes routingNodes, Iterable<Node> liveNodes)
}
}
- private boolean deassociateDeadNodes(RoutingNodes routingNodes, Iterable<Node> liveNodes) {
+ private boolean deassociateDeadNodes(RoutingNodes routingNodes, Iterable<DiscoveryNode> liveNodes) {
boolean changed = false;
Set<String> liveNodeIds = newHashSet();
- for (Node liveNode : liveNodes) {
+ for (DiscoveryNode liveNode : liveNodes) {
liveNodeIds.add(liveNode.id());
}
Set<String> nodeIdsToRemove = newHashSet();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java
index f6c97ba5f76a1..5fb356c7a39f4 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java
@@ -22,7 +22,7 @@
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.*;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.discovery.DiscoveryService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
@@ -172,7 +172,7 @@ public void submitStateUpdateTask(final String source, final ClusterStateUpdateT
ClusterChangedEvent clusterChangedEvent = new ClusterChangedEvent(source, clusterState, previousClusterState, discoveryService.firstMaster());
// new cluster state, notify all listeners
- final Nodes.Delta nodesDelta = clusterChangedEvent.nodesDelta();
+ final DiscoveryNodes.Delta nodesDelta = clusterChangedEvent.nodesDelta();
if (nodesDelta.hasChanges() && logger.isInfoEnabled()) {
String summary = nodesDelta.shortSummary();
if (summary.length() > 0) {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java
index cb92631e77484..a4edcb21c4ae3 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/jgroups/JgroupsDiscovery.java
@@ -23,8 +23,8 @@
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchIllegalStateException;
import org.elasticsearch.cluster.*;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.DiscoveryException;
import org.elasticsearch.discovery.InitialStateDiscoveryListener;
@@ -70,7 +70,7 @@ public class JgroupsDiscovery extends AbstractLifecycleComponent<Discovery> impl
private volatile boolean addressSet = false;
- private Node localNode;
+ private DiscoveryNode localNode;
private volatile boolean firstMaster = false;
@@ -142,13 +142,13 @@ public class JgroupsDiscovery extends AbstractLifecycleComponent<Discovery> impl
channel.connect(clusterName.value());
channel.setReceiver(this);
logger.debug("Connected to cluster [{}], address [{}]", channel.getClusterName(), channel.getAddress());
- this.localNode = new Node(settings.get("name"), settings.getAsBoolean("node.data", true), channel.getAddress().toString(), transportService.boundAddress().publishAddress());
+ this.localNode = new DiscoveryNode(settings.get("name"), settings.getAsBoolean("node.data", true), channel.getAddress().toString(), transportService.boundAddress().publishAddress());
if (isMaster()) {
firstMaster = true;
clusterService.submitStateUpdateTask("jgroups-disco-initialconnect(master)", new ProcessedClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
- Nodes.Builder builder = new Nodes.Builder()
+ DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
.localNodeId(localNode.id())
.masterNodeId(localNode.id())
// put our local node
@@ -164,7 +164,7 @@ public class JgroupsDiscovery extends AbstractLifecycleComponent<Discovery> impl
} else {
clusterService.submitStateUpdateTask("jgroups-disco-initialconnect", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
- Nodes.Builder builder = new Nodes.Builder()
+ DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
.localNodeId(localNode.id())
.put(localNode);
return newClusterStateBuilder().state(currentState).nodes(builder).build();
@@ -248,7 +248,7 @@ public String nodeDescription() {
if (isMaster()) {
try {
BytesStreamInput is = new BytesStreamInput(msg.getBuffer());
- final Node newNode = Node.readNode(is);
+ final DiscoveryNode newNode = DiscoveryNode.readNode(is);
is.close();
if (logger.isDebugEnabled()) {
@@ -310,8 +310,8 @@ private boolean isMaster() {
clusterService.submitStateUpdateTask("jgroups-disco-view", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
- Nodes newNodes = currentState.nodes().removeDeadMembers(newMembers, newView.getCreator().toString());
- Nodes.Delta delta = newNodes.delta(currentState.nodes());
+ DiscoveryNodes newNodes = currentState.nodes().removeDeadMembers(newMembers, newView.getCreator().toString());
+ DiscoveryNodes.Delta delta = newNodes.delta(currentState.nodes());
if (delta.added()) {
logger.warn("No new nodes should be created when a new discovery view is accepted");
}
@@ -328,7 +328,7 @@ private boolean isMaster() {
// check whether I have been removed due to temporary disconnect
final String me = channel.getAddress().toString();
boolean foundMe = false;
- for (Node node : clusterService.state().nodes()) {
+ for (DiscoveryNode node : clusterService.state().nodes()) {
if (node.id().equals(me)) {
foundMe = true;
break;
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java
index 045c78aabd66c..a04105975a045 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java
@@ -23,8 +23,8 @@
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchIllegalStateException;
import org.elasticsearch.cluster.*;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.InitialStateDiscoveryListener;
import org.elasticsearch.transport.TransportService;
@@ -54,7 +54,7 @@ public class LocalDiscovery extends AbstractLifecycleComponent<Discovery> implem
private final ClusterName clusterName;
- private Node localNode;
+ private DiscoveryNode localNode;
private volatile boolean master = false;
@@ -84,7 +84,7 @@ public class LocalDiscovery extends AbstractLifecycleComponent<Discovery> implem
clusterGroups.put(clusterName, clusterGroup);
}
logger.debug("Connected to cluster [{}]", clusterName);
- this.localNode = new Node(settings.get("name"), settings.getAsBoolean("node.data", true), Long.toString(nodeIdGenerator.incrementAndGet()), transportService.boundAddress().publishAddress());
+ this.localNode = new DiscoveryNode(settings.get("name"), settings.getAsBoolean("node.data", true), Long.toString(nodeIdGenerator.incrementAndGet()), transportService.boundAddress().publishAddress());
clusterGroup.members().add(this);
if (clusterGroup.members().size() == 1) {
@@ -93,7 +93,7 @@ public class LocalDiscovery extends AbstractLifecycleComponent<Discovery> implem
firstMaster = true;
clusterService.submitStateUpdateTask("local-disco-initialconnect(master)", new ProcessedClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
- Nodes.Builder builder = new Nodes.Builder()
+ DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
.localNodeId(localNode.id())
.masterNodeId(localNode.id())
// put our local node
@@ -153,8 +153,8 @@ public class LocalDiscovery extends AbstractLifecycleComponent<Discovery> implem
masterDiscovery.clusterService.submitStateUpdateTask("local-disco-update", new ClusterStateUpdateTask() {
@Override public ClusterState execute(ClusterState currentState) {
- Nodes newNodes = currentState.nodes().removeDeadMembers(newMembers, masterDiscovery.localNode.id());
- Nodes.Delta delta = newNodes.delta(currentState.nodes());
+ DiscoveryNodes newNodes = currentState.nodes().removeDeadMembers(newMembers, masterDiscovery.localNode.id());
+ DiscoveryNodes.Delta delta = newNodes.delta(currentState.nodes());
if (delta.added()) {
logger.warn("No new nodes should be created when a new discovery view is accepted");
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryAction.java
index 04d8009a8c12d..825b738321e19 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryAction.java
@@ -25,7 +25,7 @@
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchInterruptedException;
import org.elasticsearch.ExceptionsHelper;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.index.deletionpolicy.SnapshotIndexCommit;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.RecoveryEngineException;
@@ -135,7 +135,7 @@ public void close() {
}
}
- public synchronized void startRecovery(Node node, Node targetNode, boolean markAsRelocated) throws ElasticSearchException {
+ public synchronized void startRecovery(DiscoveryNode node, DiscoveryNode targetNode, boolean markAsRelocated) throws ElasticSearchException {
sendStartRecoveryThread = Thread.currentThread();
try {
// mark the shard as recovering
@@ -224,20 +224,20 @@ private void cleanOpenIndex() {
private static class StartRecoveryRequest implements Streamable {
- private Node node;
+ private DiscoveryNode node;
private boolean markAsRelocated;
private StartRecoveryRequest() {
}
- private StartRecoveryRequest(Node node, boolean markAsRelocated) {
+ private StartRecoveryRequest(DiscoveryNode node, boolean markAsRelocated) {
this.node = node;
this.markAsRelocated = markAsRelocated;
}
@Override public void readFrom(StreamInput in) throws IOException {
- node = Node.readNode(in);
+ node = DiscoveryNode.readNode(in);
markAsRelocated = in.readBoolean();
}
@@ -255,7 +255,7 @@ private class StartRecoveryTransportRequestHandler extends BaseTransportRequestH
@Override public void messageReceived(final StartRecoveryRequest startRecoveryRequest, final TransportChannel channel) throws Exception {
logger.trace("Starting recovery to {}, markAsRelocated {}", startRecoveryRequest.node, startRecoveryRequest.markAsRelocated);
- final Node node = startRecoveryRequest.node;
+ final DiscoveryNode node = startRecoveryRequest.node;
cleanOpenIndex();
final RecoveryStatus recoveryStatus = new RecoveryStatus();
indexShard.recover(new Engine.RecoveryHandler() {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFailedException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFailedException.java
index 71c38e34c4722..3ce9bea28f1dc 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFailedException.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryFailedException.java
@@ -20,7 +20,7 @@
package org.elasticsearch.index.shard.recovery;
import org.elasticsearch.ElasticSearchException;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.index.shard.ShardId;
/**
@@ -28,7 +28,7 @@
*/
public class RecoveryFailedException extends ElasticSearchException {
- public RecoveryFailedException(ShardId shardId, Node node, Node targetNode, Throwable cause) {
+ public RecoveryFailedException(ShardId shardId, DiscoveryNode node, DiscoveryNode targetNode, Throwable cause) {
super(shardId + ": Recovery failed from " + targetNode + " into " + node, cause);
}
}
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 537bcc814c5f7..60aeec46d69c1 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
@@ -30,8 +30,8 @@
import org.elasticsearch.cluster.action.index.NodeMappingCreatedAction;
import org.elasticsearch.cluster.action.shard.ShardStateAction;
import org.elasticsearch.cluster.metadata.IndexMetaData;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingTable;
@@ -228,7 +228,7 @@ private void applyNewShards(final ClusterChangedEvent event) throws ElasticSearc
if (routingNodes == null) {
return;
}
- Nodes nodes = event.state().nodes();
+ DiscoveryNodes nodes = event.state().nodes();
for (final ShardRouting shardRouting : routingNodes) {
@@ -257,7 +257,7 @@ private void applyNewShards(final ClusterChangedEvent event) throws ElasticSearc
}
}
- private void applyInitializingShard(final RoutingTable routingTable, final Nodes nodes, final ShardRouting shardRouting) throws ElasticSearchException {
+ private void applyInitializingShard(final RoutingTable routingTable, final DiscoveryNodes nodes, final ShardRouting shardRouting) throws ElasticSearchException {
final IndexService indexService = indicesService.indexServiceSafe(shardRouting.index());
final int shardId = shardRouting.id();
@@ -322,7 +322,7 @@ private void applyInitializingShard(final RoutingTable routingTable, final Nodes
for (ShardRouting entry : shardRoutingTable) {
if (entry.primary() && entry.started()) {
// only recover from started primary, if we can't find one, we will do it next round
- Node node = nodes.get(entry.currentNodeId());
+ DiscoveryNode node = nodes.get(entry.currentNodeId());
try {
// we are recovering a backup from a primary, so no need to mark it as relocated
recoveryAction.startRecovery(nodes.localNode(), node, false);
@@ -346,7 +346,7 @@ private void applyInitializingShard(final RoutingTable routingTable, final Nodes
}
} else {
// relocating primaries, recovery from the relocating shard
- Node node = nodes.get(shardRouting.relocatingNodeId());
+ DiscoveryNode node = nodes.get(shardRouting.relocatingNodeId());
try {
// we mark the primary we are going to recover from as relocated at the end of phase 3
// so operations will start moving to the new primary
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/JmxClusterService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/JmxClusterService.java
index 936b60b7b8f89..37ee3725a5316 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/JmxClusterService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/JmxClusterService.java
@@ -22,7 +22,7 @@
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterStateListener;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.jmx.action.GetJmxServiceUrlAction;
import org.elasticsearch.util.component.AbstractComponent;
import org.elasticsearch.util.settings.Settings;
@@ -60,7 +60,7 @@ public JmxClusterService(Settings settings, ClusterService clusterService, JmxSe
if (jmxService.publishUrl() != null) {
clusterService.add(new JmxClusterEventListener());
- for (final Node node : clusterService.state().nodes()) {
+ for (final DiscoveryNode node : clusterService.state().nodes()) {
clusterNodesJmxUpdater.execute(new Runnable() {
@Override public void run() {
String nodeServiceUrl = getJmxServiceUrlAction.obtainPublishUrl(node);
@@ -77,7 +77,7 @@ public void close() {
}
}
- private void registerNode(Node node, String nodeServiceUrl) {
+ private void registerNode(DiscoveryNode node, String nodeServiceUrl) {
try {
JMXServiceURL jmxServiceURL = new JMXServiceURL(nodeServiceUrl);
JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL, null);
@@ -103,7 +103,7 @@ private class JmxClusterEventListener implements ClusterStateListener {
if (!event.nodesChanged()) {
return;
}
- for (final Node node : event.nodesDelta().addedNodes()) {
+ for (final DiscoveryNode node : event.nodesDelta().addedNodes()) {
clusterNodesJmxUpdater.execute(new Runnable() {
@Override public void run() {
String nodeServiceUrl = getJmxServiceUrlAction.obtainPublishUrl(node);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/action/GetJmxServiceUrlAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/action/GetJmxServiceUrlAction.java
index 15d60e413b0c1..62f5e172f860d 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/action/GetJmxServiceUrlAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/jmx/action/GetJmxServiceUrlAction.java
@@ -22,7 +22,7 @@
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.jmx.JmxService;
import org.elasticsearch.transport.BaseTransportRequestHandler;
import org.elasticsearch.transport.FutureTransportResponseHandler;
@@ -54,7 +54,7 @@ public class GetJmxServiceUrlAction extends AbstractComponent {
transportService.registerHandler(GetJmxServiceUrlTransportHandler.ACTION, new GetJmxServiceUrlTransportHandler());
}
- public String obtainPublishUrl(final Node node) throws ElasticSearchException {
+ public String obtainPublishUrl(final DiscoveryNode node) throws ElasticSearchException {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
return jmxService.publishUrl();
} else {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/monitor/dump/SimpleDumpGenerator.java b/modules/elasticsearch/src/main/java/org/elasticsearch/monitor/dump/SimpleDumpGenerator.java
index af97d7389b564..2c148c2a27dfb 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/monitor/dump/SimpleDumpGenerator.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/monitor/dump/SimpleDumpGenerator.java
@@ -20,7 +20,7 @@
package org.elasticsearch.monitor.dump;
import com.google.common.collect.ImmutableMap;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.util.Nullable;
import java.io.File;
@@ -50,7 +50,7 @@ public Result generateDump(String cause, @Nullable Map<String, Object> context,
long timestamp = System.currentTimeMillis();
String fileName = "";
if (context.containsKey("localNode")) {
- Node localNode = (Node) context.get("localNode");
+ DiscoveryNode localNode = (DiscoveryNode) context.get("localNode");
if (localNode.name() != null) {
fileName += localNode.name() + "-";
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/monitor/dump/cluster/ClusterDumpContributor.java b/modules/elasticsearch/src/main/java/org/elasticsearch/monitor/dump/cluster/ClusterDumpContributor.java
index 4f1e22ffbe0c4..1335ada63ee72 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/monitor/dump/cluster/ClusterDumpContributor.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/monitor/dump/cluster/ClusterDumpContributor.java
@@ -23,7 +23,7 @@
import com.google.inject.assistedinject.Assisted;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.monitor.dump.Dump;
import org.elasticsearch.monitor.dump.DumpContributionFailedException;
@@ -54,7 +54,7 @@ public class ClusterDumpContributor implements DumpContributor {
@Override public void contribute(Dump dump) throws DumpContributionFailedException {
ClusterState clusterState = clusterService.state();
- Nodes nodes = clusterState.nodes();
+ DiscoveryNodes nodes = clusterState.nodes();
RoutingTable routingTable = clusterState.routingTable();
PrintWriter writer = new PrintWriter(dump.createFileWriter("cluster.txt"));
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java
index 5d869050ba443..466b642c35a69 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java
@@ -21,7 +21,7 @@
import com.google.inject.Inject;
import org.elasticsearch.cluster.ClusterService;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.search.SearchService;
import org.elasticsearch.search.dfs.DfsSearchResult;
import org.elasticsearch.search.fetch.FetchSearchRequest;
@@ -65,7 +65,7 @@ public class SearchServiceTransportAction {
transportService.registerHandler(SearchFetchByIdTransportHandler.ACTION, new SearchFetchByIdTransportHandler());
}
- public void sendFreeContext(Node node, final long contextId) {
+ public void sendFreeContext(DiscoveryNode node, final long contextId) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
searchService.freeContext(contextId);
} else {
@@ -73,7 +73,7 @@ public void sendFreeContext(Node node, final long contextId) {
}
}
- public void sendExecuteDfs(Node node, final InternalSearchRequest request, final SearchServiceListener<DfsSearchResult> listener) {
+ public void sendExecuteDfs(DiscoveryNode node, final InternalSearchRequest request, final SearchServiceListener<DfsSearchResult> listener) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
try {
DfsSearchResult result = searchService.executeDfsPhase(request);
@@ -103,7 +103,7 @@ public void sendExecuteDfs(Node node, final InternalSearchRequest request, final
}
}
- public void sendExecuteQuery(Node node, final InternalSearchRequest request, final SearchServiceListener<QuerySearchResult> listener) {
+ public void sendExecuteQuery(DiscoveryNode node, final InternalSearchRequest request, final SearchServiceListener<QuerySearchResult> listener) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
try {
QuerySearchResult result = searchService.executeQueryPhase(request);
@@ -133,7 +133,7 @@ public void sendExecuteQuery(Node node, final InternalSearchRequest request, fin
}
}
- public void sendExecuteQuery(Node node, final QuerySearchRequest request, final SearchServiceListener<QuerySearchResult> listener) {
+ public void sendExecuteQuery(DiscoveryNode node, final QuerySearchRequest request, final SearchServiceListener<QuerySearchResult> listener) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
try {
QuerySearchResult result = searchService.executeQueryPhase(request);
@@ -163,7 +163,7 @@ public void sendExecuteQuery(Node node, final QuerySearchRequest request, final
}
}
- public void sendExecuteQuery(Node node, final InternalScrollSearchRequest request, final SearchServiceListener<QuerySearchResult> listener) {
+ public void sendExecuteQuery(DiscoveryNode node, final InternalScrollSearchRequest request, final SearchServiceListener<QuerySearchResult> listener) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
try {
QuerySearchResult result = searchService.executeQueryPhase(request);
@@ -193,7 +193,7 @@ public void sendExecuteQuery(Node node, final InternalScrollSearchRequest reques
}
}
- public void sendExecuteFetch(Node node, final InternalSearchRequest request, final SearchServiceListener<QueryFetchSearchResult> listener) {
+ public void sendExecuteFetch(DiscoveryNode node, final InternalSearchRequest request, final SearchServiceListener<QueryFetchSearchResult> listener) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
try {
QueryFetchSearchResult result = searchService.executeFetchPhase(request);
@@ -223,7 +223,7 @@ public void sendExecuteFetch(Node node, final InternalSearchRequest request, fin
}
}
- public void sendExecuteFetch(Node node, final QuerySearchRequest request, final SearchServiceListener<QueryFetchSearchResult> listener) {
+ public void sendExecuteFetch(DiscoveryNode node, final QuerySearchRequest request, final SearchServiceListener<QueryFetchSearchResult> listener) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
try {
QueryFetchSearchResult result = searchService.executeFetchPhase(request);
@@ -253,7 +253,7 @@ public void sendExecuteFetch(Node node, final QuerySearchRequest request, final
}
}
- public void sendExecuteFetch(Node node, final InternalScrollSearchRequest request, final SearchServiceListener<QueryFetchSearchResult> listener) {
+ public void sendExecuteFetch(DiscoveryNode node, final InternalScrollSearchRequest request, final SearchServiceListener<QueryFetchSearchResult> listener) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
try {
QueryFetchSearchResult result = searchService.executeFetchPhase(request);
@@ -283,7 +283,7 @@ public void sendExecuteFetch(Node node, final InternalScrollSearchRequest reques
}
}
- public void sendExecuteFetch(Node node, final FetchSearchRequest request, final SearchServiceListener<FetchSearchResult> listener) {
+ public void sendExecuteFetch(DiscoveryNode node, final FetchSearchRequest request, final SearchServiceListener<FetchSearchResult> listener) {
if (clusterService.state().nodes().localNodeId().equals(node.id())) {
try {
FetchSearchResult result = searchService.executeFetchPhase(request);
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ConnectTransportException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ConnectTransportException.java
index 05a661db4294c..6b0abb69ec676 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ConnectTransportException.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/ConnectTransportException.java
@@ -19,25 +19,25 @@
package org.elasticsearch.transport;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
/**
* @author kimchy (Shay Banon)
*/
public class ConnectTransportException extends TransportException {
- private final Node node;
+ private final DiscoveryNode node;
- public ConnectTransportException(Node node, String msg) {
+ public ConnectTransportException(DiscoveryNode node, String msg) {
this(node, msg, null);
}
- public ConnectTransportException(Node node, String msg, Throwable cause) {
+ public ConnectTransportException(DiscoveryNode node, String msg, Throwable cause) {
super(node + ": " + msg, cause);
this.node = node;
}
- public Node node() {
+ public DiscoveryNode node() {
return node;
}
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/SendRequestTransportException.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/SendRequestTransportException.java
index 5d2c219ca1720..4159ea4dd264f 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/SendRequestTransportException.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/SendRequestTransportException.java
@@ -19,14 +19,14 @@
package org.elasticsearch.transport;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
/**
* @author kimchy (shay.banon)
*/
public class SendRequestTransportException extends RemoteTransportException {
- public SendRequestTransportException(Node node, String action, Throwable cause) {
+ public SendRequestTransportException(DiscoveryNode node, String action, Throwable cause) {
super(node.name(), node.address(), action, cause);
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/Transport.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/Transport.java
index 272a7ec695d1e..bf1a4e65615be 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/Transport.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/Transport.java
@@ -19,7 +19,7 @@
package org.elasticsearch.transport;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.util.component.LifecycleComponent;
import org.elasticsearch.util.io.stream.Streamable;
import org.elasticsearch.util.transport.BoundTransportAddress;
@@ -70,10 +70,10 @@ public static byte setError(byte value) {
*/
boolean addressSupported(Class<? extends TransportAddress> address);
- void nodesAdded(Iterable<Node> nodes);
+ void nodesAdded(Iterable<DiscoveryNode> nodes);
- void nodesRemoved(Iterable<Node> nodes);
+ void nodesRemoved(Iterable<DiscoveryNode> nodes);
- <T extends Streamable> void sendRequest(Node node, long requestId, String action,
+ <T extends Streamable> void sendRequest(DiscoveryNode node, long requestId, String action,
Streamable message, TransportResponseHandler<T> handler) throws IOException, TransportException;
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportService.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportService.java
index 88ec72ae6548d..8fce3ea72783a 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportService.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/TransportService.java
@@ -21,7 +21,7 @@
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.util.component.AbstractLifecycleComponent;
import org.elasticsearch.util.concurrent.highscalelib.NonBlockingHashMapLong;
@@ -96,7 +96,7 @@ public BoundTransportAddress boundAddress() {
return transport.boundAddress();
}
- public void nodesAdded(Iterable<Node> nodes) {
+ public void nodesAdded(Iterable<DiscoveryNode> nodes) {
try {
transport.nodesAdded(nodes);
} catch (Exception e) {
@@ -104,7 +104,7 @@ public void nodesAdded(Iterable<Node> nodes) {
}
}
- public void nodesRemoved(Iterable<Node> nodes) {
+ public void nodesRemoved(Iterable<DiscoveryNode> nodes) {
try {
transport.nodesRemoved(nodes);
} catch (Exception e) {
@@ -123,14 +123,14 @@ public void throwConnectException(boolean throwConnectException) {
this.throwConnectException = throwConnectException;
}
- public <T extends Streamable> TransportFuture<T> submitRequest(Node node, String action, Streamable message,
+ public <T extends Streamable> TransportFuture<T> submitRequest(DiscoveryNode node, String action, Streamable message,
TransportResponseHandler<T> handler) throws TransportException {
PlainTransportFuture<T> futureHandler = new PlainTransportFuture<T>(handler);
sendRequest(node, action, message, futureHandler);
return futureHandler;
}
- public <T extends Streamable> void sendRequest(final Node node, final String action, final Streamable message,
+ public <T extends Streamable> void sendRequest(final DiscoveryNode node, final String action, final Streamable message,
final TransportResponseHandler<T> handler) throws TransportException {
final long requestId = newRequestId();
try {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/local/LocalTransport.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/local/LocalTransport.java
index 7f3ed39437367..31a9e41c1d209 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/local/LocalTransport.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/local/LocalTransport.java
@@ -21,7 +21,7 @@
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import org.elasticsearch.util.Nullable;
@@ -92,13 +92,13 @@ public LocalTransport(ThreadPool threadPool) {
return boundAddress;
}
- @Override public void nodesAdded(Iterable<Node> nodes) {
+ @Override public void nodesAdded(Iterable<DiscoveryNode> nodes) {
}
- @Override public void nodesRemoved(Iterable<Node> nodes) {
+ @Override public void nodesRemoved(Iterable<DiscoveryNode> nodes) {
}
- @Override public <T extends Streamable> void sendRequest(final Node node, final long requestId, final String action,
+ @Override public <T extends Streamable> void sendRequest(final DiscoveryNode node, final long requestId, final String action,
final Streamable message, final TransportResponseHandler<T> handler) throws IOException, TransportException {
HandlesStreamOutput stream = BytesStreamOutput.Cached.cachedHandles();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java
index 03820ff645e23..f11bcfbe9d805 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java
@@ -23,7 +23,7 @@
import com.google.inject.Inject;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchIllegalStateException;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import org.elasticsearch.util.SizeValue;
@@ -355,7 +355,7 @@ TransportAddress wrapAddress(SocketAddress socketAddress) {
private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
- @Override public <T extends Streamable> void sendRequest(Node node, long requestId, String action,
+ @Override public <T extends Streamable> void sendRequest(DiscoveryNode node, long requestId, String action,
Streamable streamable, final TransportResponseHandler<T> handler) throws IOException, TransportException {
Channel targetChannel = nodeChannel(node);
@@ -391,11 +391,11 @@ TransportAddress wrapAddress(SocketAddress socketAddress) {
// });
}
- @Override public void nodesAdded(Iterable<Node> nodes) {
+ @Override public void nodesAdded(Iterable<DiscoveryNode> nodes) {
if (!lifecycle.started()) {
throw new ElasticSearchIllegalStateException("Can't add nodes to a stopped transport");
}
- for (Node node : nodes) {
+ for (DiscoveryNode node : nodes) {
try {
nodeChannel(node);
} catch (Exception e) {
@@ -404,8 +404,8 @@ TransportAddress wrapAddress(SocketAddress socketAddress) {
}
}
- @Override public void nodesRemoved(Iterable<Node> nodes) {
- for (Node node : nodes) {
+ @Override public void nodesRemoved(Iterable<DiscoveryNode> nodes) {
+ for (DiscoveryNode node : nodes) {
NodeConnections nodeConnections = clientChannels.remove(node.id());
if (nodeConnections != null) {
nodeConnections.close();
@@ -413,7 +413,7 @@ TransportAddress wrapAddress(SocketAddress socketAddress) {
}
}
- private Channel nodeChannel(Node node) throws ConnectTransportException {
+ private Channel nodeChannel(DiscoveryNode node) throws ConnectTransportException {
if (node == null) {
throw new ConnectTransportException(node, "Can't connect to a null node");
}
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/SingleShardNoBackupsRoutingStrategyTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/SingleShardNoBackupsRoutingStrategyTests.java
index 62db40f7cf4cb..bae7350ea7bb5 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/SingleShardNoBackupsRoutingStrategyTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/SingleShardNoBackupsRoutingStrategyTests.java
@@ -21,8 +21,8 @@
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.MetaData;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.MutableShardRouting;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
@@ -40,7 +40,7 @@
import static org.elasticsearch.cluster.ClusterState.*;
import static org.elasticsearch.cluster.metadata.IndexMetaData.*;
import static org.elasticsearch.cluster.metadata.MetaData.*;
-import static org.elasticsearch.cluster.node.Nodes.*;
+import static org.elasticsearch.cluster.node.DiscoveryNodes.*;
import static org.elasticsearch.cluster.routing.RoutingBuilders.*;
import static org.elasticsearch.cluster.routing.ShardRoutingState.*;
import static org.hamcrest.MatcherAssert.*;
@@ -231,8 +231,8 @@ public class SingleShardNoBackupsRoutingStrategyTests {
}
logger.info("Adding " + (numberOfIndices / 2) + " nodes");
- Nodes.Builder nodesBuilder = newNodesBuilder();
- List<Node> nodes = newArrayList();
+ DiscoveryNodes.Builder nodesBuilder = newNodesBuilder();
+ List<DiscoveryNode> nodes = newArrayList();
for (int i = 0; i < (numberOfIndices / 2); i++) {
nodesBuilder.put(newNode("node" + i));
}
@@ -436,7 +436,7 @@ public class SingleShardNoBackupsRoutingStrategyTests {
}
}
- private Node newNode(String nodeId) {
- return new Node(nodeId, DummyTransportAddress.INSTANCE);
+ private DiscoveryNode newNode(String nodeId) {
+ return new DiscoveryNode(nodeId, DummyTransportAddress.INSTANCE);
}
}
\ No newline at end of file
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/SingleShardOneBackupRoutingStrategyTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/SingleShardOneBackupRoutingStrategyTests.java
index 24bc9e03399f5..5a804f9355a55 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/SingleShardOneBackupRoutingStrategyTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/SingleShardOneBackupRoutingStrategyTests.java
@@ -21,7 +21,7 @@
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.MetaData;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.util.logging.Loggers;
@@ -32,7 +32,7 @@
import static org.elasticsearch.cluster.ClusterState.*;
import static org.elasticsearch.cluster.metadata.IndexMetaData.*;
import static org.elasticsearch.cluster.metadata.MetaData.*;
-import static org.elasticsearch.cluster.node.Nodes.*;
+import static org.elasticsearch.cluster.node.DiscoveryNodes.*;
import static org.elasticsearch.cluster.routing.RoutingBuilders.*;
import static org.elasticsearch.cluster.routing.ShardRoutingState.*;
import static org.hamcrest.MatcherAssert.*;
@@ -178,7 +178,7 @@ public class SingleShardOneBackupRoutingStrategyTests {
assertThat(routingTable.index("test").shard(0).backupsShards().get(0).currentNodeId(), equalTo("node3"));
}
- private Node newNode(String nodeId) {
- return new Node(nodeId, DummyTransportAddress.INSTANCE);
+ private DiscoveryNode newNode(String nodeId) {
+ return new DiscoveryNode(nodeId, DummyTransportAddress.INSTANCE);
}
}
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/TenShardsOneBackupRoutingTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/TenShardsOneBackupRoutingTests.java
index b7abd607b93ff..0f374ec72211c 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/TenShardsOneBackupRoutingTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/routing/strategy/TenShardsOneBackupRoutingTests.java
@@ -21,7 +21,7 @@
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.MetaData;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.util.logging.Loggers;
@@ -32,7 +32,7 @@
import static org.elasticsearch.cluster.ClusterState.*;
import static org.elasticsearch.cluster.metadata.IndexMetaData.*;
import static org.elasticsearch.cluster.metadata.MetaData.*;
-import static org.elasticsearch.cluster.node.Nodes.*;
+import static org.elasticsearch.cluster.node.DiscoveryNodes.*;
import static org.elasticsearch.cluster.routing.RoutingBuilders.*;
import static org.elasticsearch.cluster.routing.ShardRoutingState.*;
import static org.hamcrest.MatcherAssert.*;
@@ -182,7 +182,7 @@ public class TenShardsOneBackupRoutingTests {
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(6));
}
- private Node newNode(String nodeId) {
- return new Node(nodeId, DummyTransportAddress.INSTANCE);
+ private DiscoveryNode newNode(String nodeId) {
+ return new DiscoveryNode(nodeId, DummyTransportAddress.INSTANCE);
}
}
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
index b360935cbaf74..b245dcb0b90a4 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
@@ -21,8 +21,8 @@
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.MetaData;
-import org.elasticsearch.cluster.node.Node;
-import org.elasticsearch.cluster.node.Nodes;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.strategy.DefaultShardsRoutingStrategy;
import org.elasticsearch.util.io.stream.BytesStreamInput;
@@ -52,7 +52,7 @@ public class ClusterSerializationTests {
.add(indexRoutingTable("test").initializeEmpty(metaData.index("test")))
.build();
- Nodes nodes = Nodes.newNodesBuilder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3")).localNodeId("node1").masterNodeId("node2").build();
+ DiscoveryNodes nodes = DiscoveryNodes.newNodesBuilder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3")).localNodeId("node1").masterNodeId("node2").build();
ClusterState clusterState = newClusterStateBuilder().nodes(nodes).metaData(metaData).routingTable(routingTable).build();
@@ -74,7 +74,7 @@ public class ClusterSerializationTests {
.add(indexRoutingTable("test").initializeEmpty(metaData.index("test")))
.build();
- Nodes nodes = Nodes.newNodesBuilder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3")).build();
+ DiscoveryNodes nodes = DiscoveryNodes.newNodesBuilder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3")).build();
ClusterState clusterState = newClusterStateBuilder().nodes(nodes).metaData(metaData).routingTable(routingTable).build();
@@ -89,7 +89,7 @@ public class ClusterSerializationTests {
assertThat(target.prettyPrint(), equalTo(source.prettyPrint()));
}
- private Node newNode(String nodeId) {
- return new Node(nodeId, DummyTransportAddress.INSTANCE);
+ private DiscoveryNode newNode(String nodeId) {
+ return new DiscoveryNode(nodeId, DummyTransportAddress.INSTANCE);
}
}
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/local/SimpleLocalTransportTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/local/SimpleLocalTransportTests.java
index 8d8bc34b32a87..79e36daaf3ee0 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/local/SimpleLocalTransportTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/local/SimpleLocalTransportTests.java
@@ -19,7 +19,7 @@
package org.elasticsearch.transport.local;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.scaling.ScalingThreadPool;
import org.elasticsearch.transport.*;
@@ -41,17 +41,17 @@ public class SimpleLocalTransportTests {
private TransportService serviceA;
private TransportService serviceB;
- private Node serviceANode;
- private Node serviceBNode;
+ private DiscoveryNode serviceANode;
+ private DiscoveryNode serviceBNode;
@BeforeClass public void setUp() {
threadPool = new ScalingThreadPool();
serviceA = new TransportService(new LocalTransport(threadPool), threadPool).start();
- serviceANode = new Node("A", serviceA.boundAddress().publishAddress());
+ serviceANode = new DiscoveryNode("A", serviceA.boundAddress().publishAddress());
serviceB = new TransportService(new LocalTransport(threadPool), threadPool).start();
- serviceBNode = new Node("B", serviceB.boundAddress().publishAddress());
+ serviceBNode = new DiscoveryNode("B", serviceB.boundAddress().publishAddress());
}
@AfterClass public void tearDown() {
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/SimpleNettyTransportTests.java b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/SimpleNettyTransportTests.java
index f238cc6c89147..c004b914165d8 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/SimpleNettyTransportTests.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/SimpleNettyTransportTests.java
@@ -19,7 +19,7 @@
package org.elasticsearch.transport.netty;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.scaling.ScalingThreadPool;
import org.elasticsearch.transport.*;
@@ -41,17 +41,17 @@ public class SimpleNettyTransportTests {
private TransportService serviceA;
private TransportService serviceB;
- private Node serviceANode;
- private Node serviceBNode;
+ private DiscoveryNode serviceANode;
+ private DiscoveryNode serviceBNode;
@BeforeClass public void setUp() {
threadPool = new ScalingThreadPool();
serviceA = new TransportService(new NettyTransport(threadPool), threadPool).start();
- serviceANode = new Node("A", serviceA.boundAddress().publishAddress());
+ serviceANode = new DiscoveryNode("A", serviceA.boundAddress().publishAddress());
serviceB = new TransportService(new NettyTransport(threadPool), threadPool).start();
- serviceBNode = new Node("B", serviceB.boundAddress().publishAddress());
+ serviceBNode = new DiscoveryNode("B", serviceB.boundAddress().publishAddress());
}
@AfterClass public void tearDown() {
diff --git a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyClient.java b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyClient.java
index ab8ad69f29876..b5fd824dbeddb 100644
--- a/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyClient.java
+++ b/modules/elasticsearch/src/test/java/org/elasticsearch/transport/netty/benchmark/BenchmarkNettyClient.java
@@ -20,7 +20,7 @@
package org.elasticsearch.transport.netty.benchmark;
import com.google.common.collect.Lists;
-import org.elasticsearch.cluster.node.Node;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.cached.CachedThreadPool;
import org.elasticsearch.transport.BaseTransportResponseHandler;
@@ -60,7 +60,7 @@ public static void main(String[] args) {
final ThreadPool threadPool = new CachedThreadPool();
final TransportService transportService = new TransportService(new NettyTransport(settings, threadPool), threadPool).start();
- final Node node = new Node("server", new InetSocketTransportAddress("localhost", 9999));
+ final DiscoveryNode node = new DiscoveryNode("server", new InetSocketTransportAddress("localhost", 9999));
transportService.nodesAdded(Lists.newArrayList(node));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.